2016-11-10 53 views
0

從另一個字典收集字典我有一些字典:在Ansible

users_to_add: 
    - username: Harley Quinn 
     login: 90987264 
     group: mininform 
     group_desc: "Some random data for description" 
     personal_data: 
     - first_name: Harley 
      last_name: Quinn 
      mail: [email protected] 
      telnum: +7777777777 
      jobtitle: minister 
    - username: Vasya Pupkin 
     login: 77777777 
     group: mininform 
     group_desc: "Some random data for description" 
     personal_data: 
     - first_name: Vasya 
      last_name: Pupkin 
      mail: [email protected] 
      telnum: +7970000000 
      jobtitle: minister 

而且我有隻列出工作ansible模塊:

- name: Create needed groups 
    ipa_group: 
     state: present 
     name: "{{ item.group }}" 
     description: "{{ item.group_desc }}" 
     ipa_host: "{{ global_host }}" 
     ipa_user: "{{ global_user }}" 
     ipa_pass: "{{ global_pass }}" 
     validate_certs: no 
     user: [] 
    with_items: 
     - "{{ users_to_add }}" 

該模塊要在「用戶」的用戶列表參數,創建一個組並添加用戶。我想像這樣映射字典「users_to_add」: (使用users_to_add字典) {group_name: ["user1", "user2"...]}並將此新字典添加到模塊中。 我如何用ansible來完成這項工作? 我知道,首先我應該使用

set_fact: 
    new_dict: 
with_items: {{ users_to_add }} 

...

再喂這個新字典的模塊,其中關鍵的是組名創造和價值 - 要添加到組的用戶列表中,但我不明白如何與ansible做到這一點...

+0

很難理解你想在這裏...'ipa_g達到什麼roup'模塊創建組併爲其分配用戶。但是你遍歷'users_to_add'而不是組。請編輯你的問題,確切地說你想創建哪些組名包含哪些用戶名。 –

+0

我想迭代users_to_add字典,並在新字典中收集所有組名和用戶登錄,其中:{group:[擁有此組的所有用戶],group:...} – Mizeraj

回答

0

試試這個:

- name: Create needed groups 
    ipa_group: 
     state: present 
     name: "{{ item }}" 
     description: "{{ users_to_add | selectattr('group','equalto',item) | map(attribute='group_desc') | list | first }}" 
     ipa_host: "{{ global_host }}" 
     ipa_user: "{{ global_user }}" 
     ipa_pass: "{{ global_pass }}" 
     validate_certs: no 
     user: "{{ users_to_add | selectattr('group','equalto',item) | map(attribute='username') | list }}" 
    with_items: "{{ users_to_add | map(attribute='group') | list | unique }}" 
+0

非常感謝 - 它按預期工作) – Mizeraj