Ansible迭代数组并使用过滤器

时间:2018-05-02 15:21:04

标签: ansible yaml jinja2 ansible-2.x

我对ansible在下面的情景中寻求帮助有点新意。我要做的是迭代数组'access_key_ids'并运行regex_search过滤器。对于regex_search过滤器参数是'item',它是来自with_items的变量。下面这种方式不起作用就是我正在尝试的。

name: Set Fatcs

  block:

   # extract access key ids from get event response

   - set_fact:

      event_response_access_key_ids: "{{event_response_access_key_ids}} + [{{event_response.content | regex_search(item)}}]"

     with_items: "{{access_key_ids}}"

   # check if the response contains access key id for the license

   - set_fact:

      scwx_output: "{{ (event_response_access_key_ids | length > 0 ) | ternary(event_response, 'License Key does not match with available sensors')}}"

  when: event_response.json is undefined

它将event_response_access_key_ids设为空。但是当我硬编码一个值而不是'item'时它会起作用

感谢。

1 个答案:

答案 0 :(得分:0)

我一直在测试这个解决方案:

---
- name: Test
  hosts: local
  gather_facts: False

  vars:
    event_response:
      content: "hi1"
    access_key_ids:
     - "1"
     - "h"
     - "3"

  tasks:

    - name: Fact
      set_fact:
        event_response_access_key_ids: "{{ event_response_access_key_ids|default([]) + [ event_response.content | regex_search( item ) ] }}"
      with_items: "{{ access_key_ids }}"

它正确地得到了变种:

    ok: [localhost] => (item=1) => {
    "ansible_facts": {
        "event_response_access_key_ids": [
            "1"
        ]
    }, 
    "changed": false, 
    "item": "1"
}
ok: [localhost] => (item=h) => {
    "ansible_facts": {
        "event_response_access_key_ids": [
            "1", 
            "h"
        ]
    }, 
    "changed": false, 
    "item": "h"
}
ok: [localhost] => (item=3) => {
    "ansible_facts": {
        "event_response_access_key_ids": [
            "1", 
            "h", 
            null
        ]
    }, 
    "changed": false, 
    "item": "3"
}