polxpolx
polxpolx

Reputation: 115

Ansible set_fact array and populate it from in loop

I want to create an array and insert value from the the array IP_TO_DNS to reversed IP address.

The idea is to restructure the IP address given in the argument to be matchable later in my code.

Code

- name: create array reversed
  set_fact: reversed_ip=[]

- name: set convert ips from cli to matchable reversed ip
  set_fact: reversed_ip='{{ item | regex_replace('^(?P<first_range>\d{1,3})\.(?P<second_range>\d{1,3})\.(?P<third_range>\d{1,3})\.', 'named.\\g<third_range>.\\g<second_range>.\\g<first_range>')}}'
  with_items: '{{IP_TO_DNS}}'

- name: Match first block of results in path name
  debug: var=item
  with_items: '{{reversed_ip}}'

Output

TASK [dns : set convert ips from cli to matchable reversed ip] *****************
ok: [10.1.10.5] => (item=10.1.10.1)
ok: [10.1.10.5] => (item=10.1.10.2)
ok: [10.1.10.5] => (item=10.1.10.3)

TASK [dns : Match first block of results in path name] *************************
ok: [10.1.10.5] => (item=named.10.1.103) => {
    "item": "named.10.1.103"
}

It look like my variable is not set as an array and only the first value is populate.

Any ideas ?

Upvotes: 7

Views: 32959

Answers (3)

Ho Tommy
Ho Tommy

Reputation: 31

You can assign the default of reversed_ip as a list and append the item to the list.

- name: set convert ips from cli to matchable reversed ip
  set_fact: reversed_ip='{{ reversed_ip |default([]) + [item | regex_replace('^(?P<first_range>\d{1,3})\.(?P<second_range>\d{1,3})\.(?P<third_range>\d{1,3})\.', 'named.\\g<third_range>.\\g<second_range>.\\g<first_range>')] }}'
  with_items: "{{ IP_TO_DNS }}"

- name: Match first block of results in path name
  debug: var=item
  with_items: '{{reversed_ip}}'

Upvotes: 2

santosh
santosh

Reputation: 111

This is the one of the ways which I used

vars:
   my_new_list: []
tasks:
 - name: Get list of elements from list_vars
   set_fact:
     my_new_list: "{{ my_new_list + [item] }}"
  with_items: "{{ list_vars }}"

Upvotes: 11

techraf
techraf

Reputation: 68649

You are setting the same fact three times and it gets overwritten.

You should register the output:

- name: set convert ips from cli to matchable reversed ip
  set_fact: reversed_ip='{{ item | regex_replace('^(?P<first_range>\d{1,3})\.(?P<second_range>\d{1,3})\.(?P<third_range>\d{1,3})\.', 'named.\\g<third_range>.\\g<second_range>.\\g<first_range>')}}'
  with_items: '{{IP_TO_DNS}}'
  register: reversed_ip_results_list

- name: Match first block of results in path name
  debug: var=item.ansible_facts.reversed_ip
  with_items: '{{reversed_ip_results_list.results}}'

or if you want a list:

- debug: msg="{{ reversed_ip_results_list.results | map(attribute='ansible_facts.reversed_ip') | list }}"

Upvotes: 7

Related Questions