Complete DevOps Guide for Ansible

14 feb 2024 6 min di lettura
Complete DevOps Guide for Ansible
Indice dei contenuti

Introduction

In the DevOps space, the search for efficiency, reliability and scalability in software development and infrastructure management is fundamental. Ansible, an open source automation tool, has emerged as a key technology to achieve these goals. This guide aims to provide an in-depth understanding of Ansible, covering its fundamental aspects, configuration files, commands, and practical applications to master infrastructure automation.

1. Introduction to Ansible

Ansible is a powerful IT automation engine that simplifies cloud provisioning, configuration management, application delivery, intra-service orchestration, and many other IT needs. Designed for multi-tier deployments, Ansible models your IT infrastructure by describing how all your systems are related, rather than just managing one system at a time.

2. Ansible architecture

Using a client-server model, Ansible (the server or control machine) manages clients (or nodes) via the SSH or WinRM protocols. Contains a collection of modules that define tasks to perform on nodes. After receiving a command, Ansible compiles the module and sends it to the nodes for execution, after which they report the results to the server.

3. Key Features of Ansible

Ansible, a powerful IT automation tool, simplifies complex tasks and improves productivity in IT environments. Here are its main features:

  1. Agentless architecture: Ansible manages nodes without installing any agents on them, reducing overhead and complexity. Use SSH for Linux/Unix nodes and WinRM for Windows nodes.
  2. Idempotency: ensures that even if a playbook is run multiple times on the same system, the result remains consistent, avoiding unwanted side effects.
  3. Simplicity and ease of use: Written in YAML, Ansible playbooks are easy to write, read, and share, making automation accessible to everyone, including those new to automation.
  4. Declarative language: Define the desired state of your systems rather than the steps to get there, simplifying task descriptions and ensuring consistency.
  5. Expanded module library: Comes with a wide range of modules that support tasks related to system configuration, software installation, cloud provisioning, and more.
  6. Inventory Management: Ansible can work with multiple machines as defined in its inventory, which can be generated statically or dynamically from various sources.
  7. Role-based structure: Enables reusability and sharing of content between playbooks, making it easier to manage complex deployments and configurations.
  8. Integration and extensibility: Easily integrates with other DevOps tools and can be extended with custom modules, plugins, and APIs for specific needs.
  9. Secrets Management: Integrates with tools like Ansible Vault to protect sensitive data like passwords or keys.

These capabilities make Ansible a versatile tool for automating, configuring, and managing information systems, emphasizing efficiency and scalability in IT operations.

4. Get started with Ansible

Before diving into the technical details, make sure Ansible is installed on your control machine (the machine that manages your nodes). You can install Ansible on Linux, macOS, or Windows (via WSL). The simplest command on a Debian-based system is:

sudo apt-get install ansible

Or, for macOS:

brew install ansible

5. Ansible main configuration file

Ansible's behavior is controlled by configuration settings, which can be adjusted via the Ansible configuration file. The default path is /etc/ansible/ansible.cfg, but you can specify a different path by setting the ANSIBLE_CONFIG environment variable.

A typical ansible.cfg file might look like this:

[defaults]
 inventory = /etc/ansible/hosts.ini
 remote_user = root
 host_key_checking = False
 retry_files_enabled = False

6. Ansible inventories

Ansible Inventories defines the hosts and host groups on which commands, tasks, and playbooks will run. Essentially, the inventory is a structured file, typically in INI or YAML format, that lists all the nodes or machines you want Ansible to manage. May include variables that provide additional context or configuration options for each host or group.

Inventories can be static, defined manually by the user, or dynamic, generated by querying external systems. For complex environments, inventories can also organize hosts into groups and subgroups, allowing for more targeted automation strategies.

Here is an example in INI format:

[webservers]
 web1.example.com
 web2.example.com

 [dbservers]
 db1.example.com
 db2.example.com ansible_user=admin

In this example, webserver and dbserver are groups containing different servers, with an additional variable (ansible_user) specified for db2.example.com.

In the examples above, all hosts must be updated DNS records or entries in the /etc/hosts file. Ansible also allows you to define IP address for all hosts as below:

[webservers]
 webserver1 ansible_host=192.168.1.10
 webserver2 ansible_host=192.168.1.11

 [dbservers]
 dbserver1 ansible_host=192.168.1.20
 dbserver2 ansible_host=192.168.1.21

To add SSH details to an Ansible inventory, you can specify variables such as ansible_ssh_user, ansible_ssh_pass, ansible_ssh_private_key_file, and ansible_ssh_port for each host. These variables tell Ansible how to connect to hosts via SSH. Here's how you can add these details to your inventory file:

[webservers]
 webserver1 ansible_host=192.168.1.10 ansible_ssh_user=user1 ansible_ssh_private_key_file=/path/to/key
 webserver2 ansible_host=192.168.1.11 ansible_ssh_user=user2 ansible_ssh_pass=password

 [dbservers]
 dbserver1 ansible_host=192.168.1.20 ansible_ssh_user=dbuser ansible_ssh_private_key_file=/path/to/dbuser/key
 dbserver2 ansible_host=192.168.1.21 ansible_ssh_user=dbuser ansible_ssh_pass=dbpassword ansible_ssh_port=2222

We recommend using SSH keys for greater security than passwords. Ensure that the Ansible control machine has the correct permissions to access the specified key files.

7. Ansible modules

Ansible modules are the building blocks of Ansible automation and enable the execution of specific tasks on remote hosts. Each module has a particular purpose, from system package management to file management.

For example, the copy module copies files from the local computer to remote hosts:

Example:

- name: Copy file to target
 copy:
 src: /src/path/file.txt
 dest: /dest/path/file.txt

The yum module manages packages with the YUM package manager, commonly used on RHEL-based systems. It can install, upgrade and remove packages. For example, to ensure the latest version of "httpd" (Apache web server) is installed:

- name: Ensure Apache is installed
 yum:
 name: httpd
 state: latest

For Ubuntu, which uses the APT package manager, the apt module is used. It works similarly to the yum module but is adapted for Debian-based systems. To ensure that Ubuntu has the latest version of "nginx" (a high-performance web server) installed, use:

- name: Ensure Nginx is installed
 apt:
 name: nginx
 state: latest
 update_cache: yes

8. Ansible ad hoc commands

Ansible ad hoc commands let you quickly perform simple tasks without writing a playbook. They are useful for tasks you need to perform immediately on your managed nodes. For example, to check the uptime of all servers in your "webservers" group, you could use:

ansible webservers -a "uptime"

This command uses the default command module to run the uptime command on all hosts in the "webservers" group.

9. Ansible Playbook

Ansible Playbooks are the core configuration, deployment, and orchestration language of Ansible. They allow you to define and execute a series of activities on one or more nodes managed in YAML format. Playbooks can perform a variety of operations, set variables, include other playbooks, or even handle error handling.

Here is a practical example of a playbook that ensures that the Apache web server is installed and running on a group of web servers:

---
 - name: Ensure Apache is installed and running
 hosts: webservers
 tasks:
 - name: Install Apache
 apt:
 name: apache2
 state: present
 update_cache: yes
 become: yes

 - name: Start Apache
 service:
 name: apache2
 state: started
 enabled: yes
 become: yes

This playbook targets hosts in the webservers group, installs Apache using the apt module (assuming Debian/Ubuntu systems), and ensures that the service is started and enabled to run on startup.

To run the playbook:

ansible-playbook site.yml

10. Basic Ansible commands

Frequently used Ansible commands are:

possible

The ansible command is used to immediately execute tasks on target hosts, without the need for a playbook. It is ideal for running ad hoc commands for quick tasks. For example, to check disk space on all servers in your inventory, you could use:

ansible all -m shell -a 'df -h'

ansible-playbook

ansible-playbook runs Ansible playbooks, which are scripts that define a set of tasks to run on target hosts. Playbooks are written in YAML and offer a powerful way to automate complex multi-tier IT application environments. For example, to deploy a web application:

ansible-playbook deploy_app.yml

ansible-galaxy

ansible-galaxy is a command-line tool for managing Ansible roles, allowing reuse of common configuration steps. Interacts with the Galaxy website where users can share roles. To install a role from Galaxy, you could use:

ansible-galaxy install username.rolename

Conclusion

Ansible offers a powerful framework to automate and manage your IT infrastructure with simplicity and efficiency. By mastering its configuration files, commands, and practical applications, DevOps professionals can significantly improve their operations, ensuring scalable, reliable, and maintainable systems. As you continue to explore Ansible's capabilities, remember that its community and ecosystem are rich resources for learning and growth.

Support us with a

Successivamente, completa il checkout per l'accesso completo a Noviello.it.
Bentornato! Accesso eseguito correttamente.
Ti sei abbonato con successo a Noviello.it.
Successo! Il tuo account è completamente attivato, ora hai accesso a tutti i contenuti.
Operazione riuscita. Le tue informazioni di fatturazione sono state aggiornate.
La tua fatturazione non è stata aggiornata.