Managing multiple servers manually is inefficient, error-prone, and time-consuming. Ansible eliminates this hassle by automating IT tasks such as configuration management, application deployment, and orchestration. Using YAML-based playbooks, Ansible simplifies complex tasks while ensuring consistency across environments.
This guide provides an in-depth explanation of Ansible’s key concepts, installation, and best practices to help network engineers confidently implement automation.
Ansible is an agentless automation tool that connects to remote servers via SSH to execute commands. Unlike other automation tools, it doesn’t require additional software to be installed on managed nodes, making it lightweight and easy to deploy.
Key Features of Ansible:
For further details, check out Ansible's official documentation.
Ansible’s functionality revolves around several core components:
apt
, yum
) or service control (systemd
). Learn more about Ansible Module types.CloudMyLab offers a comprehensive suite of services to help you leverage Ansible for network automation. Here's how CloudMyLab can help you take your Ansible skills to the next level:
Ansible can be installed on various operating systems, including Linux, macOS, and Windows. Here's how to install Ansible on a Unix-based system like Ubuntu.
Python is the backbone of Ansible, and many of its modules are built upon Python libraries. The first thing you need to do is make sure Python is installed on your system. Typically, most modern systems come with Python pre-installed, but it’s always good to double-check.
python3 --version
You should see a version number of 3.10 or above. If not, you'll need to upgrade Python.
Before installing Ansible, install the Python package manager (pip
) and other essential libraries. Additionally, install virtualenv
to manage dependencies in an isolated environment.
sudo apt update
sudo apt install python3-pip python3-virtualenv vim
A Python virtual environment helps you isolate the Ansible installation from the rest of your system, making it easier to manage dependencies and avoid conflicts.
What is a Python Virtual Environment? A virtual environment is a self-contained directory that contains a Python installation for a specific project, along with a specific set of libraries.
Advantages of Using a Python Virtual Environment:
Now, create a virtual environment for Ansible:
virtualenv -p python3 ansible_venv
To start using the virtual environment, activate it:
source ansible_venv/bin/activate
Once activated, the prompt will change, indicating you are working inside the virtual environment.
With the virtual environment activated, install Ansible using pip
:
pip install ansible
Alternatively, you can use the PPA (Personal Package Archive) method:
sudo apt update sudo apt install software-properties-common sudo add-apt-repository --yes --update ppa:ansible/ansible sudo apt install ansible
This method simplifies installation and ensures you get the latest stable version from the repository.
Check that Ansible was installed correctly by verifying its version:
ansible --version
If Ansible is installed properly, you'll see version details. If you encounter an error related to locale encoding (e.g., "Ansible requires locale encoding to be UTF-8"), follow these steps:
Edit the locale configuration file:
sudo vi /etc/default/locale
Replace the existing contents with:
LANG="en_US.UTF-8" LC_CTYPE="en_US.UTF-8"
Save the file and reboot your machine.
After reboot, run the ansible --version command again to ensure everything is set up correctly.
Ansible uses a configuration file (ansible.cfg
) to manage its settings. Generate a basic configuration file:
ansible-config init --disabled > ansible.cfg
This will create an ansible.cfg file in your current directory. By default, Ansible looks for configuration files in these locations (in order of priority):
ANSIBLE_CONFIG
(environment variable, if set)
ansible.cfg
(in the current directory)
~/.ansible.cfg
(in the home directory)
/etc/ansible/ansible.cfg
(global configuration)
For this setup, we'll use the ansible.cfg file in the current directory.
Key Settings to Update:
A playbook is a YAML file that defines a series of tasks to be executed on managed nodes. Create a simple playbook named first_playbook.yml
:
--- hosts: localhost tasks: - name: Print Ansible config location ansible.builtin.debug: msg: - "" - "" - ""
This playbook will print the locations of the Ansible configuration file, the inventory file, and some basic system facts.
Run the playbook using:
ansible-playbook first_playbook.yml
If everything is set up correctly, you should see output displaying the configuration file and inventory file locations.
Ansible ad-hoc commands allow you to execute single tasks on your managed nodes without writing a playbook. They are useful for quick tasks like checking server connectivity, installing packages, or gathering system information.
Here are some examples of Ansible ad-hoc commands with more detailed explanations:
Ping all servers
ansible all -m ping
This command uses the ping module to check the connectivity to all servers in your inventory. The all keyword specifies that the command should be run on all managed nodes.
Install the nginx package on web servers
ansible webservers -m apt -a "name=nginx state=present"
This command uses the apt module to install the nginx package on all servers in the webservers group. The -a flag is used to specify arguments to the module. In this case, we're specifying the name of the package (nginx) and the desired state (present, which means the package should be installed).
Gather facts about all servers
ansible all -m setup
This command uses the setup module to gather information about all servers in your inventory. The setup module collects facts about the system, such as the operating system, hostname, IP address, and hardware information.
Playbooks are the core of Ansible automation. They are YAML files that define a series of tasks to be executed on managed nodes. Playbooks allow you to automate complex workflows, such as deploying applications, configuring servers, and orchestrating multi-tier deployments. Ansible uses YAML because it is easy to read and understand, even for those new to automation.
You can define variables in a playbook in several ways:
You can also validate the syntax of a playbook using the --syntax-check flag. This can help you catch errors before running the playbook.
Here's an example of a simple playbook that installs the nginx web server:
--- - hosts: webservers become: true tasks: - name: Install nginx apt: name: nginx state: present - name: Start nginx service: name: nginx state: started
This playbook defines a play that targets the webservers
group. It uses the become
directive to escalate privileges and execute tasks as root. The playbook then defines two tasks: one to install the nginx
package and another to start the nginx
service.
Roles provide a way to organize playbooks into reusable units. They allow you to group related tasks, variables, files, and templates into a standardized structure. This makes your playbooks more modular, maintainable, and easier to share. Roles are essential for organizing and reusing Ansible code, especially in larger projects.
A typical Ansible role has the following directory structure:
roles/ myrole/ tasks/ main.yml handlers/ main.yml defaults/ main.yml vars/ main.yml files/ templates/ meta/ main.yml
The tasks
directory contains the main tasks for the role, while the handlers
directory contains handlers that can be triggered by tasks. The defaults
directory contains default variables for the role, and the vars
directory contains variables that can override the defaults.
The files
directory contains static files that the role can deploy, and the templates
directory contains Jinja2 templates that can be used to generate dynamic configuration files.
The meta
directory contains metadata about the role, such as its dependencies and author information
Ansible Galaxy is a public repository for sharing Ansible roles and collections. It allows you to find and download pre-built roles for common tasks, such as installing and configuring web servers, databases, and other applications. Ansible Galaxy also supports Ansible Lightspeed with new content development capabilities. Ansible Lightspeed uses AI to help automators build Ansible content.
You can use the ansible-galaxy
command to install roles from Ansible Galaxy. For example, to install the geerlingguy.apache
role, you would run: ansible-galaxy role install geerlingguy.apache
.
Ansible Galaxy is a valuable resource for finding and sharing Ansible roles. You can find roles for a wide variety of tasks, from installing and configuring software to managing cloud resources.
To find roles on Ansible Galaxy, you can use the search functionality on the website or the ansible-galaxy
command-line tool. You can filter your search by keywords, tags, and namespaces.
To share your own roles on Ansible Galaxy, you can use the ansible-galaxy
command to create a role and then publish it to the Galaxy website.
Let's review some best practices for writing effective and maintainable Ansible playbooks:
Several IDE extensions can enhance your Ansible development experience:
Ansible is a powerful and versatile automation tool that can significantly simplify your IT operations. Its agentless architecture reduces complexity and overhead, while its idempotent nature ensures consistent and predictable configurations. By using YAML for its playbooks, Ansible makes automation accessible even to beginners. Ansible can be used for a wide range of tasks, including configuration management, application deployment, and cloud provisioning.
Whether automating configuration management, application deployment, or cloud provisioning, CloudMyLab provides the tools and expertise to accelerate your journey.
Start Automating with CloudMyLab
Here are some helpful resources for learning more about Ansible: