简体   繁体   中英

Is there a way to loop on two variables when importing an Ansible role?

I'm importing an Ansible role in a play and running its 'install' task.The role is meant to create VMs on an hypervisor like Vbox and works fine. However, I want to use it to create several VMs at the same time, and I must provide 2 variables for this purpose : - vm_ip : the ip of the vm to be created - vm_name : the name of the vm to be created

I have already tried almost everything with loops, with_items and other things. For instance, this code doesn't work :

- name: Create VMs
  hosts: localhost
  tasks:
  - import_role:
      name: vm_creation
      tasks_from: install
    vars:
      vm_ip: "{{ item.ips }}"
      vm_name: "{{ item.names }}"
      loop:
        - { ips: '192.168.20.4', names: 'test4' }
        - { ips: '192.168.20.5', names: 'test5' }

It is supposed to create both .20.4 and .20.5 VM's but the play crashes telling me this :"The task includes an option with an undefined variable. The error was: 'item' is undefined

You appear to have mis-indented the loop directive. In doing so, you have defined a variable named loop rather than actually creating a loop (this is why item is undefined).

You will also need to use include_role rather than import_role . You can read about the difference between include_role and import_role in the documentation .

- name: Create VMs
  hosts: localhost
  tasks:
  - include_role:
      name: vm_creation
      tasks_from: install
    vars:
      vm_ip: "{{ item.ips }}"
      vm_name: "{{ item.names }}"
    loop:
      - { ips: '192.168.20.4', names: 'test4' }
      - { ips: '192.168.20.5', names: 'test5' }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM