如何将 Ansible 清单名称作为变量导出到服务器



我正在尝试将服务器的 Ansible 清单名称传达给服务器本身,因此我可以在将服务器的主机名更改为相同名称的脚本中使用该名称。将其发送到文件或环境变量会很好用。

例如,在我的清单(/etc/ansible/hosts(中,我有:

[servergroupexample]
host1 ansible_host=1.2.3.4
host2 ansible_host=5.6.7.8

我想以某种方式向 1.2.3.4 传达他的名字是"host1",5.6.7.8 她的名字是"host2",这样我就可以在脚本中引用这些名称并将它们的主机名分别设置为 host1/host2。谢谢!

inventory_hostnameinventory_hostname_short是您可以使用的特殊变量的一部分。

对于这种特定情况,我建议您使用inventory_hostname_short这样,如果您以后决定以主机的完整 fqdn 名称命名主机(例如 host3.mydomain.com(,以下示例仍然有效

如果您的目标是配置目标主机名,则可以使用以下使用hostname模块的 playbook

- name: Set hostname of my machines
hosts: servergroupexample
tasks:
- name: Set hostname
hostname:
name: "{{ inventory_hostname_short }}"

代码

- name: Loop through example servers and show the hostname, ansible_host attribute
debug:
msg: "ansible_host attribute of {{ item }} is {{ hostvars[item]['ansible_host'] }}"
loop: "{{ groups['servergroupexample'] }}"

结果

ok: [localhost] => (item=host1) => {
"msg": "ansible_host attribute of host1 is 1.2.3.4"
}
ok: [localhost] => (item=host2) => {
"msg": "ansible_host attribute of host2 is 5.6.7.8"
}

您可以将任务从调试更改为 shell 或模板等。

仅输出匹配的ansible_host:

- name: Loop through example servers and show the hostname, ansible_host attribute
debug:
msg: "ansible_host attribute of {{ item }} is {{ hostvars[item]['ansible_host'] }}"
when: ansible_host == hostvars[item]['ansible_host']
loop: "{{ groups['servergroupexample'] }}"

相关内容

最新更新