Register var with dict and loop over output dynamically

ansible

I want to create and boostrap multiple vm's with an ip. This is working when only creating one at a time, but I would like scale this playbook to create more than one at a time.

I make a call to phpipam and get the next available ip from the subnet and assign that value to the vmware_guest role, and it starts up with the appropriate ip.

The limitation is when I loop over the list in: group_vars/all

total_vms:
  - vm01
  - vm02
  - vm03

It generates an ip for each item in the list as it should, but this list needs to be dynamic based on the number of vm's.

---
- name: Gathering ipam auth token
  uri:
    validate_certs: false
    url: "{{ ipam.token_request }}"
    method: POST
    user: "{{ ipam.api_user }}"
    password: "{{ ipam.api_pass | trim }}"
    force_basic_auth: yes
  register: output

- name: checking subnet for next available ip address
  uri:
    validate_certs: false
    url: "{{ ipam.available_ip }}/{{ ipam.subnet_id | int }}"
    headers: token="{{ output.json.data.token }}"
  register: ip_address
  with_items: "{{ total_vms }}"
...

How can I populate a registered variable with the value without manually specifying the size of the list? The only way I've been able to get the values back that I need is by specifically calling each element in the list:

- debug: msg={{ ip_address.results[0].json.data }}
- debug: msg={{ ip_address.results[1].json.data }}
- debug: msg={{ ip_address.results[2].json.data }}

Is it possible to store the length of the list in a var and then use it in place? Once this I can dynamically loop over the lists I should be to write the returned ip to a dict in a file and continue on with vm creation.

---
- name: Create a virtual machine from a template
  vmware_guest:
    hostname: "{{ vcenter.url }}"
    username: "{{ vcenter.username }}"
    password: "{{ vcenter.password | trim }}"
    datacenter: "{{ vcenter.datacenter }}"
    validate_certs: false
    folder: "{{ folder }}"
    name: 
      - "{{ vcenter_name }}"
    state: poweredon
    template: "{{ vcenter.template }}"
    disk:
    - size_gb: 20
      type: thin
      autoselect_datastore: true
    networks:
    - name: "{{ vlan }}"
      ip: "{{ ip_address.json.data }}"
      netmask: "{{ netmask }}"
      gateway: "{{ gateway }}"
      domain: "{{ vcenter.domain }}"
      dns_servers: "{{ vcenter.dns_servers }}"
  register: deploy
  delegate_to: localhost
...

Best Answer

I think you do this with a with_items: loop. In stead of this:

- debug: msg={{ ip_address.results[0].json.data }}
- debug: msg={{ ip_address.results[1].json.data }}
- debug: msg={{ ip_address.results[2].json.data }}

Can you try this?

- debug: msg="{{ item.json.data }}"
  with_items:
    - "{{ ip_address.results }}"