Ansible:如何引用特定键的变量

时间:2016-06-06 08:58:05

标签: loops variables ansible

我有一个host_vars文件,如下所示:

---
clients:
cl1:
  to_install:
  - value11
  - value21
  to_uninstall:
  - value31
cl3:
  to_install:
  - value12
  - value22
  - value32
  to_uninstall:
  - value42

我希望cl1/to_install下列出的值仅安装到cl1客户端,而cl3/to_install下的值仅安装到cl3。这应该通过循环to_install中包含的值来完成。 cl1和cl3也在hosts文件中定义。 我正在尝试打印值:

- name: test variables...
  hosts: localhost
  vars_files:
    - path/to/hosts_vars
tasks:
- name: Print softwares to install
  debug: msg="Softwares installed on {{ item.key }} are: {{ item.value.to_install }}"
  with_dict:
    - "{{ clients }}"

但这会打印两个客户端的to_install。我也可以明确地引用客户端(例如用cl1代替密钥),但host_vars中定义的客户端数量每次都会改变。我怎么才能引用特定客户的to_install中的值?谢谢

1 个答案:

答案 0 :(得分:1)

我想,你看起来像这样:

---
clients:
  cl1:
    name: My-First-Machine
    to_install:
      - value11
      - value21
    to_uninstall:
      - value31
  cl3:
    name: My-Second-Machine
    to_install:
    - value12
    - value22
    - value32
    to_uninstall:
    - value42

然后在你的剧本中这样:

  tasks:
    - debug:
        msg: "Softwares installed on {{ clients[machine].name }} are: {{ clients[machine].to_install }}"

然后你可以像cl1机器一样使用这样的剧本:

ansible-playbook -i hosts test.yml -e "machine=cl1"

会给你这样的结果:

ok: [localhost] => {
    "msg": "Softwares installed on My-First-Machine are: [u'value11', u'value21']"
}

PLAY RECAP *********************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0

此外,您可以将这样的剧本用于cl3机器:

ansible-playbook -i hosts test.yml -e "machine=cl3" 

会给你这样的结果:

PLAY [local] *******************************************************************

TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": "Softwares installed on My-Second-Machine are: [u'value12', u'value22', u'value32']"
}

PLAY RECAP *********************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0

希望这对你有所帮助。