2016-05-22 153 views
1

我有一組定義FQDN的變量。Ansible循環嵌套變量

domains: 
    - erp: erp.mycompany.com 
    - crm: crm.mycompany.com 
    - git: git.mycompany.com 

事實上,我都需要遍歷它們並訪問它們(在模板文件中)。因此,像domains.erp這樣訪問它們就像是一種魅力。但我無法理順這些。

顯然,如果我做的:

- name: Print domains 
    debug: 
    msg: test {{ item }} 
    with_items: 
    - "{{ domains }}" 

它打印兩個鍵和值...如果我做的:

- name: Print domains 
    debug: 
    msg: test {{ domains[{{ item }}] }} 
    with_items: 
    - "{{ domain }}" 

但是,這並不工作。我也試過hashes form在文檔中提到,但沒有得到任何好運...

+1

Ansible似乎相當複雜的嵌套列表,請參閱我的問題在這裏:http://stackoverflow.com/questions/36206551/multiple-nested-loops-in-ansible。可能劇本不應該過度工程,或者你應該實現一些自定義插件,因爲語法變得非常討厭。 – allo

回答

1

最後,我不得不使用一個字典。

它沒有工作的第一次,因爲不像with_items,其中有項目會各自己的路線,with_dict是沒有-一個襯墊的元素來遍歷之前。

domains: 
    erp: 
    address: erp.mycompany.com 
    crm: 
    address: crm.mycompany.com 
    git: 
    address: git.mycompany.com 

# used by letsencrypt 
webserverType: apache2 
withCerts: true 

tasks: 

- name: Print phone records 
    debug: 
    msg: "{{ item.value.address }}" 
    with_dict: "{{ domains }}" 

# I can still access a given domain by its name when needed like so: 
{{ domains.erp.address }} 
0

看起來你已經發現了你的問題。您的原始嘗試使用不包含相同鍵的字典列表,因此很難在每個列表項中統一訪問這些值。

第二種解決方案創建一個字典,其中的密鑰引用其他字典。

比你貼什麼,如果你仍然想使用列表另一種解決方案:

- hosts: localhost 
     vars: 
     domains: 
      - name: erp 
      address: erp.mycompany.com 
      - name: crm 
      address: crm.mycompany.com 
      - name: git 
      address: git.mycompany.com 
     tasks: 
     - name: Print phone records 
      debug: 
      msg: "{{ item.address }}" 
      with_items: "{{ domains }}" 

對我來說,這種方法簡單,但你的第二個方法效果爲好。

+0

Thx爲答案。儘管如此,通過這種方法,我似乎無法通過名稱引用我的域名。如果在我的劇本的其他部分,我需要例如訪問erp的域名,我該如何解決它? 'domains.0.address'真的很容易出錯。 – Buzut

+1

你是對的。我誤解了你的用例。如果您需要單獨獲取域項目,而不僅僅是遍歷它們,那麼您的方法可能是最可靠的方法。 – barnesm999