Shenali Silva
Shenali Silva

Reputation: 137

Ansible iterate over array and use filter

I'm kinda new to ansible seeking help with below scenario. what I'm trying to do is iterate over the array 'access_key_ids' and run regex_search filter. for the regex_search filter argument is 'item' which is the variable from with_items. It does not work this way below is what I'm trying.

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

It gives event_response_access_key_ids as empty. but when I hard code a value instead of 'item' it works

Thanks.

Upvotes: 0

Views: 913

Answers (1)

imjoseangel
imjoseangel

Reputation: 3926

I've been testing this solution:

---
- 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 }}"

And It gets the vars properly:

    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"
}

Upvotes: 1

Related Questions