是否可以在运行时定义var并使用它来访问另一个var?

时间:2017-04-25 10:55:04

标签: ansible jinja2 ansible-template

我不确定这是可能的。

我想在运行时定义一个var并使用它来访问另一个var(在文件,playbook中定义..)。

  1. 在运行时定义:

    typeConfig (possible values: "in_config" or "out_config")
    
  2. 在剧本中定义
  3. in_config:
      url_config: http://localhost/configuration
    
    out_config:
      url_config: http://config.pi.dyn-dns.org/configuration
    
  4. 我需要解决类似的问题:

    {{ {{ typeConfig }}.url_config }}
    

    我尝试:

    - name: Mytest
      hosts: all
      gather_facts: false
      sudo: yes
      vars:
        - in_config:
             url_config: http://localhost/configuration
        - out_config:
             url_config: http://config.pi.dyn-dns.org/configuration
      tasks:
         - set_fact:
              typeConfig: in_config
         - name: Value in_config.url_config
           debug: msg=" {{in_config.url_config}}"
    
         - name: Value out_config.url_config
           debug: msg=" {{out_config.url_config}}"
    
         - name: Value typeConfig
           debug: var=typeConfig
    
         - debug: msg="{{ {{ typeConfig }}.url_config }} "
    

    实际结果

      

    任务路径:/home/nor/gitrepos/iiot-iac/ansible/myUnitTest.yml:19   致命:[node1]:失败了! => {       "失败":是的,       " msg":"模板错误,模板字符串:期望令牌':',得到'}'。字符串:{{{{typeConfig}}。url_config}}" }" }

1 个答案:

答案 0 :(得分:1)

您可以使用以下方式访问该值:

- debug:
    msg: "{{ vars[typeConfig].url_config }}"

请记住,{{ ... }}不是编写变量名的方法,而是启动Jinja2表达式。在查询值时,使用Ansible中的Jinja2表达式引用变量,因此使用{{ {{ ... }} }}没有意义。

相关问题