2017-04-25 22 views
0

我不確定這是可能的。是否可以在運行時定義一個var並使用它來訪問另一個var?

我想在運行時定義一個var並使用它來訪問另一個var(在文件,playbook中定義)。

  1. 在運行時定義:

    typeConfig (possible values: "in_config" or "out_config") 
    
  2. 在劇本中定義:

    in_config: 
        url_config: http://localhost/configuration 
    
    out_config: 
        url_config: http://config.pi.dyn-dns.org/configuration 
    

我需要解決類似這樣:

{{ {{ 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 致命:[節點1]:失敗! => { 「failed」:true, 「msg」:「template template error while templating string:expected token':',got'}'。String:{{{typeConfig}}。url_config}}」}「}

回答

1

您可以通過訪問該值:

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

記住{{ ... }}不是寫一個變量名的方式,而是開始Jinja2的表達和查詢值時,變量。在Ansible中使用Jinja2表達式引用,因此使用{{ {{ ... }} }}是沒有意義的。

相關問題