2

I want to create a new list through a loop. I created a task like this. Ansible 2.9.10

- name: "Generate list"
  set_fact:
    dst: "{{dst_list | default([])}} + [ '{{ item[0] }}' ]" 
  with_items:
    - "{{failed_connections}}"
- debug: var=dst


"failed_connections": [
    [
        "1.1.1.1", 
        8888
    ], 
    [
        "1.1.1.1", 
        8080
    ], 
    [
        "2.2.2.2", 
        8888
    ], 
    [
        "2.2.2.2", 
        8080
    ], 
    [
        "2.2.2.2", 
        443
    ]
]

I end up only getting the last item in the list.

TASK [access-consul-kv : Generate list] 

*********************************************************************************************
ok: [127.0.0.1] => (item=[u'1.1.1.1', 8888])
ok: [127.0.0.1] => (item=[u'1.1.1.1', 8080])
ok: [127.0.0.1] => (item=[u'2.2.2.2', 8888])
ok: [127.0.0.1] => (item=[u'2.2.2.2', 8080])
ok: [127.0.0.1] => (item=[u'2.2.2.2', 443])

TASK [access-consul-kv : debug] *****************************************************************************************************ok: [127.0.0.1] => {
    "dst": [
        "2.2.2.2"
    ]
}

How can I get a list of all addresses and preferably only unique ones?

De1f
  • 89
  • 1
  • 6

2 Answers2

5

In your task:

- name: "Generate list"
  set_fact:
    dst: "{{dst_list | default([])}} + [ '{{ item[0] }}' ]" 
  with_items:
    - "{{failed_connections}}"

You're setting dst to the value of dst_list + some value. Since you never define dst_list, you always get the value from the default([]) expression, so your set_fact task actually looks like this:

set_fact:
  dst: [ '{{ item[0] }}' ]

If you want to append to a list, you need to use the name of the variable you're setting with set_fact inside the set_fact expression, like this:

set_fact:
  dst: "{{ dst|default([]) + [ item[0] ] }}"

Note that we only need one set of {{...}} markers here.

I will often avoid the use of the default filter by using a vars key to set the default value, like this:

- name: "Generate list"
  set_fact:
    dst: "{{ dst + [ item[0] ] }}"
  with_items:
    - "{{failed_connections}}"
  vars:
    dst: []

I find this makes the expression a little simpler.

larsks
  • 277,717
  • 41
  • 399
  • 399
2

How can I get a list of all addresses and preferably only unique ones?

To append the items in the list

  dst: "{{ dst + item[0] }}"

To get a unique list:

- set_fact:
    unique_list: "{{ dst | unique }}"

If that doesn't work, try to look at this example.

Kevin C
  • 4,851
  • 8
  • 30
  • 64