KIA CEED
KIA CEED

Reputation: 305

Use ansible output for set_fact with loop maybe

I use ansible for create and run lxc containers in proxmox. Run container task:

    - name: "DHCP IP"
      proxmox:
   ...
        hostname: "{{ item }}"
   ...
        pubkey: "{{  pubkey  }}"
      with_items:
          - "{{ (servers_name_suggested | union(servers_name_list)) | unique }}"
          register: output_dhcp
          when: not static_ip

    - set_fact:
        vmid: "{{ output_dhcp.results[0].msg | regex_search('[0-9][0-9][0-9]') }}"

    - name: "Start container {{ vmid }}"
      proxmox:
        vmid: "{{ vmid }}"
        api_user: root@pam
        api_password: "{{  api_password }}"
        api_host: "{{  api_host }}"
        state: started
      when: start_lxc

It's work if launched one container, one item in task "DHCP IP". If I set two or more item, my task started only first container. Because I am setting

output_dhcp.results[0].msg

How I can take information about all containers, as example, if I will create tree containers:

output_dhcp.results[1].msg
output_dhcp.results[2].msg

and received to

- name: "Start container {{ vmid }}"
  proxmox:
    vmid: "{{ vmid }}"

for run all my new cotainers.

Upvotes: 1

Views: 900

Answers (1)

zigarn
zigarn

Reputation: 11595

The output_dhcp.results is a list, if you extract only the first item with a [0] you will only have the first item.

You need to transform the list into another list you can iterate over in the "Start container" task:

- set_fact:
    vmids: "{{ output_dhcp.results | map(attribute='msg') | map('regex_search', '[0-9][0-9][0-9]') | list }}"

- name: "Start container {{ item }}"
  proxmox:
    vmid: "{{ item }}"
    api_user: root@pam
    api_password: "{{ api_password }}"
    api_host: "{{ api_host }}"
    state: started
  with_items: "{{ vmids }}"
  when: start_lxc

To explain the transformation part:

  • output_dhcp.results | map(attribute='msg') => get the msg attribute of each item of the output_dhcp.results list (http://jinja.pocoo.org/docs/dev/templates/#map)
  • | map('regex_search', '[0-9][0-9][0-9]') => apply the regex_search on each item of the list
  • | list => transform the generator into a list

Upvotes: 1

Related Questions