In today’s fast-paced IT landscape, automation is key to efficiently managing infrastructure and ensuring scalability and reliability. Ansible, an open-source automation tool, offers a powerful solution for automating tasks such as configuration management, application deployment, and orchestration. In this comprehensive guide, we’ll explore Ansible’s core concepts, installation process, advanced functionalities, and provide practical examples to help you harness its full potential.
- What is Ansible and What is it Used For?
- How to Install Ansible
- Base Concepts and Terminology
- Ansible example 1: Install k3s on a remote server
- Create an Ansible Playbook
- Run the Ansible Playbook
- Verify the Installation
- Ansible example 2: Install Apache and PHP using the inventory
- Ansible example 3: Ensuring Idempotence
- Best Practices
- Conclusion
What is Ansible and What is it Used For?
Ansible is a versatile automation tool that simplifies IT orchestration, configuration management, and application deployment tasks. Developed by Red Hat, Ansible boasts an agentless architecture, enabling seamless communication with remote nodes via SSH. It eliminates the need for installing software on target systems, making it lightweight and easy to set up. Ansible is widely used across industries to automate repetitive tasks, enforce system configurations, and streamline DevOps processes.
How to Install Ansible
Installing Ansible is straightforward and can be done on various operating systems. Follow these steps:
- On Linux: Utilize your package manager to install Ansible. For instance, on Ubuntu:
update sudo apt install ansible
- On macOS: Employ Homebrew for Ansible installation. Execute the following commands:sqlCopy
brew update
brew install ansible
- On Windows: Ansible can be installed via Windows Subsystem for Linux (WSL) or tools like Cygwin.
For detailed instructions, accompanied by screenshots and useful links, refer to the Ansible Installation Guide.
Base Concepts and Terminology
Ansible operates on a simple yet powerful principle: it connects to remote servers via SSH (or other transport mechanisms), executes predefined tasks defined in playbooks, and then reports back the results. Let’s break down how Ansible works in more detail:
- Inventory: Ansible operates on a list of managed nodes, which are specified in an inventory file. This file can be static or dynamic, depending on your requirements. Each entry in the inventory represents a remote server (or a group of servers) that Ansible will manage.
- Playbooks: Playbooks are YAML files containing a set of instructions or tasks that Ansible will execute on the managed nodes. These tasks can range from installing software packages, configuring services, deploying applications, and more. Playbooks are divided into one or more plays, and each play consists of a list of tasks to be executed sequentially.
- Modules: Ansible relies on modules to perform specific actions on managed nodes. Modules are small programs written in Python (mostly) that encapsulate the functionality needed to carry out tasks. Ansible ships with a vast collection of built-in modules covering a wide range of tasks, from managing packages to configuring network devices and cloud resources.
- Execution: When you run an Ansible playbook, Ansible connects to each managed node via SSH (or another transport mechanism) and executes the tasks defined in the playbook. It gathers information about the system using modules called “facts” and uses this information to determine which tasks need to be executed. Ansible then applies the tasks in a idempotent manner, meaning that running the playbook multiple times will result in the same state on the managed nodes.
- Reporting: As Ansible executes tasks on the managed nodes, it collects output and reports back the results in real-time. This includes information about which tasks were successful, which failed, and any errors encountered during execution. Ansible provides detailed logs and reports to help you troubleshoot and debug issues.
- Idempotence: One of the key principles of Ansible is idempotence, which means that running a playbook multiple times should result in the same state on the managed nodes. This ensures that Ansible is safe to use and allows you to define the desired state of your infrastructure without worrying about unintended consequences.
Other key elements in the Ansible world are:
Roles: Roles aid in organizing and structuring Ansible playbooks and tasks, promoting reusability and maintainability.
Handlers: Handlers are tasks triggered by other tasks in playbooks, activated only if changes occur. They commonly handle tasks like service restarts post-configuration changes.
Vault: Ansible Vault encrypts sensitive data within playbooks, safeguarding information such as passwords or API keys during storage and transmission.
Dynamic Inventory: Dynamic inventory allows Ansible to automatically discover and manage hosts based on external sources like cloud providers or LDAP.
Templates: Ansible templates utilize placeholders dynamically replaced with values during playbook execution, facilitating configuration file creation tailored to specific hosts or environments.
Callbacks: Callbacks are plugins intercepting events during playbook execution, enabling customization of output, logging, or notification behavior.
Facts: Ansible gathers system information from managed nodes, known as facts, utilized in playbooks to make decisions or execute conditional tasks based on host characteristics.
Filters: Ansible filters enable data manipulation within playbooks, encompassing operations like string manipulation, list operations, or data formatting.
Ansible example 1: Install k3s on a remote server
Let’s walk through the process of installing k3s on a Linux server with the specified user and password. We’ll start from scratch:
Step 1: Prepare the Environment
Ensure that you have a Linux server running with SSH access enabled. You should have the IP address (i.e. 192.168.1.12), with your username (brewed), and password (brilliance) ready.
Step 2: Install Ansible
First, we need to install Ansible on your local machine (the machine from which you will run Ansible). Assuming you’re using Ubuntu, you can install Ansible using the following commands:
sudo apt update
sudo apt install ansible
Create an Ansible Playbook
Now, let’s create an Ansible playbook to install k3s on the server. Create a new file named install_k3s.yml
:
---
- name: Install k3s
hosts: 192.168.1.12
remote_user: brewed
become: true
gather_facts: false
tasks:
- name: Download k3s installation script
get_url:
url: "https://github.com/k3s-io/k3s/releases/download/{{ k3s_version }}/k3s"
dest: "/tmp/k3s"
mode: "u+x"
vars:
k3s_version: "v1.21.5+k3s2" # Update to the desired k3s version
- name: Install k3s
shell: /tmp/k3s server
In this playbook:
- We specify the host (192.168.1.12) and the remote user (brewed) to connect to the server.
- We set
become: true
to execute tasks with sudo privileges. - We download the k3s installation script from the official GitHub release page.
- We make the script executable with mode “u+x”.
- We install k3s by running the installation script with the “server” argument.
Run the Ansible Playbook
Save the playbook file and then execute the playbook using the following command:
ansible-playbook install_k3s.yml --extra-vars "ansible_ssh_pass=brilliance"
This command runs the playbook and provides the SSH password (brilliance
) as an extra variable.
Verify the Installation
After the playbook execution completes successfully, you should verify that k3s is installed and running on the server. You can do this by SSHing into the server and running kubectl commands to interact with the Kubernetes cluster.
Ansible example 2: Install Apache and PHP using the inventory
Step1: Create an Inventory File
Create a file named hosts
and define the IP addresses of the servers where you want to install Apache and PHP:
[web_servers]
192.168.1.12
192.168.1.13
192.168.1.14
Step 2: Write the Ansible Playbook
Create a playbook named install_apache_php.yml
:
---
- name: Install Apache and PHP
hosts: web_servers
remote_user: brewed
become: true
gather_facts: true
tasks:
- name: Install Apache
apt:
name: apache2
state: present
- name: Install PHP
apt:
name: php
state: present
In this playbook:
- We specify the
web_servers
group from the inventory file to target the servers where Apache and PHP will be installed. - We set
become: true
to execute tasks with sudo privileges. - We use the
apt
module to install Apache (apache2
) and PHP (php
) packages.
Step 3: Run the Ansible Playbook
ansible-playbook -i hosts install_apache_php.yml --extra-vars "ansible_ssh_pass=brilliance"
This command runs the playbook and provides the SSH password (brilliance
) as an extra variable.
Step 4: Verify the Installation
After the playbook execution completes successfully, verify that Apache and PHP are installed and running on the target servers. You can do this by accessing the web servers’ IP addresses in a web browser or by checking the Apache and PHP installation directories and configuration files.
Ansible example 3: Ensuring Idempotence
To ensure idempotence and maintain consistency across servers, you can specify the exact version of packages to be installed in the Ansible playbook. Here’s how you can modify the playbook to achieve this:
---
- name: Install Apache and PHP
hosts: web_servers
remote_user: brewed
become: true
gather_facts: true
tasks:
- name: Install Apache
apt:
name: apache2
state: present
update_cache: yes
version: 2.4.41-4ubuntu3.5 # Specify the exact version of Apache
- name: Install PHP
apt:
name: php
state: present
update_cache: yes
version: 7.4.3-4ubuntu2.8 # Specify the exact version of PHP
In this modified playbook:
- We’ve added the
version
parameter to both the tasks for installing Apache and PHP. - By specifying the exact version, Ansible will ensure that the specified version of Apache and PHP is installed on the target servers.
- If the specified version is already installed, Ansible will skip the installation process, ensuring idempotence.
- The
update_cache: yes
parameter ensures that Ansible updates the package cache before installing the specified versions, ensuring that the correct version is fetched from the package repositories.
With these modifications, your Ansible playbook will install Apache and PHP with the exact specified versions, ensuring consistency across all servers and leveraging idempotence.
Best Practices
In our examples previously we just used the password in clear, but only because it is a learning session. In reality things are a little bit more complex, below a list of best practices for managing transport and avoiding the use of passwords in clear text.
Let’s explore them:
- SSH Key Authentication: Ansible primarily uses SSH for connecting to remote nodes. Instead of using passwords, you can configure Ansible to authenticate using SSH keys. This involves generating SSH key pairs on the Ansible control node and distributing the public keys to the remote nodes. Ansible can then authenticate to the remote nodes using the SSH keys.
- SSH Configuration: Ensure that your SSH configuration on both the Ansible control node and the remote nodes is properly configured for security. This includes disabling password authentication and enforcing the use of SSH keys for authentication. You can configure these settings in the SSH configuration files (
ssh_config
andsshd_config
). - SSH Agent Forwarding: Ansible supports SSH agent forwarding, which allows the SSH agent on the Ansible control node to authenticate to remote nodes using the SSH keys loaded into the agent. This eliminates the need to store SSH keys on the Ansible control node and provides a more secure method of authentication.
- Use Ansible Vault: Ansible Vault is a feature that allows you to encrypt sensitive data, such as passwords or SSH private keys, in Ansible playbooks and inventory files. Instead of storing passwords in clear text, you can encrypt them using Ansible Vault and then decrypt them during playbook execution. This helps protect sensitive information from being exposed.
- Key Rotation: Regularly rotate SSH keys and Ansible Vault encryption keys to enhance security. This helps mitigate the risk of unauthorized access if keys are compromised. Automate key rotation processes where possible to ensure consistency and reduce manual effort.
- Secure File Transfer: When transferring files between the Ansible control node and remote nodes, use secure protocols such as SCP or SFTP. Ensure that file transfers are encrypted to protect sensitive data in transit.
- SSH Bastion Hosts: If your infrastructure uses bastion hosts or jump servers for SSH access, configure Ansible to connect through the bastion host when accessing remote nodes in a private network. This helps secure SSH access and reduces the exposure of internal nodes to the internet.
- Monitor SSH Activity: Implement monitoring and logging of SSH activity to detect and alert on suspicious or unauthorized access attempts. Regularly review SSH logs for anomalies and investigate any unauthorized access incidents promptly.
By following these best practices, you can enhance the security of SSH authentication and data transfer in your Ansible environment, while also ensuring that sensitive information is protected from exposure.
Conclusion
With this guide, we’ve explored various aspects of Ansible, a powerful automation tool for managing IT infrastructure. Here’s a summary of what we’ve covered:
- Introduction to Ansible: Ansible is an open-source automation platform that simplifies IT operations by automating tasks such as configuration management, application deployment, and orchestration.
- Installation: We provided detailed instructions on how to install Ansible on your system, covering various operating systems and installation methods.
- Ansible Basics: We discussed the fundamental concepts of Ansible, including playbooks, inventories, tasks, and modules. Playbooks are YAML files that define tasks to be executed on remote nodes, while inventories specify the target hosts.
- Node Management: Managing nodes effectively is crucial for maintaining a stable infrastructure. We explored best practices for managing nodes, including dynamic inventory, node organization, tagging, and documentation.
- Transport and Authentication: We delved into best practices for secure transport and authentication in Ansible, emphasizing SSH key authentication, SSH configuration hardening, Ansible Vault for encryption, and monitoring SSH activity.
- Examples and Use Cases: We provided detailed examples of using Ansible for various tasks, such as automating k3s installation, orchestrating containers, configuring Nginx Ingress Controller and Apache web servers, and combining multiple examples into comprehensive playbooks.
- Best Practices: Throughout the discussion, we highlighted best practices for optimizing Ansible usage, including idempotence, automation, monitoring, and security measures.
By mastering Ansible and following these best practices, you can streamline your IT operations, improve efficiency, and ensure the security and stability of your infrastructure. Whether you’re a beginner or an experienced user, Ansible offers powerful automation capabilities to meet your needs.
Share this content: