如何使用具有来自hostvars的可变接收值的ansible模板模块?

How to use ansible template module with variable receiving value from hostvars?

在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/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

预期输出,如果满足条件:

API_CONFIG = {
        'api_email_url': 'http://a.b.c.d:8080/api/users/mail',
    }

我收到一个错误:"msg": "AnsibleError: template error while templating string: expected token 'colon', got '}'

如何解决这个问题并获得所需的输出?

我自己破解了预期的输出,使用了几种尝试-命中-错误的方法。解决方案是:

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',
}