Ansible Tutorial for DevOps: Automation Made Easy

Paul Hill

May 15, 2023 • 13 min read

CONTENTS

    Are you looking for a comprehensive guide to make automation easier? Well, look no further! Ansible is an easy-to-use IT automation engine that does just that.

    This tutorial is perfect for entry level DevOps professionals as well as IT beginners and aspiring DevOps professionals who are looking to get started using Ansible in their own development and operations efforts.

    In this tutorial we’ll discuss what Ansible is, when it should be used, how it benefits your projects, and provide hands-on examples of tasks you can do with it quickly. So let’s begin our journey into this exciting world of automated infrastructure management – join us as we explore the helpful features of Ansible!

    What is Ansible, and why you should use it for DevOps automation

    Ansible is an open-source IT automation tool that allows DevOps teams to automate repetitive tasks, streamline workflows, and manage configurations. It simplifies the process of deploying software, managing updates, and connecting different systems within a network.

    Ansible offers a human-readable language that helps reduce the learning curve and ensures seamless communication between members of your team. It is easy to set up, flexible, and reliable, making it a top choice for organizations seeking to optimize their DevOps processes.

    With Ansible, you can spend less time on tedious tasks and more on innovation, all while ensuring that your systems are running at their best.

    helpdesk
    Logo White

    Learn IT Ops

    Without Leaving Your Home

    Common DevOps tasks Ansible can automate

    DevOps is all about streamlining processes and saving time, which is why Ansible has become such a popular tool in the DevOps world. There are several common tasks that can be easily automated using Ansible, from software deployments to server configurations. For example, Ansible can automate the installation and configuration of database systems or web servers, eliminating the need for manual deployments.

    It can also handle software updates and upgrades, ensuring that all systems are up-to-date and functioning properly. With these tasks automated, DevOps teams can focus on more strategic and creative work, instead of getting bogged down in tedious manual tasks.

    How to install and configure Ansible

    Welcome to the world of Ansible! In this paragraph, you will learn how to install and configure an Ansible environment. First things first, you need to have access to a Linux machine with superuser privileges. Once you have that, you can proceed to the installation process.

    Ansible can be installed using different package management systems such as apt, yum, or dnf depending on your Operating System. But how do you know which to use? You can copy / paste this script to see what package manager your OS uses:

    if [ -n "$(command -v apt-get)" ]; then
      echo "Your package manager is APT"
    elif [ -n "$(command -v yum)" ]; then
      echo "Your package manager is YUM"
    elif [ -n "$(command -v dnf)" ]; then
      echo "Your package manager is DNF"
    else
      echo "Your package manager wasn't identified"
    fi

    Once you have identified your package manager, you can use one of the commands below to install Ansible with your desired Package Manager:

    Step 1) Installing Ansible using apt (Debian-based distributions like Ubuntu):

    sudo apt update
    sudo apt install software-properties-common
    sudo apt-add-repository --yes --update ppa:ansible/ansible
    sudo apt install ansible

    Step 2) Installing Ansible using yum (Older Red Hat, CentOS and Fedora):

    sudo yum install epel-release
    sudo yum install ansible 

    Step 3) Installing Ansible using dnf (Newer Fedora, CentOS and RHEL):

    sudo dnf install epel-release
    sudo dnf install ansible

    Once you have successfully installed Ansible, you can start configuring your environment. A basic configuration involves creating an inventory file and modifying the ansible.cfg file.

    Modifying the ansible.cfg file (optional)

    The ansible.cfg file contains the configuration settings for Ansible, and while the default configuration is usually sufficient, you may want to modify it to suit your particular use case. Here are a few common modifications you might consider:

    • Inventory File Path: By default, Ansible looks for the inventory file at /etc/ansible/hosts. If you want to use a different inventory file, you can change this with the inventory parameter under the [defaults] section.
    [defaults] inventory = /path/to/your/inventory 
    • Remote User: The default remote user is root. If you want Ansible to connect as a different user, you can specify this with the remote_user parameter.
    [defaults] remote_user = yourusername 
    • Sudo User: If you want Ansible to execute operations with sudo, you can enable this with the become parameter.
    [defaults] become = True 
    
    • Ansible Modules Library Path: If you have custom modules in your Ansible library, you can add the path to your library with the library parameter.
    [defaults] library = /path/to/your/library
    • SSH Key File: If you want Ansible to use a specific private key file instead of the default ~/.ssh/id_rsa, you can specify this with the private_key_file parameter.
    [defaults] private_key_file = /path/to/your/private/key
    • Log Path: By default, Ansible does not use a log file. If you want to enable logging, you can specify a log path with the log_path parameter.
    [defaults] log_path = /path/to/your/logfile

    These are just a few examples of the kinds of modifications you might want to make to the ansible.cfg file. The exact changes you make will depend on your specific use case and the requirements of your environment. Always be sure to test your changes thoroughly to ensure they have the desired effect and don’t cause any unexpected behavior.

    Setting up SSH keys

    Setting up SSH keys is an important step for configuring Ansible, as it allows Ansible to connect to your hosts without needing a password. Here are the steps to set this up:

    Step 1: Generate SSH Key Pair

    On your Ansible control node (the machine running Ansible), generate a new SSH key pair as the user who will run Ansible commands (it could be your user or a dedicated ansible user). You can generate an SSH key pair with the ssh-keygen command:

    ssh-keygen

    Press Enter to accept the default file location and name, and enter a passphrase if desired (or leave it empty for passwordless authentication).

    Step 2: Copy the Public Key to Your Hosts

    Now, you must copy your public key to each host you want to manage with Ansible. You can do this with the ssh-copy-id command, which will copy your public key to the specified user’s authorized keys on the target host:

    ssh-copy-id user@your.host.ip

    Replace user with the username Ansible should use to connect to the host, and your.host.ip with the IP address of the host. You’ll be prompted to enter the user’s password.

    Step 3: Test the SSH Key Authentication

    Finally, test that you can SSH into the host without a password:

    ssh user@your.host.ip

    Again, replace user and your.host.ip with your own details. If set up correctly, you should be able to SSH into the host without being asked for a password.

    Step 4: Specify Your Private Key in Ansible.cfg

    If you’re not using the default private key location (~/.ssh/id_rsa), you’ll need to tell Ansible which private key to use. You can do this in your hosts file or ansible.cfg. In ansible.cfg, add the following under the [defaults] section:

    [defaults] private_key_file = /path/to/your/private/key

    Replace /path/to/your/private/key with the path to your private key file.

    Now, Ansible should be able to connect to your hosts using SSH key authentication.

    You can specify a different SSH key for each server in your Inventory file if needed. If you need to do this then check out that part in the section below.

    Modifying your Ansible Inventory file

    The Ansible hosts file, also known as the inventory file, is a file where you define the machines (hosts) that you’ll be managing using Ansible. Each host can be specified by an IP address or a hostname, and hosts can be grouped together for easier management.

    The default location for the hosts file is /etc/ansible/hosts, but you can create an inventory file anywhere and specify its location using the -i <inventory> option in the ansible command or by setting the inventory option in the ansible.cfg file.

    Here is how you might add a host to the inventory file:

    Step 1) Open the hosts file in a text editor. For example, if you’re using nano:

    sudo nano /etc/ansible/hosts

    Step 2) Add a line for your host(s). This can be as simple as the hostname or IP address of the machine:

    192.168.1.100

    You can also specify a host with a custom ansible SSH user, SSH port, and a specific private key:

    192.168.1.100 ansible_user=myuser ansible_port=2222 ansible_private_key_file=/home/myuser/.ssh/id_rsa

    Hosts can be grouped by adding them under a label in square brackets. For example:

    [webservers] 
    192.168.1.100
    192.168.1.101
    
    [dbservers]
    192.168.1.102
    192.168.1.103

    In this example, the hosts are divided into two groups, “webservers” and “dbservers”. You can then use these group names when running your ansible commands or playbooks to target specific groups of machines.

    Step 3) Save and exit the text editor.

    Remember that the hosts file must be readable by the user running the Ansible commands, and if you’re specifying private key files, they must also be accessible and readable by the Ansible user.

    Ansible Playbooks

    An Ansible playbook is a script written in YAML that describes a set of tasks to be performed on one or more hosts. Each playbook consists of one or more “plays”, and each play targets a specific group of hosts and contains a series of tasks to be executed on those hosts.

    Playbooks are at the heart of Ansible and are used to automate tasks that otherwise could be time-consuming and error-prone if performed manually. They allow you to describe complex IT workflows and processes in a way that’s easy to understand and maintain.

    Let’s take a look at an example Ansible Playbook that will configure an Alma Linux server by installing the EPEL repository, installing updates, and installs Python 3.9.

    Step 1) Configure Playbook Basics

    Lets start by defining what hosts we want to configure, whether or not to use sudo privileges, and prepare to enter the tasks that will be completed in the playbook:

    ---
    - hosts: all
      become: yes
      tasks:

    In Ansible playbooks, --- and - have specific meanings as per the YAML syntax:

    1. ---: This is an optional indicator for the start of a YAML document. An Ansible playbook can have multiple documents, so you can write multiple plays in a single playbook, each starting with ---. However, it’s common to see only a single play in a playbook, in which case --- simply indicates the start of the play. It’s not required by Ansible or YAML, but it’s considered good practice to include it for clarity.
    2. -: In YAML, a single dash - is used to denote a list item. In the context of an Ansible playbook, each task within the tasks list starts with a -. Similarly, when defining a list of hosts or a list of variables, you would use -. This is a fundamental part of YAML syntax.

    Now, for the hosts, become and tasks lines specifically:

    1. hosts: The hosts keyword is used to define which hosts the playbook will be run against. This could be a group of hosts, a single host, or all hosts, depending on what’s specified in the inventory file. In the playbook provided, hosts: all means that the playbook will be run on all hosts defined in the Ansible inventory.
    2. become: The become keyword in Ansible allows you to execute operations with sudo (superuser) privileges. This is necessary for tasks that require administrative permissions, like installing packages or updating system files. When become: yes is specified, it means that the tasks in the playbook will be run with sudo privileges.
    3. tasks: The tasks keyword is used to define a list of tasks that the playbook will execute.

    These keywords are fundamental to Ansible playbooks, and understanding them is crucial to writing and understanding Ansible automation scripts.

    Step 2: Define the Ansible Tasks

    First, we need to install the EPEL repository because Python 3.9 is not available in the default Alma Linux repositories.

    - name: Install EPEL repository
      yum:
        name: epel-release
        state: present

    Here’s the breakdown of the syntax shown above:

    • - name: Install EPEL repository: This starts the definition of a new task. The name keyword is followed by a description of the task, which is a string that describes what the task does. This name will be printed out when you run the playbook, which makes it easier to understand what’s happening.
    • yum:: This is the name of the Ansible module being used by the task. The yum module manages packages with the yum package manager, which is used by certain Linux distributions such as CentOS, RHEL, and their derivatives.
    • name: epel-release: This is a parameter to the yum module. It specifies the name of the package that the module will manage. In this case, the package is epel-release, which is a package that installs the EPEL repository.
    • state: present: This is another parameter to the yum module. It specifies the desired state of the package. In this case, the state is present, which means that the package should be installed. If the package is not already installed, Ansible will install it. If the package is already installed, Ansible will do nothing.

    Next, we will update all packages on the server.

    - name: Update all packages
      yum:
        name: "*"
        state: latest

    Finally, we will install Python 3.9.

    - name: Install Python 3.9
      yum:
        name: python39
        state: present

    Full Playbook:

    Here is the complete playbook. Pay special attention to the tab indentation for the tasks as it is different than what we showed above:

    ---
    - hosts: all
      become: yes
      tasks:
        - name: Install EPEL repository
          yum:
            name: epel-release
            state: present
    
        - name: Update all packages
          yum:
            name: "*"
            state: latest
    
        - name: Install Python 3.9
          yum:
            name: python39
            state: present

    To run the playbook, save it to a file (for example, setup.yml), and then use the ansible-playbook command:

    ansible-playbook setup.yml

    This playbook will install the EPEL repository, update all packages, and then install Python 3.9 on all hosts specified in your inventory file. The become: yes directive tells Ansible to execute the tasks with sudo privileges.

    Conclusion

    From this post, we’ve seen how Ansible can be an asset to DevOps automation and simplify complex tasks with ease. With a quick install and walkthrough of the basic command line syntax, it’s easy to get started with Ansible. Additionally, there are complex playbooks that can be written to call multiple tasks specific to anyone’s environment. This combination of convenience and customization makes Ansible a great solution when considering new strategies for DevOps automation. Lastly, as always, following best practices and having backups can save time when troubleshooting any issues with automation. Now you have the knowledge to start utilizing Ansible for your DevOps needs.

    Coding and AutomationDevOps

    Want to improve your IT skillset? Start with a free account and get access to our IT labs!

    Blogpostctadesktop

    Sign up free and start learning today!

    Practice on REAL servers, learn from our video lessons, interact with the Server Academy community!