8 September 2023
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.
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:
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.
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.
By default, Ansible configuration and files are located in /etc/ansible/
. The key files and directories are:
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.
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.
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.
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.
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.
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.
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 taskThese let you test and troubleshoot your playbooks. You can also run playbooks in parallel mode to speed up execution on multiple servers.
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 distrosyum
- Package management on RedHat based distrosservice
- Manage servicescopy
- Copy files from local or remote locationsgit
- Deploy software or files from git checkoutsuser
- User account managementping
- Test connectivity to hostsThere 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.
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.
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.
Ansible provides a simple yet powerful way to automate IT configurations and workflows.
Key takeaways from this beginner's Ansible guide:
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.
Ansible can be run from any machine with Python installed. Managed nodes only require SSH access from the control machine where Ansible is run.
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.
Yes, Ansible excels at both configuration management as well as application deployment. Playbooks can automate multi-tier deployments across development, testing and production environments.
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.
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
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