32

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']" }

Jurudocs
  • 8,595
  • 19
  • 64
  • 88

1 Answers1

52

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.

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • 2
    My group has hostid and hostname as listed below: [cluster] machine1 ansible_host=10.0.0.8 machine2 ansible_host=10.2.8.8 machine3 ansible_host=10.2.9.8 . Is there anyway to get the ansible_host from the groups to use with_items? – mjm Jun 27 '18 at 20:39
  • 6
    @mjm Accessing variables on the host can be done with this syntax: `hostvars[item].ansible_host`. There's some more info on Ansible "magic variables" [here](https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables). – worldsayshi Apr 29 '19 at 12:26
  • 1
    If anyone else is struggling to get the mongo example working from the official Ansible Github repo, it's way out of date, and uses the bare group variable for with_items. – Andrew Fielden Jun 03 '20 at 20:58