在迭代with_item调试列表时如何通过传递when条件来执行Ansible任务?

时间:2020-02-22 14:40:39

标签: loops debugging ansible conditional-statements

我正在尝试根据用户的with_item列表上的when条件执行API POST。从API GET收集when条件,然后将其存储为调试变量。

问题:似乎调试变量没有正确迭代,并且API POST任务仅遵循第一个结果。这将导致尝试对with_items列表中的所有项目执行POST,或者跳过所有项目。

我不知道每个“ request_ad_user”是否正在创建一个新变量,以及如何在“ when”条件下对其进行迭代。我想念什么?

这是我的代码:

- name: Add a users to univention AD server.
  hosts: localhost

  tasks:
      - name: Include user to add as variable
        include_vars:
            file: users.yaml
            name: users

      - name: Check if AD users exist (object DN)
        uri:
          url: https://10.10.10.10/univention/udm/users/user/uid%3D{{item.username}}%2Ccn%3Dusers%2Cdc%3Dcybertax%2Cdc%3Dcso%2Cdc%3Dcom
          user: admin
          password: "{{users.adminpw}}"
          validate_certs: no
          return_content: yes
          status_code: 200,404
          method: GET
          timeout: 10
        with_items:
          - "{{users.user}}"
        register: request_ad_user

      - name: debug univention user object DN request
        debug:
          var: request_ad_user

      - name: Add AD user accounts
        uri:
          url: https://10.10.10.10/univention/udm/users/user/
          user: admindh
          password: "{{users.vcenterPassword}}"
          validate_certs: no
          return_content: yes
          status_code: 201
          method: POST
          body: "{\"uuid\": \"string\", \"uri\": \"https://10.104.8.110/univention/udm/users/user/uid={{item.username}},dc=cybertax,dc=cso,dc=com\", \"options\": {\"pki\": false}, \"policies\": {\"pol
          body_format: json
        when:
          - request_ad_user.results[0].status == 404
        with_items:
          - "{{users.user}}"

1 个答案:

答案 0 :(得分:1)

尝试添加循环索引,并在when子句中使用该索引:

  - name: Add AD user accounts
    uri:
      url: https://10.10.10.10/univention/udm/users/user/
      user: admindh
      password: "{{users.vcenterPassword}}"
      validate_certs: no
      return_content: yes
      status_code: 201
      method: POST
      body: "{\"uuid\": \"string\", \"uri\": \"https://10.104.8.110/univention/udm/users/user/uid={{item.username}},dc=cybertax,dc=cso,dc=com\", \"options\": {\"pki\": false}, \"policies\": {\"pol
      body_format: json
    when:
      - request_ad_user.results[ndx].status == 404
    with_items:
      - "{{users.user}}"
    loop_control:
      index_var: ndx