Part 8 – Editing Files using Ansible

This lab shows how to edit a name server config via ansible.

Example Playbook (dns-overwrite.yml)

sudo vi dns-overwrite.yml

What this playbook does

  • Change files in dns
---
- hosts: all
  become: true

  vars_files:
    - /etc/ansible/group_vars/resolvfile.yml

  tasks:

    # Ubuntu + Zorin (systemd-resolved)
    - name: Overwrite DNS for Ubuntu/Zorin (systemd-resolved)
      copy:
        dest: /etc/systemd/resolved.conf
        content: |
          [Resolve]
          DNS={{ dns_server }}
          Domains={{ dns_domain }}
      when: ansible_distribution in ['Ubuntu', 'Zorin']

    - name: Restart systemd-resolved on Ubuntu/Zorin
      service:
        name: systemd-resolved
        state: restarted
      when: ansible_distribution in ['Ubuntu', 'Zorin']

    # CentOS (real resolv.conf)
    - name: Overwrite DNS for CentOS
      copy:
        dest: /etc/resolv.conf
        content: |
          search {{ dns_domain }}
          nameserver {{ dns_server }}
      when: ansible_distribution == 'CentOS'

Lets define a variable file /etc/ansible/group_vars/resolvfile.yml

dns_server: 172.16.11.10
dns_domain: ash.local

Do a dry run

ansible-playbook dns-overwrite.yml --check

Run the playbook

Run a check d.

ansible centos -m command -a "tail -10  /etc/resolv.conf"

That was fun to do and not that hard.

(Visited 4 times, 1 visits today)

By Ash Thomas

Ash Thomas is a seasoned IT professional with extensive experience as a technical expert, complemented by a keen interest in blockchain technology.