如何使用ansible模板模块,从hostvars接收变量值?
在templates/config.py中:如何使用ansible模板模块,从hostvars接收变量值?,ansible,ansible-inventory,ansible-template,Ansible,Ansible Inventory,Ansible Template,在templates/config.py中: {% if env_value == 'Dev' %} {% set x = {{hostvars['ces_dev']['ansible_host']}} %} {% else %} {% set x = {{hostvars['ces_demo']['ansible_host']}} %} {% endif %} API_CONFIG = { 'api_email_url': 'http://{{x}}:8080/api/us
{% if env_value == 'Dev' %}
{% set x = {{hostvars['ces_dev']['ansible_host']}} %}
{% else %}
{% set x = {{hostvars['ces_demo']['ansible_host']}} %}
{% endif %}
API_CONFIG = {
'api_email_url': 'http://{{x}}:8080/api/users/mail',
}
在主机资源清册中:
ces_dev ansible_ssh_private_key=<path> ansible_host=a.b.c.d
ces_demo ansible_ssh_private_key=<path> ansible_host=x.y.z.w
我收到一个错误:“msg”:“AnsibleError:模板字符串时模板错误:应为标记“冒号”,得到“}”
如何解决这个问题并获得所需的输出?我自己用几个try-hit-error方法破解了预期的输出。解决方案是:
API_CONFIG = {
{% if env_value == 'Dev' %}
'api_email_url': 'http://{{hostvars['ces_dev']['ansible_host']}}:8080/api/users/mail',
'api_token_url': 'http://{{hostvars['ces_dev']['ansible_host']}}:8080/api/app/',
{% else %}
'api_email_url': 'http://{{hostvars['ces_demo']['ansible_host']}}:8080/api/users/mail',
'api_token_url': 'http://{{hostvars['ces_demo']['ansible_host']}}:8080/api/app/',
{% endif %}
}
默认情况下,变量是展开的
{% if env_value == 'Dev' %}
{% set x = hostvars.ces_dev.ansible_host %}
{% else %}
{% set x = hostvars.ces_demo.ansible_host %}
{% endif %}
API_CONFIG = {
'api_email_url': 'http://{{x}}:8080/api/users/mail',
}
请提供一个包含最小模板、剧本和数据的完整版本,以重现您的问题。错误最有可能出现在您的剧本或包含的变量(或我们没有看到的模板的一部分)中。谢谢!虽然我以不同的方式破解了它,但这也很有效。
{% if env_value == 'Dev' %}
{% set x = hostvars.ces_dev.ansible_host %}
{% else %}
{% set x = hostvars.ces_demo.ansible_host %}
{% endif %}
API_CONFIG = {
'api_email_url': 'http://{{x}}:8080/api/users/mail',
}