Ansible role for updating resolv.conf

As described in my previous post, Ansible is very, very powerful tool for your daily automation tasks. I am posting this simple role in order to demonstrate some of the capabilities of Ansible. This is a separate role, which is used to update /etc/resolv.conf on a group of hosts (inventory) with your own.

For convenience sake, I am posting this in my github repo as well. First, lets start with tasks/main.yml. This is the main working "script", which does the magic happen:


- name: Check if there are any previous entries in resolv.conf
  find:
    paths: /etc/resolv.conf
    patterns: '^nameserver ([0-9]{1,3}\.){1,3}[0-9]{1,3}$'
  register: found_previous

- name: Set up resolv.conf (non-verride).
  template:
    src: "{{ item }}"
    dest: /etc/resolv.conf
    owner: root
    group: root
    mode: 0644
  with_first_found:
    - files:
        - "{{ 'hostname_' + inventory_hostname + '.j2' }}"
        - resolv.j2
  paths:
    - ../templates
  when: (found_previous is not defined and replace_previous == 1) or replace_previous == 0

- name: Set up resolv.conf (override or non-existent).
  template:
    src: "{{ item }}"
    dest: /etc/resolv.conf
    owner: root
    group: root
    mode: 0644
  with_first_found:
    - files:
        - "{{ 'hostname_' + inventory_hostname + '.j2' }}"
        - resolv.j2
  paths:
    - ../templates
  when: (found_previous is defined) and (replace_previous == 1)

The other important feature to look at is templates/resolv.j2. This is your main jinja2 template file, which is simple loop that iterates over the variable resolv_conf (placed in defaults/main.yml), which containts our nameservers:

{% for nameserver in resolv_conf %}
nameserver {{ nameserver }}
{% endfor %}

You may need to change vars/main.yml in order to change the default behavior of the script which replaces all previous entries.

Comments