下面的剧本应该生成一个包含以下内容的文件:
a,b
ssh_host_key
ssh_rsa_host_key
但是,我构造变量名的方式导致语法/模板错误或“变量名不存在”:
---
- hosts: localhost
connection: local
vars:
CentOS:
ciphers: "a,b"
hostkeys:
- "ssh_host_key"
- "ssh_rsa_host_key"
tasks:
- copy:
dest: "{{ playbook_dir }}/test.out"
content: |
# This works:
{{ CentOS.ciphers }}
# This results in 'No variable found with this name':
{{ lookup('vars', ansible_distribution + '.ciphers') }}
# Templating errors:
{% for hostkey in {{ lookup('vars', ansible_distribution + '.hostkeys') }} %}
{{ hostkey }}
{% endfor %}
# Templating errors:
{% for hostkey in {{ hostvars[inventory_hostname][ansible_distribution + '.hostkeys'] }} %}
{{ hostkey }}
{% endfor %}
“组装”变量名称的正确方法是什么?或者有更好的方法吗?
答案1
Ansible 新闻组的 Martin Krizek 回答了我的问题。正确的语法是:
---
- hosts: localhost
connection: local
vars:
CentOS:
hostkeys:
- "ssh_host_key"
- "ssh_rsa_host_key"
tasks:
- copy:
dest: "{{ playbook_dir }}/test.out"
content: |
{% for hostkey in lookup('vars', ansible_distribution)['hostkeys'] %}
{{ hostkey }}
{% endfor %}