1

I'm working on a project that will use a number of devices that will need to be configured with the same plays, but separate variables. I have a vars file which includes a number of libraries, one for each device. The name of the library matches the name of the device, for example:

(Device1)

- {xxx: "AAA", yyy: "BBB", zzz: "CCC"}
- {xxx: "AAA", yyy: "BBB", zzz: "CCC"}

(Device2)

- {xxx: "AAA", yyy: "BBB", zzz: "CCC"}
- {xxx: "AAA", yyy: "BBB", zzz: "CCC"}

The play itself is supposed to figure out which library matches the device, use that library's variables and none of the other ones. My current attempt is done like this:

- name: do this
  command: "do some of item.xxx with some item.zzz
- include_vars: device-library.yaml
  when: "{{item}} == {{ansible_hostname}}"

But I always get:

fatal: [xxx.xxx.xxx.xxx]: FAILED! => {"failed": true, "msg": "ERROR! 'item' is undefined"}

When this project was just one device, we used with_items: stuff.yaml all the time and it worked just fine.

My question is this: what do I have to put in place of {{item}}, or is there a better way?

0

1 Answer 1

7

From this statement:

The play itself is supposed to figure out which library matches the device, use that library's variables and none of the other ones.

I conclude you are trying to replicate one of the most fundamental features of Ansible.

What you should do:

  1. create a subdirectory host_vars in your Ansible project directory;
  2. move the files containing variable definitions to the host_vars directory;
  3. make sure the above file names match exactly the host names used by Ansible to refer to the target machines (no .yaml extension);
  4. delete all manual include directives from your playbook;
  5. run the playbook.

Alternatively to cover several servers you can do the same using group_vars subdirectory and name the files according to the group names defined in the inventory file.

Refer to the documentation for more information.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .