删除不在词典中的用户

时间:2019-10-17 18:14:41

标签: json ansible jinja2

我在ansible中有一个任务,该任务返回包含用户列表的字典,并使用它通过服务器中的另一个任务来添加这些用户。

- name: Get users
  uri:
    url: http://users.com/users
    method: GET
    return_content: yes
  register: json_users

-name: Add users
 user:
   name: "{{ item }}"
 with_items:
   - {{ json_users[content] }}

现在,我想删除不在此列表中的用户,但我不知道如何提出此任务。

我的列表是这样的:

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    },
    "phone": "010-692-6593 x09125",
    "website": "anastasia.net",
    "company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }
  },

现在,想象一下,除了用户列表之外,我在服务器中还有更多用户。可以创建另一个任务来删除该任务吗?我愿意使用任何方法。

谢谢

1 个答案:

答案 0 :(得分:0)

ansible在模块中提供了一个非常出色的参数,称为state:。此参数可用于控制模块在目标节点上的行为,即不存在/存在,即在用户情况下删除/添加。

在使用user:作为参数调用delete模块之前,您需要创建目标节点上所有用户的列表,然后将其与上述json中的用户进行比较,然后调用user:个模块,其参数为delete:

- name: Get users
  uri:
    url: http://users.com/users
    method: GET
    return_content: yes
  register: json_users

- name: Add users
 user:
   name: "{{ item }}"
 with_items:
   - "{{ json_users[content] }}"

- name: create a list of users not present in the above json
  <module>:

- name: Add users
 user:
   name: "{{ item }}"
 state: absent
 remove: yes
 with_items:
   - "{{ to_delete_list }}"

希望如此有帮助。让我知道,如果您需要帮助以创建json中不存在的用户列表。此外,{{ json_users[content] }}将在with_items中作为迭代获得所有关键字,您只需要名称attribute即可与user模块一起使用。

除上述内容外,我们还可以使用模块getent:获取用户列表,这将设置一个名为getent_passwd:的事实,我们可以解析此代码以获取username

使用username:作为关键字,创建了预期用户列表。

---
- name: to delete the users not needed as per the json
  hosts: localhost
  gather_facts: no
  tasks:
    - include_vars: 
        file: vars.yml
        name: expected

    - getent:
        database: passwd
      register: list_of_users

    - set_fact:
        expected_users: "{{ expected_users | default([]) | map(attribute='item') | list }}"
      loop:
        - "{{ expected | json_query('expected[*].username')  }}"

    - debug:
        msg: "{{ item.key }}"
      when: "item.key not in expected_users"
      with_dict:
        - "{{ getent_passwd }}"

您可以将debug:更新为将user:模块与state: absent一起使用

注意:删除用户时要小心