This Ansible playbook is designed to update configuration files on multiple servers, ensuring each server has a unique configuration based on its specific variables, such as host_id
and ip_addr
.
How It Works:
- Inventory File: Lists all the target servers along with their unique variables (
host_id
andansible_host
which represents the IP address). - Playbook: Uses Ansible’s
template
module to generate configuration files on each server, incorporating the host-specific variables. - Looping with Variables: The playbook loops over the list of servers, dynamically assigning the
host_id
andip_addr
variables for each host and applying the configuration template accordingly. - Template File: The Jinja2 template file defines the structure of the configuration file and includes placeholders for the variables.
Implementation Details:
- Inventory File (
hosts
): Specifies the servers and their unique variables. - Playbook (
playbook.yml
): Defines tasks to apply the configuration template on each server using a loop. - Template File (
config.j2
): Contains the configuration structure, with placeholders forhost_id
andip_addr
.
Example Inventory File:
[servers]
server1 ip_addr=192.168.1.1 host_id=1
server2 ip_addr=192.168.1.2 host_id=2
server3 ip_addr=192.168.1.3 host_id=3
Example Playbook:
- name: Update configuration file on multiple servers
hosts: localhost
tasks:
- name: Apply the configuration template on each server
ansible.builtin.template:
src: templates/config.j2
dest: "{{ dest_path }}"
loop: "{{ groups['servers'] }}"
loop_control:
loop_var: current_host
vars:
dest_path: /path/to/destination/config_file
host_id: "{{ hostvars[current_host].host_id }}"
ip_addr: "{{ hostvars[current_host].ansible_host }}"
delegate_to: "{{ current_host }}"
Example Template File (config.j2
):
# Configuration File
host_id = {{ host_id }}
ip_addr = {{ ip_addr }}
Running the Playbook:
Execute the playbook with the following command:
ansible-playbook -i hosts playbook.yml
This setup ensures that each server in the servers
group receives a configuration file tailored to its specific host_id
and ip_addr
, maintaining consistency and reducing the potential for manual errors.