DEV Community

Cover image for Ansible For Beginners - Part 1
Goodnews Azonubi
Goodnews Azonubi

Posted on

Ansible For Beginners - Part 1

Introduction

Ansible is an open-source automation tool used for configuration management, application deployment, and orchestration. It allows system administrators and developers to automate repetitive tasks and also manage infrastructures more efficiently. Whether you're managing a few servers or a vast infrastructure, Ansible simplifies operations using human-readable YAML configuration files, also known as playbooks.

Key Features of Ansible

  • Agentless: Ansible doesn't require any special software or agents to be installed on the machines you're managing. It uses SSH to connect to and control remote machines or servers.
  • Idempotent: Ansible ensures that your systems are in a consistent state, applying changes only when necessary.
  • Simple, Yet Powerful: It uses a simple YAML syntax in the form of playbooks that are easy to read and write.
  • Extensible: Ansible can be extended through custom modules or plugins, making it highly flexible.

In this guide, we'll explore the basics of Ansible and get you started on your journey toward mastering IT automation.

Prerequisites

Before diving into Ansible, ensure you meet the following prerequisites:

  1. Basic Understanding of Command-Line Usage: Familiarity with using the terminal on Linux OS.
  2. Access to a Control Node (Master node): This is the machine where Ansible will be installed and run (it could be your local machine).
  3. Managed Nodes (Slave Nodes): Remote servers or virtual machines to manage (e.g. AWS, Azure, GCP instances, or virtual machines running locally). You'll need SSH access to these nodes.
  4. Ansible Installed: We will cover the installation, but if you already have Ansible installed, you’re good to go.
  5. Basic Networking Knowledge: Understanding IP addresses, SSH, and network ports is helpful for managing remote systems.

Table of Contents

  1. Introduction
    • Key Features of Ansible
  2. Prerequisites
  3. Getting Started with Ansible
    • Installation on Linux (Ubuntu/Debian)
    • Ansible Configuration
    • Setting Up SSH for Remote Access
  4. Ansible Inventory File
    • Creating a Simple Inventory File
    • Inventory Hosts Grouping and Aliases
  5. Running Ansible Ad-Hoc Commands
    • What Are Ad-Hoc Commands?
    • Example: Ping all servers
    • Example: Check disk space
  6. Ansible Modules
    • Introduction to Ansible Modules
    • Commonly Used Modules: apt service copy
  7. Ansible Playbooks
    • What is an Ansible Playbook?
    • Structure of a Playbook
    • Writing Your First Playbook
    • Running a Playbook
  8. Conclusion
    • Summary of Key Concepts

Getting Started with Ansible

Before getting started with using Ansible you need to install it and configure the environment. Here's the steps to set it up on your local machine which will act as the control node.

Installation on Linux (Ubuntu/Debian)

  • 1. Update your system
sudo apt update
sudo apt upgrade
Enter fullscreen mode Exit fullscreen mode
  • 2. Install Ansible
sudo apt install ansible
Enter fullscreen mode Exit fullscreen mode
  • 3. Verify installation
ansible --version
Enter fullscreen mode Exit fullscreen mode

Image description

Ansible Configuration

Ansible primarily uses SSH to manage remote servers. Therefore, you need remote access to the managed nodes for ansible to work effectively without requiring a password but using SSH key-based authentication.

Setting Up SSH for Remote Access:

1.. Generate SSH key pair

ssh-keygen -t rsa -b 4096 -C "ansible@control-node"
Enter fullscreen mode Exit fullscreen mode
  • -t rsa: Specifies the type of key to create (RSA in this case).
  • -b 4096: Specifies the number of bits in the key (4096 is a strong size).
  • -C "ansible@control-node": Adds a comment to the key for easy identification (you can change this comment to match your setup, e.g., "Ansible control node").

Image description

  • A public and private key is generated (ansible_key and ansible_key.pub) where ansible_key.pub is the public key which will be copied to all the managed nodes. It will be copied to the authorized_keys file of the managed nodes. While the ansible_keyfile contains the private key and should not be exposed publicly.

Image description
2.. Copy the public key to the managed nodes

  • You can either copy the public key manually to the managed nodes

Image description

Image description

  • or you can execute this command which will copy it automatically. Since you don't have SSH access you might connect using the password of the managed node to copy your public key.
ssh-copy-id -i ~/.ssh/your_public_key.pub user@managed_node_ip
Enter fullscreen mode Exit fullscreen mode

Once SSH is configured, Ansible can manage the remote node.

Ansible Inventory File

The inventory file contains a list of hosts that Ansible will manage. You can specify hosts or groups of hosts in this file and if you don't create one ansible will use the inventory file default path /etc/ansible/hosts. Creating your own inventory file in Ansible is crucial for several reasons, especially in terms of organization, flexibility, and scalability in managing systems.

Creating a Simple Inventory File

vi inventory
Enter fullscreen mode Exit fullscreen mode
# Group of servers
[webservers]
192.168.1.10
192.168.1.11

# Group of databases
[dbservers]
db1.example.com
db2.example.com
Enter fullscreen mode Exit fullscreen mode

Inventory Hosts Grouping and Aliases

Using the square bracket we can group the target servers into different categories like dbservers, webservers etc. Another way to identify them is using an Alias. We can achieve this by including an alias for each server at the beginning of the line (server1, server2, db1) and assigning the address of the server to the ansible_host parameter.

  • Ansible_host is an inventory parameter for specifying the dns hostname or ip address of the target server.
[webservers]
server1 ansible_host=192.168.1.101
server2 ansible_host=192.168.1.102

[dbservers]
db1 ansible_host=192.168.1.201
Enter fullscreen mode Exit fullscreen mode

Running Ansible Ad-Hoc Commands

These are one-off tasks that you can execute without creating a playbook. Once Ansible is installed and your inventory file is set up, you can start running ad-hoc commands.

What Are Ad-Hoc Commands?

Ad-hoc commands are quick commands run on the managed nodes. They allow you to perform simple tasks without creating a complete playbook and these commands use the ansible command-line tool.

Example: Ping all servers

You can use the ping module to check connectivity to all hosts in your inventory:

  • Since we created our own inventory file we need to explicitly define it in our command using the -i flag so ansible doesn't try to use the default file in the /etc/ansible/hosts path. Image description
  • We can configure Ansible to use the inventory file we created by adding an ansible.cfg file in the current working directory. This does not overwrite the default path but only applies within this directory, as it has higher precedence.

Image description

  • You can look up other parameters like the private_key_file which ansible uses to connect to all your managed nodes. You can view others that can be overridden by viewing the default Ansible configuration file located at: /etc/ansible/ansible.cfg. Image description

Image description

ansible all -m ping
Enter fullscreen mode Exit fullscreen mode

Image description

Example: Check disk space

To check the disk space on all servers:

ansible all -m command -a "df -h"
Enter fullscreen mode Exit fullscreen mode

Image description

Ansible Modules

Introduction to Ansible Modules

Ansible modules are reusable units of code that can be used to perform specific tasks on managed nodes. Modules allow you to automate actions such as installing packages, managing services, copying files, and much more. Ansible modules are categorized into various groups based on their functionality

  • 1. Core Modules: Core modules are the most essential and widely used modules that ship with Ansible. These are stable and maintained as part of the Ansible core.
    • File Modules: Manage files and directories. Examples: file, copy, template, fetch, synchronize
    • Package Management Modules: Install, update, and remove packages. Examples: apt, yum, dnf, pip
    • and more...
  • 2. Cloud Modules: These modules allow you to manage cloud infrastructure resources such as virtual machines, storage, networks, and other services from cloud providers.
    • AWS Modules: Manage resources in Amazon Web Services. Examples: ec2, s3, rds, cloudformation
    • and more...
  • 3. Utility Modules: Utility modules are for general-purpose tasks such as managing files, running commands, or handling notifications.
    • Command and Shell Modules: Run commands or scripts on remote systems. Examples: command, shell, raw
    • and more..

We will be using some of these modules in the next section..

Ansible Playbooks

Ansible Playbooks allow you to automate the configuration and deployment of applications on multiple servers in a predictable manner.

What is an Ansible Playbook?

  • A playbook contains one or more "plays," which map a group of hosts to tasks that should be run on those hosts. It is written in the YAML syntax format.
  • Playbooks can include variables, conditionals, loops, and more, allowing for complex orchestration.
  • Play: This define a set of activities to be run on hosts (task). Each play is a list of dictionary ( in YAML term) separated by a dash - which contains properties like name, hosts ans tasks.
    • Task: This is a single action to be performed on a host or hosts e.g., install a package

Writing Your First Playbook

  • 1. Create a new YAML file (e.g. install_apache.yml or install_apache.yaml).
nano install_apache.yml
Enter fullscreen mode Exit fullscreen mode

A basic ansible playbook structure looks like this:

---
- name: Install and start Apache Web Server
  hosts: webservers
  become: yes  # This enables privilege escalation (sudo)
  tasks:
    - name: Update Package
      apt:
        update_cache: yes  # Ensures the apt cache is updated before installation

    - name: Install Apache
      apt:
        name: apache2
        state: present

    - name: Start Apache service
      service:
        name: apache2
        state: started
Enter fullscreen mode Exit fullscreen mode

Image description

  • 2. Run your playbook:
ansible-playbook install_apache.yml
Enter fullscreen mode Exit fullscreen mode

Play:
Image description

Managed Node: apache is installed on the managed node which has an IP address: 192.168.56.10
Image description
Default Page: Paste the IP address on your browser to view Apache default page
Image description

Conclusion

In this first part of the Ansible for Beginners series, we've covered the following key concepts:

  • Ansible and its primary functions
  • Installation and configuration
  • Setting up SSH for remote access
  • Understanding the inventory file
  • Running ad-hoc commands
  • Ansible modules and their usage
  • Introduction to Ansible Playbooks

What’s Next in Part 2:

In Part 2, we will delve deeper into more advanced topics, including Ansible variables, conditionals, loops, roles and more..

You can also check out my article on Protecting Sensitive Data using Ansible Vault

Let's connect on LinkedIn here

Top comments (0)