Ansible is one of the most popular tools for automating configuration management, deploying applications, and orchestrating tasks. Thanks to its simplicity, idempotent nature, and agentless architecture, it has become a cornerstone of many infrastructure operations. This article focuses on the basics of using Ansible for configuration management and ensuring idempotence in configuration changes across a server fleet with CentOS 7.
Prerequisites
Before getting started, you'll need:
- CentOS 7 installed on all managed servers.
- Access to a control server with Ansible installed.
- SSH keys for secure access to target servers without using passwords.
Installing Ansible
- Log in to your control server.
- Add the EPEL repository:
sudo yum install epel-release
. - Install Ansible:
sudo yum install ansible
. - Verify the installation:
ansible --version
.
Configuring Ansible
-
Creating an Inventory File: Create a file
/etc/ansible/hosts
and add server groups along with their addresses. For example:[webservers] server1 ansible_host=192.168.1.1 server2 ansible_host=192.168.1.2
-
Setting Up SSH Keys: Ensure you have SSH keys set up for secure connection to your servers without passwords.
-
Ansible Configuration File: Edit
/etc/ansible/ansible.cfg
to optimize Ansible behavior, such as settinghost_key_checking = False
to skip SSH key verification.
Basic Usage of Ansible
-
Testing Connection: Run
ansible all -m ping
to verify that Ansible can connect to your servers. -
Running Ad-hoc Commands: To execute commands on all servers, use
ansible all -a '<command>'
, where<command>
is your command.
Idempotent Configuration Changes
Idempotence is a key concept in Ansible, meaning that running the same tasks repeatedly won't change the system unless necessary. To ensure idempotence:
-
Use Ansible Modules Instead of Direct Commands: Modules like
yum
,file
,template
,service
, and others ensure that changes are made only if needed. -
Creating Playbooks: Playbooks are YAML files that define which tasks should be performed on servers. An example playbook for installing and starting Nginx:
--- - hosts: webservers tasks: - name: Install nginx yum: name: nginx state: present - name: Start nginx service: name: nginx state: started enabled: yes
-
Running Playbooks: Use
ansible-playbook <playbook_file>.yml
to execute your playbook. Ansible will check the current state of servers and perform only the changes necessary to achieve the desired state defined in the playbook.
Ansible offers an efficient and straightforward way to manage configurations and ensure idempotence in configuration changes across a server fleet. With idempotent playbooks and modules, you can minimize redundant adjustments and ensure consistency across your infrastructure.