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