2017-08-08 44 views
0

要開始了我在YAML定義我所有的變量Ansible,遍歷多個寄存器,並在方法長時間使用積累的

app_dir: "/mnt/{{ item.name }}" 
app_dir_ext: "/mnt/{{ item.0.name }}" 
workstreams: 
    - name: tigers 
    service_workstream: tigers-svc 
    app_sub_dir: 
     - inbound 
     - inbound/incoming 
     - inbound/error 
     - inbound/error/processed 
    - name: lions 
    service_workstream: lions-svc 
    app_sub_dir: 
     - inbound 
     - inbound/incoming 
     - inbound/error 
     - inbound/error/processed 

你可能注意到app_dir: "/mnt/{{ item.name }}"app_dir_ext: "/mnt/{{ item.0.name }}"看着奇怪,所以我本來有我的變量在YAML中設置如下,但是當我有大量工作流時,決定使用上述內容主要是由於YAML中的行數較少。

workstreams: 
    - name: tigers 
    service_workstream: tigers-svc 
    app_dir: /mnt/tigers 
    ... 

我再有Ansible代碼來檢查目錄存在,如果不能創建和應用權限(!注意,採取這種方法由於對操作的SSH超時使用上一個數字的file:模塊時非常大的NFS掛載份額)。

- name: Check workstreams app_dir 
    stat: 
    path: "{{ app_dir }}" 
    register: app_dir_status 
    with_items: 
    - "{{ workstreams }}" 

- name: Check workstreams app_sub_dir 
    stat: 
    path: "{{ app_dir_ext }}/{{ item.1 }}/" 
    register: app_sub_dir_status 
    with_subelements: 
    - "{{ workstreams }}" 
    - app_sub_dir 

- name: create workstreams app_dir 
    file: 
    path: "/mnt/{{ item.0.name }}" 
    state: directory 
    owner: "ftp" 
    group: "ftp" 
    mode: '0770' 
    recurse: yes 
    with_nested: 
    - '{{ workstreams }}' 
    - app_dir_status.results 
    when: 
    - '{{ item.1.stat.exists }} == false' 

這是一個小哈克,但不過工作,我有第二,第三,第四路在這裏check..etc

我的問題是,如何我更新/重構上面的代碼中使用<register_name>.stat.exists == falseapp_dir_statusapp_sub_dir_status來控制我的任務?

回答

0

你不需要做嵌套循環! app_sub_dir_status內有所有必需的數據 - 只需剝離不需要的項目。

這裏的簡單例子:

--- 
- hosts: localhost 
    gather_facts: no 
    vars: 
    my_list: 
     - name: zzz1 
     sub: 
      - aaa 
      - ccc 
     - name: zzz2 
     sub: 
      - aaa 
      - bbb 
    tasks: 
    - stat: 
     path: /tmp/{{ item.0.name }}/{{ item.1 }} 
     register: stat_res 
     with_subelements: 
     - "{{ my_list }}" 
     - sub 
    - debug: 
     msg: "path to create '{{ item }}'" 
     with_items: "{{ stat_res.results | rejectattr('stat.exists') | map(attribute='invocation.module_args.path') | list }}" 

您可以通過stat_res.results | rejectattr('stat.exists') | list迭代爲好,但必須重新構建路徑/tmp/{{ item.item.0.name }}/{{ item.item.1 }} - 注意雙item,因爲第一item是包含另一個item作爲stat_res.results元素stat任務的原始循環元素。

P.S.我也沒有看到你的第一個任務的理由,因爲subdir任務可以檢測到所有丟失的目錄。