Managing and configuring the hostnames across your infrastructure can be a crucial aspect of system administration. This task becomes a breeze with Ansible, thanks to the hostname module. The hostname module allows us to manage the hostnames on a given machine.
This tutorial explores this module in detail, starting with its functionality, parameters, and examples.
What Is a Hostname?
A hostname is essentially a label that identifies a machine on a network. Proper hostname configuration is essential for systems on a network to recognize and communicate with each other, especially in more extensive infrastructures.
Ansible Hostname Module Parameters
Luckily, the hostname module provides a simple set of parameters to configure the hostnames on the target machines quickly.
Supported parameters include:
Name – This is the required parameter that represents the host’s name. It should be a short and fully qualified domain name (FQDN).
Use – It specifies which strategy to use. Supported values include:
- System
- Sysv
- Init
- Openrc
This helps Ansible determine the method to manage the hostname. Most of the time, Ansible detects it automatically, but you can specify it if necessary.
Examples:
Example 1: Basic Usage
The following shows a basic example of using the hostname module to configure a hostname on the target machine:
- hosts: all
tasks:
- name: Set Hostname
hostname:
name: "webserver.linuxhint.com"
Example 2: Specifying a Strategy
While Ansible generally detects the service manager in use on the target system (like systemd or init), we might want to set it explicitly in some instances as follows:
- hosts: all
tasks:
- name: Set Hostname using systemd
hostname:
name: "webserver.linuxhint.com"
use: systemd
Example 3: Dynamic Hostname Configuration
Using the power of Ansible variables, we can dynamically set the hostnames based on conditions or host-specific data as demonstrated in the following:
- hosts: all
vars:
type: "database"
tasks:
- name: Set Hostname based on type
hostname:
name: "{{ type }}.linuxhint.com"
Conclusion
You learned about the Ansible hostname module that offers a straightforward way to manage and configure the hostnames across various hosts in the Ansible inventory.