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

How to export Ansible Inventory name to Server as variable

我正在尝试将服务器的 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。谢谢!

代码

- 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'] }}"

inventory_hostnameinventory_hostname_short 是您可用的 special variables 的一部分。

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

如果您的目标是配置目标主机名,您可以使用以下使用 hostname module

的剧本
- name: Set hostname of my machines
  hosts: servergroupexample

  tasks:
    - name: Set hostname
      hostname:
        name: "{{ inventory_hostname_short }}"