How to use the IP addresses of the machines matching the grain in the Salt state file
I am creating a formula / state file that adds a rule iptables
:
ipt_allow:
iptables.append:
- table: filter
- chain: INPUT
- jump: ACCEPT
- match: state
- connstate: 'NEW,ESTABLISHED'
- dport: 6666
- proto: tcp
- source: 'ip1, ip2, ip3, ...'
I don't want to hard-code IP addresses into source
. ip1
, ip2
and ip3
are the IP addresses of the minions that match the grain role:role1
. This way, if I ever add more grain minions role1
down the road, they will be added to the iptables rule after rerunning this state file. How to do it?
source to share
Got it. This can be done using the functions of the salt mine.
-
/srv/pillar/mines.sls
:mine_functions: network.ip_addrs: - eth1
This makes it accessible
network.ip_addrs
to the master and minions, in particular to the interfaceeth1
. -
/srv/pillar/top.sls
:base: '*': - mines
This applies to the column (hence the mine function) to all minions.
-
Now you can use a function
mine.get
in your state files to call this mine function. This is what I used in my case:{% for server, addrs in salt ['mine.get'] ('role: role1', 'network.ip_addrs', expr_form = 'grain'). items ()%} ipt_allow _ {{server}}: iptables.append: - table: filter - chain: INPUT - jump: ACCEPT - match: state - connstate: 'NEW, ESTABLISHED' - dport: 6666 - proto: tcp - source: {{addrs [0]}} {% endfor%}
Where:
-
salt['mine.get']
calls a functionmine.get
, -
('role:role1', 'network.ip_addrs', expr_form='grain').items()
specifies the function to match minions that haverole1
as valuerole
that is grain (expr_form='grain'
) and gets itnetwork.ip_addrs
. - The output is the consistent minion id (I believe) and the result
network.ip_addrs
, so we store it inserver
andaddrs
. - The loops
for
go around creating a new ID each time using the value in{{ server }}
and replacing the IP address in{{ addrs[0] }}
.
-
Links that helped:
source to share