Skip to content
All posts

Ansible Setup Made Easy: Step-by-Step Instructions

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.

Contents

  1. Ansible Basics
  2. Understanding Ansible’s Architecture
  3. Step-by-Step Guide to Ansible Setup
  4. Writing Your First Playbook
  5. Using Ad-hoc Commands
  6. Ansible Playbooks
  7. Ansible Roles
  8. Ansible Best Practices
  9. Ansible Tools and IDE Integrations

Part 1: Ansible Basics

What is Ansible?

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:

  • Idempotency: Ensures that running a task multiple times won’t cause unintended changes if the system is already in the desired state.
  • Human-readable Playbooks: Uses YAML syntax to define tasks in a structured yet easy-to-understand format.
  • Extensibility: Supports a wide range of modules to automate system configuration, deployments, and more.

For further details, check out Ansible's official documentation.

Part 2: Understanding Ansible’s Architecture

Ansible’s functionality revolves around several core components:

  • Control Node: The system where Ansible is installed and commands are executed.
  • Managed Node: The remote servers or devices that Ansible manages.
  • Inventory: A file or a dynamic script that lists the managed nodes that Ansible will interact with.
  • Modules: Pre-built scripts that execute specific tasks like package management (apt, yum) or service control (systemd). Learn more about Ansible Module types.
  • Tasks: Individual units of action within a playbook, such as installing a package or starting a service.
  • Ansible Playbooks: YAML files that define a series of tasks to be executed on managed nodes. 
  • Roles: A way to organize playbooks into reusable units, making them more modular and maintainable.

CloudMyLab: Empowering Your Ansible

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 Instant Env: Launch a pre-configured Ansible environment in minutes with CloudMyLab's Ansible Instant Env. This cloud-hosted solution provides all the tools and resources you need to get started with Ansible automation, including pre-built playbooks, modules, and templates.
  • Real-World Use Case Templates: Explore CloudMyLab's collection of real-world use case templates, designed to mirror industry standards and provide a solid foundation for your network projects.
  • Network Automation Professional Services: CloudMyLab offers professional services to help you accelerate your network automation journey. Our team of certified engineers can help you design, implement, and manage your Ansible automation solutions.
  • Learning Labs: CloudMyLab's Learning Labs provide a hands-on environment for learning and experimenting with Ansible and other networking technologies. These labs are designed to help you gain practical experience and prepare for certifications.

Part 3: Step-by-Step Guide to Ansible Setup

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.

Prerequisites

  • Operating System: Ubuntu 20.04 LTS or above (preferred version is 20.04 or later). 
  • Python Version: Ensure Python 3.10 or above is installed. Ansible requires Python 3.10+ for its latest versions. But specific versions may vary depending on the Ansible release being used.

Step 1: Check Your Python Version 

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.

Step 2: Install Required Python Packages 

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 

Step 3: Create a Python Virtual Environment 

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: 

  • Isolation: Keeps project dependencies separate. 
  • Compatibility: Avoids conflicts between packages. 
  • Manageability: Easy to create and delete environments as needed. 

Now, create a virtual environment for Ansible: 

virtualenv -p python3 ansible_venv

Step 4: Activate the Virtual Environment 

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.

Step 5: Install Ansible 

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.

Step 6: Verify the Installation 

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. 

Step 7: Create Ansible Configuration File 

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: 

  • Inventory: By default, the inventory file is located at /etc/ansible/hosts. If you want to use a custom inventory file, update the inventory setting. 
  • Host Key Checking: Disable SSH key checking by setting host_key_checking = False in the ansible.cfg file. 

Writing Your First Ansible Playbook

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

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.

Ansible Playbooks

What are Ansible Playbooks

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:

  • Using the vars block at the beginning of the playbook.
  • Defining variables in inventory files.
  • Using separate variable files.
  • Passing variables on the command line.

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.

Ansible Roles

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

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.

Finding and Sharing Ansible Roles

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.

Ansible Best Practices

Let's review some best practices for writing effective and maintainable Ansible playbooks:

  • Keep it simple: Use advanced features only when necessary and strive for clarity and readability.
  • Use version control: Store your playbooks, roles, and inventory files in a version control system like Git.
  • Name your plays and tasks: Use descriptive names that clearly indicate the purpose of each play and task.
  • Use comments: Add comments to explain complex logic or non-obvious configurations.
  • Use fully qualified collection names: When referencing modules or plugins, use their fully qualified collection names to avoid ambiguity.
  • Use dynamic inventory: In cloud environments, use dynamic inventory to automatically discover and manage your instances.
  • Group inventory by function: Organize your inventory into logical groups based on the roles of your servers.
  • Separate production and staging inventory: Use separate inventory files for your production and staging environments to prevent accidental deployments.
  • Use Ansible Vault: Encrypt sensitive data like passwords and API keys using Ansible Vault.
  • Test your playbooks: Before deploying to production, thoroughly test your playbooks in a staging environment. You can use the --check flag for dry runs to see what changes would be made without actually making them.
  • Use whitespace: Use whitespace effectively to improve the readability of your playbooks. For example, add a blank line before each task or block of tasks.

Ansible Tools and IDE Integrations

Several IDE extensions can enhance your Ansible development experience:

  • VS Code - official Ansible Extension: Adds language support for Ansible to Visual Studio Code and OpenVSX compatible editors.
  • Vim: Useful Vim plugins include ansible-vim and the Ansible vim and neovim plugin.
  • Emacs: lsp-mode provides Ansible Language Server Protocol support for Emacs.
  • PyCharm: Useful plugins include Ansible Lint and Ansible Vault Integration.

Next Steps

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

Learning Resources

Here are some helpful resources for learning more about Ansible: