I have a problem to find a working solution to loop over my inventory. I start my playbook with linking a intentory file:
ansible-playbook -i inventory/dev.yml playbook.yml
My playbook looks like this:
---
- hosts: localhost
  tasks:
    - name: Create VM if enviro == true
      include_role:
        name: local_vm_creator
      when: enviro == 'dev' 
So when loading the playbook the variable enviro is read from host_vars and sets the when condition to dev. The inventory file dev.yml looks like this:
[local_vm]
192.168.99.100
192.168.99.101
192.168.99.102
[local_vm_manager_1]
192.168.99.103
[local_vm_manager_2]
192.168.99.104
[local-all:children]
local_vm
local_vm_manager_1
local_vm_manager_2
My main.yml in my role local_vm_creator looks like this:
---
- name: Create test host
  local_action: shell docker-machine create -d virtualbox {{ item }}
  with_items:
    - node-1
    - node-2
    - node-3
    - node-4
    - node-5
- debug: msg="host is {{item}}"
  with_items:  groups['local_vm'] 
And the problem is that i can't get the listed servers from the dev.yml inventory file.
it just returns:
ok: [localhost] => (item=groups['local_vm']) => { "item": "groups['local_vm']", "msg": "host is groups['local_vm']" }
If the only problem is with_items loop, replace it with:
with_items: "{{ groups['local_vm'] }}"
and you are good to go. Bare variables are not supported in with_ any more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With