Warm tip: This article is reproduced from serverfault.com, please click

ansible get result from role and append to a list

发布于 2020-12-01 00:55:27

I have a play like this

---
- name: List images in ACRs
  any_errors_fatal: true
  hosts:
    - localhost
  gather_facts: false

  vars:
    acrs: ["registry1", "registry2"]

  tasks:
    - name: list repos
      with_items: "{{ acrs }}"
      include_role:
        name: list_docker_image_repos
      vars:
        registry_name: "{{ item }}"

list_docker_image_repos will do set_fact which a list of dicts. How can I append all the facts (from every iteration) to a list?

Or is there are different way to do this?

thanks

Questioner
D. Seah
Viewed
0
Vladimir Botka 2020-12-01 09:53:58

In each iteration put the list into a dictionary. For example, given the role

shell> cat roles/list_docker_image_repos/tasks/main.yml
- set_fact:
    docker_image_repos: "{{ ['repo1', 'repo2', 'repo3']|
                            product([registry_name])|
                            map('join', '-')|
                            list }}"
- set_fact:
    my_lists: "{{ my_lists|
                  combine({registry_name: docker_image_repos}) }}"

the playbook

- hosts: localhost
  vars:
    acrs: ["reg1", "reg2"]
    my_lists: {}
  tasks:
    - name: list repos
      include_role:
        name: list_docker_image_repos
      loop: "{{ acrs }}"
      vars:
        registry_name: "{{ item }}"
    - debug:
        var: my_lists

gives

    "my_lists": {
        "reg1": [
            "repo1-reg1",
            "repo2-reg1",
            "repo3-reg1"
        ],
        "reg2": [
            "repo1-reg2",
            "repo2-reg2",
            "repo3-reg2"
        ]
    }

Extract the list of the lists. For example

    - debug:
        msg: "{{ acrs|map('extract', my_lists)|list }}"

gives

    "msg": [
        [
            "repo1-reg1",
            "repo2-reg1",
            "repo3-reg1"
        ],
        [
            "repo1-reg2",
            "repo2-reg2",
            "repo3-reg2"
        ]
    ]

Use filter flatten to put all items into a single list. For example

    - debug:
        msg: "{{ acrs|map('extract', my_lists)|flatten }}"

gives

    "msg": [
        "repo1-reg1",
        "repo2-reg1",
        "repo3-reg1",
        "repo1-reg2",
        "repo2-reg2",
        "repo3-reg2"
    ]