如何将库存组别名分配给变量?

如何将库存组别名分配给变量?

我有这个 Ansible 库存文件:

[fileservers]
fs01.example.com   ansible_ssh_host=192.168.1.1    ip_addr=192.168.1.1

[dbservers]
db01.example.com   ansible_ssh_host=192.168.1.2    ip_addr=192.168.1.2

[webservers]
web01.example.com   ansible_ssh_host=192.168.1.3    ip_addr=192.168.1.3

[cmsservers]
cms01.example.com   ansible_ssh_host=192.168.1.4    ip_addr=192.168.1.4

我想要做的是,当我在 web01.example.com 服务器上运行此剧本时,能够设置一些包含主机别名的事实:

- name: create alias facts
  set_fact:
    file_server_alias: hostvars[{{ inventory_hostname }}]['groups']['fileservers'][0]  # should get string 'fs01.example.com'
    db_server_alias: hostvars[{{ inventory_hostname }}]['groups']['dbservers'][0]      # should get string 'db01.example.com'
    cms_server_alias: hostvars[{{ inventory_hostname }}]['groups']['cmsservers'][0]    # should get string 'cms01.example.com'

但是,当我执行上述操作时,file_server_alias 只会设置为“hostvars[{{ inventory_hostname }}]['groups']['fileservers'][0]”,依此类推。有没有办法将这些库存组别名分配给变量?

答案1

您需要将整个赋值表达式放在胡子里面。此示例适用于 ansible-playbook 2.5.1 和 Python 2.7

---
- hosts: fileservers
  gather_facts: no
  tasks:
        - name: create alias facts
          set_fact:
            file_server_alias: "{{ hostvars[inventory_hostname]['groups']['fileservers'][0] }}" # should get string 'fs01.example.com'
            db_server_alias: "{{ hostvars[inventory_hostname]['groups']['dbservers'][0] }}"      # should get string 'db01.example.com'
            cms_server_alias: "{{ hostvars[inventory_hostname]['groups']['cmsservers'][0] }}"    # should get string 'cms01.example.com'
        - name: debug
          debug:
            msg: "{{ file_server_alias }} {{ db_server_alias }} {{ cms_server_alias }}"

输出:

$ ansible-playbook -i inventory playbook.yml 

PLAY [fileservers] *********************************************************************************************************************************************************************************************************************************************

TASK [create alias facts] **************************************************************************************************************************************************************************************************************************************
ok: [fs01.example.com]

TASK [debug] ***************************************************************************************************************************************************************************************************************************************************
ok: [fs01.example.com] => {
    "msg": "fs01.example.com db01.example.com cms01.example.com"
}

PLAY RECAP *****************************************************************************************************************************************************************************************************************************************************
fs01.example.com           : ok=2    changed=0    unreachable=0    failed=0   

相关内容