Ansible loop over variables

Question:

i am using ansible to update configuration file of newly added NIC
for that i have defined some variables in separate yml file

/tmp/ip.yml

Playbook

similarly repeated for second interface.

Even Though this method works for 2 NIC,this is too difficult to manage ,that is for each new NIC added i need to modify playbook and update corresponding variable in /tmp/ip.yml.

Is there a way to add variables to /tmp/ip.yml and may be using some separator parse it to playbook with out modifying playbook each time for plugging in new NIC.

Answer:

There is a lot to say here.
First, try to avoid lineinfile like plague. It is really a last-resort solution. lineinfile makes it hard to write consistent and idempotents playbooks.

Now, since you’re trying to populate RH style interface files, it is quite easy to do.

Organize your variables

The first thing to do is to have a proper structure for your variables. You’ll want to loop over your interfaces so you have to make stuff ‘loopable’. Having interface1, interface2interfaceN is not scalable as you mentioned.

Here is a suggestion :

Write your template

Now that you have your data, you need a template to create your OS config file.

I included two variations : you can skip outputting a line when it’s not set ({% if ... %} construct) or provide default values (for instance {{item.onboot|default('no')}}).

Your mileage may vay, depending if you want to use a default or to skip with the if construct.

Create a task

Finally, here is a task that will create interface configuration files for each interface :

This should do it all.

Of course, best way to use this task is to add it to some “network” role, and call it from a playbook.

Good luck.

Leave a Reply