Ansible Basics
NAME HERE, TITLE HERE
COMPANY HERE
WHAT YOU WILL LEARN
Ansible is capable of handling many powerful automation tasks with the flexibility to adapt to many environments and workflows. With Ansible, users can very quickly get up and running to do real work.
In this presentation, we will cover:
What is Ansible
How Ansible Works
Ad-Hoc Commands
Playbook Basics
Reuse and Redistribution of Ansible Content with Roles
Ansible Tower
WHAT IS ANSIBLE AUTOMATION?
The Ansible project is an open source community sponsored by Red Hat. It’s also a simple automation language that perfectly describes IT application environments in Ansible Playbooks .
Ansible Engine is a supported product built from the Ansible community project.
Ansible Tower is an enterprise framework for controlling, securing, managing and extending your Ansible automation (community or engine) with a UI and RESTful API .
The Ansible Project is open source and sponsored by Red Hat.
Ansible Engine is a supported product built from the Ansible community project, and Ansible Tower is the framework for the automation that Ansible Engine does.
There’s also an open-source version of Tower which is the AWX project, and it’s associated with the Ansible GitHub.
WHY ANSIBLE?
So why should you think about using Ansible and what sets it apart?
First off, Ansible is simple: we expect that your user base is going to be mixed with people of all skill levels and because of that we wanted to make it incredibly easy to get started. The language playbooks are written in is YAML, which is very easy-to-read for humans, and those playbooks work consistently across many environments
It’s also extremely powerful in how many nodes we can spin up and manage at any given time, which is largely due to the fact that Ansible is agentless. There are no agents to keep up to date and the requirements are minimal.
THE ANSIBLE WAY
CROSS PLATFORM – Linux, Windows, UNIX
Agentless support for all major OS variants, physical, virtual, cloud and network.
HUMAN READABLE – YAML
Perfectly describe and document every aspect of your application environment
PERFECT DESCRIPTION OF APPLICATION
Every change can be made by playbooks, ensuring everyone is on the same page.
VERSION CONTROLLED
Playbooks are plain-text. Treat them like code in your existing version control.
DYNAMIC INVENTORIES
Capture all the servers 100% of the time, regardless of infrastructure, location, etc.
ORCHESTRATION THAT PLAYS WELL WITH OTHERS – HP SA, Puppet, Jenkins, RHNSS, etc.
Homogenize existing environments by leveraging current toolsets and update mechanisms.
In addition, that agentless support isn’t just Linux exclusive.
This also applies to Windows machines, networking devices, and of course both physical and cloud servers, as well as static or dynamic inventory.
Also, one of the main selling points of Ansible is that we work well with existing toolkits.
Sometimes people don’t know where to start; I’d advise you to pick a pain point in your environment to focus on, something small that you can leverage Ansible for and see how that feels, because you can always homogenize over time.
BATTERIES INCLUDED
Ansible comes bundled with hundreds of modules for a wide variety of automation tasks:
cloud
containers
database
files
messaging
monitoring
network
notifications
packaging
source control
system
testing
utilities
web infrastructure
Installing Ansible nets you a TON of modules that range in type from the popular cloud modules to packaging and database modules.
The list you see here are some of the “high profile” modules, but there are lots more that aren’t listed.
COMMUNITY
THE MOST POPULAR OPEN-SOURCE AUTOMATION COMMUNITY ON GITHUB
34,000+ stars & 13,500+ forks on GitHub
4000+ GitHub Contributors
Over 2000 modules shipped with Ansible
New contributors added every day
1400+ users on IRC channel
World-wide meetups taking place every week
Ansible Galaxy: over 9,000 contributors and 18,000 roles
500,000+ downloads a month
AnsibleFests, Ansible Automates, and other global events
ANSIBLE: COMPLETE AUTOMATION
One of the other bullet points that we highlight around Ansible is that it’s the complete package.
So it’s not just configuration management; it’s also orchestration, app-deployment and provisioning as well.
Looking at this graphic here , you can see that there are tools that definitely perform one or more of these use cases, but can’t do them all and that’s really one of the big strengths of Ansible.
Some users like to refer to it as “Automation Glue”.
WHAT CAN I DO WITH ANSIBLE?
Automate the deployment and management of your entire IT footprint.
On this slide, you can see the different use cases for how to manage and automate your machines.
(some examples are: security and compliance, orchestration, creating new VMs, creating a CI/CD pipeline) - all of these things can be done with Ansible.
INSTALLING ANSIBLE
# the most common and preferred way of installation
$ pip install ansible
# install the epel-release RPM if needed on CentOS, RHEL, or Scientific Linux
$ sudo yum install ansible
# you will need the PPA repo configured
$ sudo apt-get install ansible
There are many ways to install Ansible, including making your own rpm package, running from source, or you can just use a package manager. As you can see, the examples below are using pip, yum, and apt.
The yum and apt installations require additional steps so if you prefer using a single command, then you can install with pip.
1 - Most common and preferred way (unless your Python is set up weird)
2 - If you’re running a RHEL or CentOS type of machine, install epel-release and grab the package from there
3- Ubuntu/Debian flavor OS
If anything stumps you, it’s always helpful to take a look at the Ansible Installation documentation for more information.
HOW ANSIBLE WORKS
Once you have Ansible installed, you’re going to need to become acquainted with the key components of how Ansible works.
The graphic on this slide shows the relationship between all the main pieces of Ansible, starting with the user who writes an Ansible playbook.
MODULES
Modules are bits of code transferred to the target system and executed to satisfy the task declaration.
apt/yum
copy
file
get_url
git
ping
debug
service
synchronize
template
uri
user
wait_for
assert
We talked a bit about modules in the previous couple slides, but I did want to point out a list of some commonly used modules that you may see out in example repos, blog posts, etc. a fair amount.
Typically, you're going to see a lot of package management modules being used, lots of file modules like copy and file, but as mentioned previously, there are tons more as well.
MODULES
https://docs.ansible.com/ansible/latest/modules/modules_by_category.html
You can check out all of them by looking at the exhaustive module index on docs.ansible.com.
They’re broken down by category, so you can more easily find what you need.
I would highly recommend bookmarking this page!
MODULES: RUN COMMANDS
If Ansible doesn’t have a module that suits your needs there are the “run command” modules:
command: Takes the command and executes it. The most secure and predictable.
shell: Executes through a shell like /bin/sh so you can use pipes etc. Be careful.
script: Runs a local script on a remote node after transferring it.
raw: Executes a command without going through the Ansible module subsystem.
NOTE: Unlike standard modules, run commands have no concept of desired state and should only be used as a last resort
On this slide we’re gonna discuss the command and shell modules which are super useful because you can execute commands with them on your remote nodes.
The only big difference is that the command is not processed through the shell so redirect options and certain variables won’t work.
If you need those, just use the shell module instead.
The command modules let you run networking commands with Ansible, the same way a network engineer would type them on the command line.
If you have something that’s not a core module or you haven't written a custom one, you can utilize the script module.
For example, if you want to push out a homegrown script, you can do that here.
We also have the raw module, which issues a pure SSH command and bypasses the python module mechanism.
This is handy if you’re talking to a machine that doesn’t have python (for example, a server that’s running Windows!).
AD-HOC COMMANDS
# check all my inventory hosts are ready to be managed by Ansible
$ ansible all -m ping
# run the uptime command on all hosts in the web group
$ ansible web -m command -a “uptime”
# collect and display the discovered for the localhost
$ ansible localhost -m setup
We’re going to transition right into ad-hoc commands from the commands modules because often times, you utilize command/shell to issue one-off commands to your hosts.
This is essentially what ad-hoc commands are; just quick checks on your servers that you don’t want to preserve in an Ansible playbook.
The examples here are pretty typical.
Our first example is just checking whether we have connectivity with the host by issuing the ping command (I do this all the time to make sure everything is responding).
In the second example here, you can see the command to check the uptime on the two servers in my web group using the command module.
And lastly, the third example is gathering facts about our local machine which would yield the information that you can use for conditionals and variables and whatnot.
[a bit of the output is shown on next slide]
SIDEBAR: DISCOVERED FACTS
$ ansible localhost -m setup
localhost | success >> {
"ansible_facts": {
"ansible_default_ipv4": {
"address": "192.168.1.37",
"alias": "wlan0",
"gateway": "192.168.1.1",
"interface": "wlan0",
"macaddress": "c4:85:08:3b:a9:16",
"mtu": 1500,
"netmask": "255.255.255.0",
"network": "192.168.1.0",
"type": "ether"
},
INVENTORY
Inventory is a collection of hosts (nodes) against which Ansible can work with.
Hosts
Groups
Inventory-specific data (variables)
Static or dynamic sources
Ad-hoc commands and modules always come back to the inventory we’re managing. Inventory consists of hosts, groups, inventory specific data, and whether it’s static or dynamic sources. Note that “hosts” has been expanded overtime to include network devices, containers and virtually anything else that is network-addressable.
STATIC INVENTORY EXAMPLE
10.42.0.2
10.42.0.6
10.42.0.7
10.42.0.8
10.42.0.100
This is a free-form static inventory listed by IP address. If I clean that up a bit, I get...
STATIC INVENTORY EXAMPLE
[control]
control ansible_host=10.42.0.2
[web]
node-1 ansible_host=10.42.0.6
node-2 ansible_host=10.42.0.7
node-3 ansible_host=10.42.0.8
[haproxy]
haproxy ansible_host=10.42.0.100
[all:vars]
ansible_user=vagrant
ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key
...a host file that’s separated into groups (which in this example is control, web, and haproxy).
We also have some inventory-specific data where we’re defining ansible_host for each of these different nodes, and we’ve got a vars section defined for all the hosts where we’re setting the connecting user.
There’s also a path to the private key file we’re using for authentication.
STATIC INVENTORY EXAMPLE IN YAML
all:
vars:
ansible_user: vagrant
ansible_ssh_private_key_file: ~/.vagrant.d/insecure_private_key
children:
web:
hosts:
node-1:
ansible_host: 10.42.0.6
node-2:
ansible_host: 10.42.0.7
node-3:
ansible_host: 10.42.0.8
This is a similar example of the same hosts file in YAML format which is a new option as of version 2.4.
This provides some flexibility in regards to the format you might find easier to work with.
VARIABLES
Ansible can work with metadata from various sources and manage their context in the form of variables.
Command line parameters
Plays and tasks
Files
Inventory
Discovered facts
Roles
To go into a little more detail, variables in Ansible are used to account for differences between servers.
By using variables, I have the ability to keep a nice layer of abstraction in my playbook and define my variables as needed in various host or group vars files.
These could be for things like facts or file paths or package versions.
VARIABLE PRECEDENCE
The order in which the same variable from different sources will override each other:
Extra vars
Set_facts/Registered vars
Include_vars
Include_params
Role params
Task vars (only for the task)
Block vars (only for tasks in the block)
Role vars
Play vars_files
Play vars_prompt
Play vars
Host facts
Playbook host_vars
Inventory host_vars
Inventory file/script host vars
Playbook group_vars
Inventory group_vars
Playbook group_vars/all
Inventory group_vars/all
Inventory file or script group vars
Role defaults
This brings up a good time to talk about variable precedence, which is basically the order in which the same variables will override each other.
The latest version has 21 levels of variable precedence wherein extra_vars will always take precedence and role_defaults will get overwritten by all of these other var types.
TASKS
Tasks are the application of a module to perform a specific unit of work.
file: A directory should exist
yum: A package should be installed
service: A service should be running
template: Render a configuration file from a template
get_url: Fetch an archive file from a URL
git: Clone a source code repository
Just to recap, so far we’ve talked about acting against inventory with modules, but those modules are going to be contained in things called tasks.
These are simple and declarative, because we’re telling the module to do something specific like (give examples from slide of things the modules will do within the tasks).
EXAMPLE TASKS IN A PLAY
tasks:
- name: add cache in directory
file:
path: /opt/cache
state: directory
- name: install nginx
yum:
name: nginx
state: latest
- name: restart nginx
service:
name: nginx
state: restarted
In this example, the first task is called “add cache in directory”.
Note that you can name it anything you'd like.
Here we're going to call the file module and give it a couple of options.
Our path is going to be opt/cache and the state is directory, meaning we're going to create the directory opt/cache.
HANDLER TASKS
Handlers are special tasks that run at the end of a play if notified by another task.
Normal tasks run sequentially, handler tasks run on notification.
Handlers may be notified multiple times during a single play, and are triggered when a tasks causes a change in state.
If nothing notifies a handler, it will not run. Regardless of how many tasks notify a handler, it will run only once, after all of the tasks complete in a particular play.
EXAMPLE HANDLER IN A PLAY
tasks:
- name: add cache dir
file:
path: /opt/cache
state: directory
- name: install nginx
yum:
name: nginx
state: latest
notify: restart nginx
handlers:
- name: restart nginx
service:
name: nginx
state: restarted
In this slide, we have an example of a handler in which after we install nginx, we add a notify to restart the services.
Then, there’s a handlers section in which we define that handler.
If the conditions to trigger the handler aren’t met, then the handler won’t run.
Handlers may be notified multiple times during a single play, and are triggered when a task causes a change in state.
PLAYS & PLAYBOOKS
Plays are ordered sets of tasks to execute against host selections from your inventory.
A playbook is a file containing one or more plays.
All these things we’ve been talking about including tasks, handlers, modules, etc. are all part of what make up plays and playbooks.
PLAYBOOK EXAMPLE
---
- name: install and start apache
hosts: web
vars:
http_port: 80
max_clients: 200
remote_user: root
tasks:
- name: install httpd
yum: pkg=httpd state=latest
- name: write the apache config file
template: src=/srv/httpd.j2 dest=/etc/httpd.conf
- name: start httpd
service: name=httpd state=started
ROLES
Roles are a packages of closely-related Ansible content that can be shared more easily than plays alone.
PLAYBOOK EXAMPLE
site.yml
roles/
common/
files/
templates/
tasks/
handlers/
vars/
defaults/
meta/
webservers/
files/
templates/
tasks/
handlers/
vars/
defaults/
meta/
This is how it looks from a project perspective.
Not all of these directories need to be used, these are just standards that are available and ready to fill in with your tasks, handlers, variables, whatever you need for the particular role.
PLAYBOOK WITH ROLES EXAMPLE
# site.yml
---
- hosts: web
roles:
- common
- webservers
This is how you would call a role from the main playbook.
It keeps everything simple and you can switch things out or delete easily without parsing through a huge list of tasks that you’ve made separately for every host type.
ANSIBLE GALAXY
If you’d like to check out our huge community site for Ansible roles, visit Galaxy.Ansible.com.
You can sort through things by author name, stars, number of downloads, as well as other filters, and you can even share your own roles here as well.
WHERE TO FIND PLAYBOOK EXAMPLES
General Examples:
https://github.com/ansible/ansible-examples
Lightbulb:
https://github.com/ansible/lightbulb/tree/master/examples
Ansible + Vagrant:
https://github.com/geerlingguy/ansible-vagrant-examples
WHERE TO FIND PLAYBOOK EXAMPLES
Would you like to learn Ansible? It’s easy to get started:
ansible.com/get-started
Have you used Ansible already? Try Tower for free:
ansible.com/tower-trial
Want to learn more?
ansible.com/whitepapers
If you’d like to learn more about Ansible our Getting Started page is a great resource.
Our documentation is also very thorough and well-written, so check that out as well.
If you’re ready to try Tower you can visit our Tower Trial page, and you can also check out the whitepapers on our website!
Show a playbook written out? Show roles? Tower?