Ansible loop over variables

混江龙づ霸主 提交于 2019-11-30 13:41:42

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, interface2 ... interfaceN is not scalable as you mentioned.

Here is a suggestion :

interfaces_ipv4:
  - name: eth0
    bootproto: static
    ipaddress: 192.168.211.249
    netmask: 255.255.255.0
    gateway: 192.168.211.2
    dns: 192.168.211.2
  - name: eth2
    bootproto: static
    ipaddress: 10.0.0.100
    netmask: 255.0.0.0

Write your template

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

BOOTPROTO={{item.bootproto}}
IPADDR={{item.ipaddress}}
NETMASK={{item.netmask}}
{% if item.gateway is defined %}
GATEWAY={{item.gateway}}
{% endif %}
PEERDNS=no
DNS1={{item.dns}}
ONBOOT={{item.onboot|default('no')}}

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 :

- name: Push template
  template: 
    src=/path/to/the/above/template.j2
    dest=/etc/sysconfig/network-scripts/ifcfg-{{item.name}}.cfg
  with_items:
    - "{{ interfaces_ipv4 }}"

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!