如何使用Ansible进行多条件循环?

时间:2017-12-07 12:45:07

标签: ansible jinja2

我有rolesusers。我想循环查看包含roles的{​​{1}} users

state=present

我正在尝试使用过滤器并仅使用iam_roles: - name: "developers-role" assume_role_policy_document: "developers" state: present managed_policy: - arn:aws:iam::XXXXXXXXXXX:policy/CustomAmazonS3ReadOnlyAccess - name: "bigdata-role" assume_role_policy_document: "bigdata" state: present managed_policy: - arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess - arn:aws:iam::XXXXXXXXXXX:policy/CustomAmazonRDSReadOnlyAccess iam_users: - name: test-user-1 state: present groups: [developers] password: slack_name: access_key_state: create - name: test-user-2 state: present groups: [developers] password: slack_name: 获取users并在我的state=present子句中使用它,但到目前为止没有运气

when

1 个答案:

答案 0 :(得分:0)

使用debug语句尝试提取用户似乎很奇怪。如果要根据属性的值从列表中选择对象,则最佳选择可能是Jinja2 selectattr过滤器。例如,给定此输入:

iam_users:
  - name: test-user-1
    state: present
    groups: [developers]
    password:
    slack_name:
    access_key_state: create

  - name: test-user-2
    state: present
    groups: [developers]
    password:
    slack_name:

  - name: test-user-3
    state: absent
    groups: [developers]
    password:
    slack_name:

您可以使用此set_fact任务:

- set_fact:
    iam_present_users: "{{ iam_users|selectattr('state', 'equalto', 'present')|list }}"

哪会导致iam_present_users包含:

"iam_present_users": [
    {
        "access_key_state": "create", 
        "groups": [
            "developers"
        ], 
        "name": "test-user-1", 
        "password": null, 
        "slack_name": null, 
        "state": "present"
    }, 
    {
        "groups": [
            "developers"
        ], 
        "name": "test-user-2", 
        "password": null, 
        "slack_name": null, 
        "state": "present"
    }
]

有关过滤器的库存列表,请参见the jinja documentation;有关ansible特定的过滤器列表,请参见the ansible documentation