Ansible Firefighting Hotline Series (13): Automated Configuration of LINUX DHCP

Ansible Firefighting Hotline Series (13): Automated Configuration of LINUX DHCP

#Linux #Automation #Automation #Ansible #DHCP

🤩 Introduction: Are you still struggling with IP address allocation? Ansible comes to the rescue!

Dear operations colleagues, do you feel overwhelmed when it comes to configuring a DHCP server? 😫

Manually editing <span><span>dhcpd.conf</span></span> and <span><span>dhcpd6.conf</span></span> is not only complex and error-prone, but also involves handling a myriad of details such as IP address ranges, lease times, and MAC address/DUID bindings. Maintaining configuration consistency across multiple environments (development, testing, production) is nothing short of a nightmare! IP conflicts, clients unable to obtain the correct DNS… Once these issues arise, troubleshooting can be time-consuming and labor-intensive.

To completely eliminate this pain point, this issue of Ansible Firefighting Hotline 🔥 rushes in! We will demonstrate an enterprise-level Ansible automation solution that allows for the standardized, secure, and reliable deployment of DHCPv4 and DHCPv6 servers with just one click, while easily configuring clients. Let IP address management become simple, efficient, and error-free! 🚀

🤔 Design Philosophy: Why is our Playbook a Best Practice?

An excellent automation solution is far more than just a simple combination of commands. Our design philosophy incorporates the core practices advocated by Red Hat, allowing your automation solution to leap from “it just works” to “professional and reliable”!

1Modular Design, Separation of Responsibilities ✨ We have broken down the entire scenario into two independent Playbooks: <span><span>deploy_dhcp_server</span></span> and <span><span>configure_dhcp_client</span></span>. The benefits of this design are obvious: single responsibility and clear logic. You can run either one independently as needed, greatly enhancing the reusability and maintainability of the solution.2Configuration as Code, GitOps Ready 📚 All core configuration files (<span><span>dhcpd.conf</span></span>, <span><span>dhcpd6.conf</span></span>) are managed as project files rather than being manually modified directly on the server. This means your entire DHCP infrastructure can be included in a version control system (like Git)! Every change to the IP address range, MAC address binding is traceable, making auditing, rollback, and team collaboration unprecedentedly easy and secure.3Standardized Client Configuration ✅ For client configuration, we did not use handwritten <span><span>nmcli</span></span> commands, but directly called the official Red Hat <span><span>rhel-system-roles.network</span></span> system role. This ensures the standardization, stability, and cross-version compatibility of client configurations. Whether the target system is RHEL 8 or RHEL 9, one set of code achieves the same effect!4Idempotency Assurance, Safety First 🛡️ All our Playbooks strictly adhere to Ansible’s core principle of idempotency. You can confidently execute them repeatedly; Ansible will automatically detect the current state and apply only the necessary changes. Whether it’s the initial deployment or configuration updates, the results will be predictable, and you no longer have to worry about repeated executions breaking the service!

📈 Multi-Dimensional Scoring of Automation Scenarios

Dimension Score
Ease of Use
Reusability ⭐ ⭐ ⭐ ⭐
Stability ⭐ ⭐ ⭐ ⭐
Scalability ⭐ ⭐ ⭐ ⭐
Best Practice Compliance ⭐ ⭐ ⭐ ⭐

🛠️ Foolproof Deployment Guide

Talking theory is not as good as trying it out!

Prerequisites

1 An Ansible control node.2 The target server is configured with SSH trust, and the user executing Ansible has <span><span>sudo</span></span> permissions.3 The control node has Ansible installed. If you need to configure clients, you also need to install the <span><span>rhel-system-roles</span></span> package.

Project Directory Structure

First, please create the following directory and file structure on your Ansible control node:

dhcp_automation/
├── deploy_dhcp_server.yml
├── configure_dhcp_client.yml
├── inventory
└── files/
    ├── dhcpd.conf
    └── dhcpd6.conf

Complete File Contents (Copy and Paste)

1. Inventory: <span><span>inventory</span></span>
# ====================================================================== 
# Ansible Inventory for DHCP Automation 
# ====================================================================== 

# ------------------------------------------------------------------------ 
# DHCP Server Group 
# ------------------------------------------------------------------------ 
# deploy_dhcp_server.yml Playbook will be executed on hosts in this group. 
# Place the hostnames or IP addresses of the machines you want to configure as DHCP servers here. 
# ------------------------------------------------------------------------ 
[dhcp_servers] 
servera.example.com

# ------------------------------------------------------------------------ 
# DHCP Client Group 
# ------------------------------------------------------------------------ 
# configure_dhcp_client.yml Playbook will be executed on hosts in this group. 
# Place the hostnames or IP addresses of the machines you want to configure as DHCP clients here. 
# ------------------------------------------------------------------------ 
[dhcp_clients] 
serverb.example.com 
serverc.example.com
2. Playbook 1: <span><span>deploy_dhcp_server.yml</span></span>
---
- name: Deploy and configure DHCPv4 and DHCPv6 servers
  hosts: dhcp_servers
  become: true

  tasks:
    # ====================================================================== 
    # 1. Pre-flight Checks 
    # ==================================================================== 
    - name: Check if the operating system is RHEL/CentOS 8/9
      ansible.builtin.assert:
        that:
          - ansible_distribution in ['RedHat', 'CentOS']
          - ansible_distribution_major_version in ['8', '9']
        fail_msg: "This Playbook only supports RHEL 8/9 or CentOS 8/9 series operating systems."
        quiet: true

    # ==================================================================== 
    # 2. Installation & Configuration 
    # ==================================================================== 
    - name: Ensure dhcp-server package is installed
      ansible.builtin.yum:
        name: dhcp-server
        state: present

    - name: Deploy DHCPv4 configuration file (dhcpd.conf)
      ansible.builtin.copy:
        src: files/dhcpd.conf
        dest: /etc/dhcp/dhcpd.conf
        owner: root
        group: root
        mode: '0644'
        # Ensure SELinux context is correct
        setype: dhcp_etc_t
      notify: restart dhcpd # Notify handler to restart service when configuration file changes

    - name: Deploy DHCPv6 configuration file (dhcpd6.conf)
      ansible.builtin.copy:
        src: files/dhcpd6.conf
        dest: /etc/dhcp/dhcpd6.conf
        owner: root
        group: root
        mode: '0644'
        setype: dhcp_etc_t
      notify: restart dhcpd6 # Notify handler to restart service when configuration file changes

    # ==================================================================== 
    # 3. Service Management 
    # ==================================================================== 
    - name: Ensure dhcpd and dhcpd6 services are started and set to start on boot
      ansible.builtin.service:
        name: "{{ item }}"
        state: started
        enabled: true
      loop:
        - dhcpd
        - dhcpd6

    # ==================================================================== 
    # 4. Firewall Configuration 
    # ==================================================================== 
    - name: Ensure firewall allows dhcp and dhcpv6 services
      ansible.builtin.firewalld:
        service: "{{ item }}"
        state: enabled
        immediate: true
        permanent: true
      loop:
        - dhcp
        - dhcpv6

  # ==================================================================== 
  # 5. Handlers - Respond to configuration changes 
  # ====================================================================== 
  handlers:
    - name: restart dhcpd
      listen: "restart dhcpd"
      ansible.builtin.service:
        name: dhcpd
        state: restarted

    - name: restart dhcpd6
      listen: "restart dhcpd6"
      ansible.builtin.service:
        name: dhcpd6
        state: restarted
3. Playbook 2: <span><span>configure_dhcp_client.yml</span></span>
---
- name: Configure DHCP Client
  hosts: dhcp_clients
  become: true

  # ------------------------------------------------------------------------ 
  # Use rhel-system-roles.network role to configure client network 
  # This is the standardized, cross-version network configuration method recommended by Red Hat Linux service automation 
  # ------------------------------------------------------------------------ 
  roles:
    - rhel-system-roles.network

  # ------------------------------------------------------------------------ 
  # Variable Definitions - Provide configuration parameters for the role 
  # ------------------------------------------------------------------------ 
  vars:
    # Define the network connection to be configured
    network_connections:
      # Create a connection named 'dhcp-connection' for eth1 interface
      - name: "dhcp-connection"
        interface_name: eth1
        type: ethernet
        # Enable IPv4 automatic configuration (DHCP)
        ip:
          dhcp4: yes
          # Enable IPv6 automatic configuration (SLAAC + DHCPv6)
          auto6: yes
        state: up
4. DHCPv4 Configuration: <span><span>files/dhcpd.conf</span></span>
# Ansible-managed DHCPv4 Configuration
authoritative;

# Define a subnet
subnet 192.168.0.0 netmask 255.255.255.0 {
  # Define dynamic address pool range
  range 192.168.0.150 192.168.0.254;
  # Define network options
  option routers 192.168.0.1;
  option broadcast-address 192.168.0.255;
  option domain-name-servers 192.168.0.1, 8.8.8.8;
  option domain-search "internal.example.com", "example.com";
  default-lease-time 600;
  max-lease-time 7200;
}

# Reserve a fixed IP address for a specific host
host web.internal.example.com {
  hardware ethernet 52:54:00:01:fa:0c;
  fixed-address 192.168.0.100;
}
5. DHCPv6 Configuration: <span><span>files/dhcpd6.conf</span></span>
# Ansible-managed DHCPv6 Configuration
authoritative;

# Define an IPv6 subnet
subnet6 fde2:6494:1e09:2::/64 {
  # Define dynamic address pool range
  range6 fde2:6494:1e09:2::20 fde2:6494:1e09:2::60;
  # Define network options
  option dhcp6.name-servers fde2:6494:1e09:2::1;
  option dhcp6.domain-search "internal.example.com", "example.com";
  default-lease-time 600;
  max-lease-time 7200;
}

# Reserve a fixed IPv6 address for a specific host (identified by DUID)
host app-server {
  host-identifier option dhcp6.client-id 00:04:cf:e4:cf:3b:19:63:60:27:08:e8:d5:67:58:e8:57:00;
  fixed-address6 fde2:6494:1e09:2::101;
}

How to Use in Your Environment?

1

Modify Configuration Files ✏️: Open the <span><span>files/</span></span> directory and edit <span><span>dhcpd.conf</span></span> and <span><span>dhcpd6.conf</span></span>, modifying the IP address ranges, gateways, DNS servers, MAC/DUID bindings, etc. according to your network plan.

2

Update Inventory 📝: Edit the <span><span>inventory</span></span> file, filling in the hostnames or IP addresses of your DHCP servers and clients in the corresponding groups.

3

Execute Automation ▶️:

Deploy DHCP Server:

ansible-playbook -i inventory deploy_dhcp_server.yml

Configure DHCP Client:

ansible-playbook -i inventory configure_dhcp_client.yml

Done! It’s that simple! Now you can go brew a cup of coffee ☕️ and enjoy the ease brought by automation.

🎁 Bonus Time! Get the Complete Annotated Version!

Do you find the above Playbooks not detailed enough? Want to dive deeper into the logic behind each line of code and the best practices recommended by the official documentation?

👉 Click the link below to get the packaged download of the Playbook project with complete annotations and syntax highlighting! 👈

Let you not only use it but also understand it thoroughly, becoming the most outstanding Ansible automation expert in your team!

Leave a Comment