[英]How to set different environment variable for each client in Ansible playbook
I am trying to run a slightly different bash script on each ansible client, because each node needs to have a pre-set ID which has already been established.我试图在每个 ansible 客户端上运行一个稍微不同的 bash 脚本,因为每个节点都需要有一个已经建立的预设 ID。 In other words: The bash script looks for an environment variable, and I need that environment variable to be individually set for each Ansible host.
换句话说:bash 脚本寻找一个环境变量,我需要为每个 Ansible 主机单独设置该环境变量。
I have a list of identities in a file, which correspond to the host number.我有一个文件中的身份列表,与主机号相对应。
For example, in my inventory (/etc/ansible/hosts) I have:例如,在我的清单 (/etc/ansible/hosts) 中,我有:
[servergroupexample]
ansible-host-1 ansible_host=1.2.3.4
ansible-host-2 ansible_host=5.6.7.8
And in a file in /root/IDs.txt I have:在 /root/IDs.txt 的文件中,我有:
ID-asjdajdj399jad
ID-iajadijasijada
Where the line number in the IDs.txt corresponds to the ansible host number (eg ansible-host-2 should receive an environment variable which is set to the second line of IDs.txt)其中 IDs.txt 中的行号对应于 ansible 主机号(例如 ansible-host-2 应接收设置为 IDs.txt 的第二行的环境变量)
So it should be possible to grep for the number in the ansible host file (eg "ansible-host-1" returns "1") and then that 1 indicates which line to read from the IDs.txt and set as the environment variable on the host itself before running the script.因此,应该可以对 ansible 主机文件中的数字进行 grep(例如“ansible-host-1”返回“1”),然后 1 表示从 IDs.txt 读取哪一行并将其设置为环境变量在运行脚本之前主机本身。 How do I do that?
我怎么做?
Thanks!谢谢!
Q: "The bash script looks for an environment variable, and I need that environment variable to be individually set for each Ansible host."
问: “bash 脚本查找环境变量,我需要为每个 Ansible 主机单独设置该环境变量。”
A: Run once and create a dictionary from the lists with the dict and zip filters. A: 运行一次并使用dict 和 zip过滤器从列表中创建一个字典。 Then use
my_ID
to set the environment of the command for each host.然后使用
my_ID
为每个主机设置命令的环境。 For example例如
- hosts: servergroupexample
tasks:
- set_fact:
my_ID: "{{ dict(groups.servergroupexample|
zip(lookup('file', 'IDs.txt').splitlines())) }}"
run_once: true
- command: echo $MYID
register: result
environment:
MYID: "{{ my_ID[inventory_hostname] }}"
- debug:
var: result.stdout
with the inventory and IDs.txt带有库存和 IDs.txt
$ cat hosts
[servergroupexample]
test_01
test_02
$ cat IDs.txt
ID-asjdajdj399jad
ID-iajadijasijada
gives给
ok: [test_01] =>
result.stdout: ID-asjdajdj399jad
ok: [test_02] =>
result.stdout: ID-iajadijasijada
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.