CUSTOMISED
Expert-led training for your team
Dismiss
Ansible for Beginners: A Comprehensive Guide to Get Started with IT Automation

8 September 2023

Ansible for Beginners: A Comprehensive Guide to Get Started with IT Automation

Configuration management and IT automation are critical for managing infrastructure and applications efficiently. Ansible is a popular open-source automation tool that can help you with configuration management, application deployment, orchestration and more.

This beginner's guide will walk you through the key concepts and basics of getting started with Ansible. This material is taken from JBI Tech Trainings course in Ansible. To find out more feel free to get in contact with our dedicated team. 

File:Ansible logo.svg - Wikipedia

 

What is Ansible?

Ansible is an automation engine for managing configurations, provisioning, deployment and orchestration. It is agentless, using SSH to connect to machines and execute tasks.

Some key features of Ansible:

  • Agentless - Does not require any agents or daemons to be installed on remote machines. Uses SSH to connect.
  • Idempotent - Repeated application of playbooks have the same effect. This avoids unexpected side effects from multiple runs.
  • Declarative - Playbooks describe the desired end-state, not specific commands to execute.
  • Human Readable - Playbooks and modules use YAML format which is easy for humans to understand.

These features make Ansible a simple yet powerful automation tool. The agentless nature and readable declarative playbooks are key advantages compared to similar tools like Puppet or Chef.

Ansible works by connecting to remote machines over SSH and executing modules to administer those systems. Modules perform specific tasks like installing a package, changing config files, restarting services etc. Playbooks are the basis for configuration management in Ansible. They are written in YAML and describe the desired configurations for your systems.

Installing Ansible

Ansible can be installed on various platforms like Linux, MacOS and Windows. We will look at installing Ansible on Ubuntu Linux.

First, update the apt package index:

sudo apt update

Next, install Ansible:

sudo apt install ansible

To verify the installation, check the Ansible version:

ansible --version

This will display the installed Ansible version:

ansible 2.9.6
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/username/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 3.8.10 (default, Nov 14 2022, 12:59:47) [GCC 9.4.0]  

Ansible is now installed and ready to use. Next, we will look at the directory structure and config files.

Ansible Directory Structure

By default, Ansible configuration and files are located in /etc/ansible/. The key files and directories are:

  • /etc/ansible/ansible.cfg - Ansible configuration file
  • /etc/ansible/hosts - Default inventory file with host groups
  • /etc/ansible/roles/ - Directory for Ansible roles
  • /etc/ansible/playbooks/ - Playbook directory

The ansible.cfg file contains global configuration settings. The hosts inventory file lists the hosts managed by Ansible. We will look at both these key files next.

Ansible Configuration File

The ansible.cfg file contains various settings that control Ansible execution, logging etc. Some useful settings are:

[defaults] 
inventory = /etc/ansible/hosts
remote_user = username  
ask_pass = True
...
  • inventory specifies the location of the default inventory file.
  • remote_user configures the default SSH user name for connecting to hosts.
  • ask_pass enables prompting for SSH password if not specified.

Feel free to modify other settings as per your requirements. Ansible will use sensible defaults for most use cases.

Inventory File

The inventory file lists all the hosts that Ansible can connect to and manage. It can also group hosts and set variables per group. Below is a simple inventory file example:

[webservers] 
web1.example.com
web2.example.com

[dbservers]  
db.example.com

[webservers:vars]
ansible_user=admin 

Here webservers and dbservers are host groups. We also set a variable ansible_user for the webservers group. The inventory file supports a good amount of flexibility in grouping hosts and setting variables.

Now that Ansible is installed and configured, we can start using it to manage our systems.

Running Ad-Hoc Commands

Ansible modules do the actual work like administering remote systems. Modules can be executed directly from the command line using the ansible program. This allows running simple one-off tasks. Some examples:

Install a package:

ansible webservers -m apt -a "name=nginx state=present"

Restart service:

ansible webservers -m service -a "name=nginx state=restarted"

Ad-hoc commands let you easily run Ansible tasks without having to write playbooks. Next we will look at playbooks which provide reproducible multi-machine configurations.

Ansible Playbooks

Playbooks are the way to automate configuration management and deployment with Ansible. They are written in YAML format and designed to be human readable.

Playbooks contain one or more plays. Each play defines a set of activities (tasks) to be run on specified hosts.

Below is a simple playbook example with two plays:

---

- name: Install Nginx
  hosts: webservers

  tasks:
  - name: Update apt cache 
    apt:
      update_cache: yes
      
  - name: Install nginx
    apt:  
      name: nginx
      state: latest
      
- name: Start Nginx
  hosts: webservers
  
  tasks:

  - name: Start Nginx
    service:
      name: nginx
      state: started  

In a play, the tasks define what needs to be done. Modules like apt and service do the actual work here.

Playbooks allow you to configure entire environments and workflows in a reproducible and maintainable way. We will dive further into playbook structure and concepts next.

Playbook File Structure

Playbooks contains plays and plays contain tasks. Let us look at the common playbook components:

Hosts

The hosts line specifies the managed hosts a play runs on. It can be a single host, group from inventory or query like hosts: dbservers.

Tasks

Each task runs an Ansible module. The module and arguments for the task are specified using key-value pairs.

Handlers

Handlers are tasks that run only when notified after some change. They are like triggered tasks.

Variables

Variables hold values that can be referenced in plays. They provide portability and help manage differences between environments.

Templates

Templates combine variables and text files for configuration file generation.

Roles

Roles are pre-defined sets of tasks and files that can be reused. We will cover Ansible roles later.

Now you have an overview of the playbook components. Next, let's look at how to run playbooks.

Running Playbooks

Ansible playbooks can be executed using the ansible-playbook command.

To run a playbook:

ansible-playbook playbook.yml

By default, Ansible will connect to remote servers, run each task and report back the status.

Some useful command line options:

  • --check - Performs a dry run to check for syntax errors
  • -v - Verbose output
  • --start-at-task="install nginx" - Start execution at a specific task

These let you test and troubleshoot your playbooks. You can also run playbooks in parallel mode to speed up execution on multiple servers.

Ansible Modules

Ansible executes modules to do the actual work on remote hosts. Modules accept parameters and handle implementation details.

Some commonly used modules:

  • apt - Package management for APT based distros
  • yum - Package management on RedHat based distros
  • service - Manage services
  • copy - Copy files from local or remote locations
  • git - Deploy software or files from git checkouts
  • user - User account management
  • ping - Test connectivity to hosts

There are over 2000+ modules covering virtually all areas of system administration. You can browse modules on Ansible website.

Writing playbooks involves combining modules to achieve the desired configurations.

Ansible Variables

Variables store values that can be reused in playbooks. They help manage differences between environments and provide portability.

Some ways variables can be defined:

---

# Playbook variable
http_port: 80  

# Inventory variable 
db_host: "sql01.example.com"

# Facts contain info about managed hosts
{{ ansible_os_family }}   

# Registered variables store task results
register: result

# Set facts create variables
set_fact:
  apps_dir: "/opt/apps" 

Variables can be referenced in playbooks as {{ http_port }}.

Ansible has a variable precedence hierarchy that determines which variables override others.

Ansible Roles

As playbooks get larger, it can help to break them into reusable components called roles.

Roles package related configurations, handlers, files and variables together:


site.yml
webservers.yml 
handlers/
files/
templates/
tasks/
vars/

Roles provide a nice way to modularize and organize more complex playbook code. They allow reuse across different playbooks and projects.

We have covered the key concepts you need to start learning and using Ansible.

Conclusion

Ansible provides a simple yet powerful way to automate IT configurations and workflows.

Key takeaways from this beginner's Ansible guide:

  • Ansible is agentless and uses SSH to connect to remote hosts
  • Playbooks describe desired configurations in a declarative way
  • Modules do the actual work of system administration
  • Variables help manage differences between environments
  • Roles allow reusable abstractions for complex automation

With these building blocks, you can start automating your infrastructure effectively with Ansible. Make sure to checkout the Ansible documentation for more detailed usage and examples.

Frequently Asked Questions

What are the requirements for using Ansible?

Ansible can be run from any machine with Python installed. Managed nodes only require SSH access from the control machine where Ansible is run.

How does Ansible compare to other automation tools?

Ansible is agentless unlike Chef or Puppet which have agents on remote nodes. The declarative yaml playbooks are very readable. Ansible also has a large collection of modules covering most administrative tasks.

Can Ansible be used for configuration management and deployment?

Yes, Ansible excels at both configuration management as well as application deployment. Playbooks can automate multi-tier deployments across development, testing and production environments.

Does Ansible have graphical tools or a web interface?

Ansible itself is command line only tool. There are third party tools like Ansible Tower from RedHat that provide web interfaces, dashboards and other functionality on top of Ansible. 

If you enjoyed this article you might enjoy our next article Supercharge Your Sysadmin Skills with Ansible Playbooks

In the world of DevOps and automation, Ansible plays a pivotal role in orchestrating and managing IT infrastructure efficiently. At JBI Training, we offer a selection of courses to empower you with the skills required to excel in Ansible and DevOps practices.

  • Ansible: Dive into the world of Ansible, a powerful automation tool. Learn how to automate repetitive tasks, configure and manage systems, and streamline your IT operations.
  • DevOps Introduction: Gain an introduction to the DevOps philosophy and practices. Understand the principles of collaboration between development and operations teams, and explore how DevOps can accelerate software delivery.
  • DevOps Essentials / DevOps with Azure: Deepen your understanding of DevOps with our Essentials course. Learn about essential DevOps tools, practices, and cultural principles. Alternatively, explore DevOps with Azure, focusing on the integration of Azure services within the DevOps pipeline.

Enroll in these courses and equip yourself with the knowledge and tools to navigate the world of Ansible automation and DevOps. Learn to streamline operations, accelerate software delivery, and foster collaboration between development and operations teams.

CONTACT
+44 (0)20 8446 7555

[email protected]

SHARE

 

Copyright © 2024 JBI Training. All Rights Reserved.
JB International Training Ltd  -  Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS

Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us

POPULAR

Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course