【问题标题】:Ansible - conditions in group_var fileAnsible - group_var 文件中的条件
【发布时间】:2017-06-02 03:40:30
【问题描述】:

我有一个场景,我需要根据运行 ansible playbook 时传递的名为“provider”的字符串参数在组 var 中设置一个变量。

ansible 2.3.0.0,python 版本 = 2.7.5 在 groups_vars.yml 中,这就是我想要实现的目标

if provider=azure then
insecure_registrys: ['{{azure_ip.state.ip_address}}:5000'] else if
provider=vsphere then
insecure_registrys: ['11.168.25.xx:5000']

我在 github 中检查了一个问题后正在尝试这种方式

insecure_registrys: "{{ ( true | ternary('['{{azure_ip.state.ip_address}}:5000']','['11.168.25.xx:5000']'))}}"

上面的true稍后会被provider check替换。它通过了语法检查但在中间失败

失败了! => {"failed": true, "msg": "{% if etcd_interface != '' %}{{ hostvars[inventory_hostname]['ansible_' + etcd_interface].ipv4.address }}{%- else %}{ { hostvars[inventory_hostname].ansible_default_ipv4.address }}{% endif %}:模板错误,而模板字符串:预期令牌',',得到'{'。字符串:{{(真|三元('['{{azure_ip. state.ip_address}}:5000']','['11.168.25.xx:5000']'))}}"}

你能在这种情况下帮助我吗?谢谢

【问题讨论】:

    标签: python ansible jinja2


    【解决方案1】:

    永远不要使用嵌套的 Jinja2 表达式,更简单:

    insecure_registries: "{{ [azure_ip.state.ip_address+':5000'] if provider == 'azure' else ['11.168.25.xx:5000'] }}
    

    并且使用三元过滤器:

    insecure_registries: "{{ (provider == 'azure') | ternary( [azure_ip.state.ip_address+':5000'], ['11.168.25.xx:5000'] ) }}
    

    【讨论】:

    • 嗨康斯坦丁,看起来三元运算符在检查为真之前评估了条件的双方。因此,即使传递的提供者是 vsphere,我也会收到此错误“'dict object' has no attribute 'state'”。试图声明“azure_ip.state.ip_address : state: ip_address: test in all.yml”,但仍然失败。我是否需要强制声明,如果需要,在这些情况下哪个是最好的地方?
    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    相关资源
    最近更新 更多