问题
For example, I want to find all nodes with a certain tag, grab their IP address, then generate a config file to distribute to those nodes.
A use case might be a database that needs to know about every other node, but can have nodes added and removed at any time.
回答1:
You can use Salt Mine to do it. First, distribute this configuration to all the Minions:
mine_functions:
grains.item:
- roles
- fqdn_ip4
With that configuration, every Minion will publish those two grains to all other minions. More details about Mine here.
Now, we can create a file with all the names with role=db.
/tmp/mydbhosts:
file:
- managed
- source: salt://example/myhosts
- template: mako
The template example/myhosts:
% for minion, peer_grains in salt['mine.get']('*', 'grains.items').items():
% if "db" in peer_grains["role"]:
minion peer_grains["fqdn_ip4"]
% endif
% endfor
回答2:
I have a hacky solution, so hopefully someone else can find a better answer.
The approach is to create a Python script that runs salt
to grab the YAML output of network.ip_addrs eth0
then use that to call a particular sls with a pillar.
I made an example prototype which still needs to be implemented and tweaked:
#!/usr/bin/env python
import subprocess
import yaml
# Query all db nodes for their ip addresses
data = subprocess.check_output(
'salt -G "role:db" network.ip_addrs eth0',
shell=True
)
data = yaml.load(data)
# Parse and reshuffle for pillar input
addrs = []
for a in data.values():
addrs.append(a[0])
addrs = yaml.dump({'db_peers': addrs})
# Update configuration file on each node
data = subprocess.check_output(
'salt -G "role:db" state.sls db.configure pillar="{}"'.format(addrs),
shell=True
)
This will execute something along the lines of:
salt -G "role:db" state.sls db.configure pillar="db_peers: [1.2.3.4, 2.3.4.5]"
This could potentially be put into a module, but I'm not sure how to nicely ask salt-minion to communicate to the master to run db.configure
on other nodes. I could simply execute the command similar to the script above.
来源:https://stackoverflow.com/questions/20897796/using-the-output-of-salt-to-be-used-as-input-for-an-sls-state-or-pillar