Configuring the network interface on a Debian Bullseye VM with an Ansible playbook

Configuring the network interfaces of Linux machines can be tedious and unpredictable if we do it by hand. Let’s automatize the procedure and minimize the possible mistakes with using Ansible! This example uses Debian, but it can be easily ported to any platform.

Here’s my example playbook that can be used to configure network for static IP address on Debian Bullseye after the OS installation.

This is just a simple and portable playbook. If we want to follow the industry standards, it is easy to create an Ansible role from this.

---
- name: Configure network for static IP address
  hosts: all
  become: yes

  tasks:
    - name: Configure network interface
      community.network.ipadm_addr:
        name: "{{ ansible_default_ipv4.interface }}"
        state: present
        addr: "{{ static_ip_address }}/{{ netmask }}"
        type: static

    - name: Configure DNS servers
      lineinfile:
        path: /etc/resolv.conf
        line: "nameserver {{ dns_server }}"

    - name: Restart network service
      service:
        name: networking
        state: restarted

This playbook will configure the network interface for static IP address, configure the DNS servers and restart network service.

We can run this playbook by saving it as a file with .yml extension (e.g., network.yml) and then running the following command:

ansible-playbook network.yml --extra-vars "static_ip_address=<IP_ADDRESS> netmask=<NETMASK> dns_server=<DNS_SERVER>"

Make sure to replace <IP_ADDRESS>, <NETMASK> and <DNS_SERVER> with our own values.

Leave a comment