Ansible Essentials Workshop

Pawel Krupa (@paulfantom)

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.

  • What is Ansible and The Ansible Way
  • Installing Ansible
  • How Ansible Works and its Key Components
  • Ad-Hoc Commands
  • Playbook Basics
  • Reuse and Redistribution of Ansible Content with Roles

What is Ansible?

It's a simple automation language that can perfectly describe an IT application infrastructure in Ansible Playbooks.

It's an automation engine that runs Ansible Playbooks.

Ansible Tower is an enterprise framework for controlling, securing and managing your Ansible automation with a UI and RESTful API.

Ansible Is...

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.

Ansible: The Language of DevOps

COMMUNICATION IS THE KEY TO DEVOPS.

Ansible is the first automation language
that can be read and written across IT.

Ansible is the only automation engine
that can automate the entire application lifecycle
and continuous delivery pipeline.

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

Community

THE MOST POPULAR OPEN-SOURCE AUTOMATION COMMUNITY ON GITHUB

  • 13,000+ stars & 4,000+ forks on GitHub
  • 2000+ GitHub Contributors
  • Over 900 modules shipped with Ansible
  • New contributors added every day
  • 1200+ users on IRC channel
  • Top 10 open source projects in 2014
  • World-wide meetups taking place every week
  • Ansible Galaxy: over 18,000 subscribers
  • 250,000+ downloads a month
  • AnsibleFests in NYC, SF, London

http://ansible.com/community

Complete Automation

Use Cases

Installing Ansible


# the most common and preferred way of
# installation
$ sudo pip install ansible

# you will need the EPEL repo configured on
# CentOS, RHEL, or Scientific Linux
$ sudo yum install ansible

# you will need the PPA repo configured on
# Debian or Ubuntu
$ sudo apt-get install ansible
          

Demo Time:
Installing Ansible

Workshop:
Installing Ansible

How Ansible Works

Plays & Playbooks

Modules & Tasks

Plugins

Inventory

Inventory

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

Modules Documentation

http://docs.ansible.com/

Modules Documentation


# List out all modules installed
$ ansible-doc -l
...
copy
cron
...

# Read documentation for installed module
$ ansible-doc copy
> COPY

  The [copy] module copies a file on the local box to remote locations. Use the [fetch] module to copy files from remote locations to the local
  box. If you need variable interpolation in copied files, use the [template] module.

  * note: This module has a corresponding action plugin.

Options (= is mandatory):
...
          

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 on the host. 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.

Inventory

Inventory is a collection of hosts (nodes) with associated data and groupings that Ansible can connect and manage.

  • Hosts (nodes)
  • Groups
  • Inventory-specific data (variables)
  • Static or dynamic sources

Static Inventory Example


10.42.0.2
10.42.0.6
10.42.0.7
10.42.0.8
10.42.0.100
host.example.com
          

Static Inventory Example


[control]
control ansible_host=10.42.0.2

[web]
node-[1:3] ansible_host=10.42.0.[6:8]

[haproxy]
haproxy ansible_host=10.42.0.100

[all:vars]
ansible_user=vagrant
ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key
          

Ad-Hoc Commands

An ad-hoc command is a single Ansible task to perform quickly, but don’t want to save for later.

Ad-Hoc Commands: Common Options

  • -m MODULE_NAME, --module-name=MODULE_NAME
    Module name to execute the ad-hoc command
  • -a MODULE_ARGS, --args=MODULE_ARGS
    Module arguments for the ad-hoc command
  • -b, --become
    Run ad-hoc command with elevated rights such as sudo, the default method
  • -e EXTRA_VARS, --extra-vars=EXTRA_VARS
    Set additional variables as key=value or YAML/JSON
  • --version
    Display the version of Ansible
  • --help
    Display the MAN page for the ansible tool

Ad-Hoc Commands


# check all my inventory hosts are ready to be
# managed by Ansible
$ ansible all -m ping

# collect and display the discovered facts
# for the localhost
$ ansible localhost -m setup

# run the uptime command on all hosts in the
# web group
$ ansible web -m command -a "uptime"
          

Sidebar: Discovered Facts

Facts are bits of information derived from examining a host systems that are stored as variables for later use in a play.


$ 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"
      },
          

Demo Time:
Ad-Hoc Commands

Workshop:
Ad-Hoc Commands

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

Variable Precedence

The order in which the same variable from different sources will override each other.

  1. extra vars
  2. task vars (only for the task)
  3. block vars (only for tasks in block)
  4. role and include vars
  5. play vars_files
  6. play vars_prompt
  7. play vars
  8. set_facts
  1. registered vars
  2. host facts
  3. playbook host_vars
  4. playbook group_vars
  5. inventory host_vars
  6. inventory group_vars
  7. inventory vars
  8. role defaults

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

Example Tasks in a Play


tasks:
- name: httpd package is present
  yum:
    name: httpd
    state: latest

- name: latest index.html file is present
  copy:
    src: files/index.html
    dest: /var/www/html/

- name: restart httpd
  service:
    name: httpd
    state: restarted
          

Handler Tasks

Handlers are special tasks that run at the end of a play if notified by another task when a change occurs.

If a configuration file gets changed notify a service restart task that it needs to run.

Example Handler Task in a Play


tasks:
- name: httpd package is present
  yum:
    name: httpd
    state: latest
  notify: restart httpd

- name: latest index.html file is present
  copy:
    src: files/index.html
    dest: /var/www/html/

handlers:
- name: restart httpd
  service:
    name: httpd
    state: restarted
          

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.

Playbook Example


---
- name: install and start apache
  hosts: web
  become: yes
  vars:
    http_port: 80

  tasks:
  - name: httpd package is present
    yum:
      name: httpd
      state: latest

  - name: latest index.html file is present
    copy:
      src: files/index.html
      dest: /var/www/html/

  - name: httpd is started
    service:
      name: httpd
      state: started
          

Human-Meaningful Naming


 ---
 - name: install and start apache
   hosts: web
   become: yes
   vars:
     http_port: 80

   tasks:
   - name: httpd package is present
     yum:
       name: httpd
       state: latest

   - name: latest index.html file is present
     copy:
       src: files/index.html
       dest: /var/www/html/

   - name: httpd is started
     service:
        name: httpd
        state: started
          

Host Selector


---
- name: install and start apache
  hosts: web
  become: yes
  vars:
    http_port: 80

  tasks:
  - name: httpd package is present
    yum:
      name: httpd
      state: latest

  - name: latest index.html file is present
    copy:
      src: files/index.html
      dest: /var/www/html/

  - name: httpd is started
    service:
      name: httpd
      state: started
          

Privilege Escalation


---
- name: install and start apache
  hosts: web
  become: yes
  vars:
    http_port: 80

  tasks:
  - name: httpd package is present
    yum:
      name: httpd
      state: latest

  - name: latest index.html file is present
    copy:
      src: files/index.html
      dest: /var/www/html/

  - name: httpd is started
    service:
      name: httpd
      state: started
          

Play Variables


---
- name: install and start apache
  hosts: web
  become: yes
  vars:
    http_port: 80

  tasks:
  - name: httpd package is present
    yum:
      name: httpd
      state: latest

  - name: latest index.html file is present
    copy:
      src: files/index.html
      dest: /var/www/html/

  - name: httpd is started
    service:
      name: httpd
      state: started
          

Tasks


---
- name: install and start apache
  hosts: web
  become: yes
  vars:
    http_port: 80

  tasks:
  - name: latest httpd package is present
    yum:
      name: httpd
      state: latest

  - name: latest index.html file is present
    copy:
      src: files/index.html
      dest: /var/www/html/

  - name: httpd is started
    service:
      name: httpd
      state: started
          

Demo Time:
A Simple Playbook Run

Workshop:
Your First Playbook

Doing More with Playbooks

Here are some more essential playbook features that you can apply:

  • Templates
  • Loops
  • Conditionals
  • Tags
  • Blocks

Templates

Ansible embeds the Jinja2 templating engine that can be used to dynamically:

  • Set and modify play variables
  • Conditional logic
  • Generate files such as configurations from variables

Loops

Loops can do one task on multiple things, such as create a lot of users, install a lot of packages, or repeat a polling step until a certain result is reached.


- yum:
    name: "{{ item }}"
    state: latest
  with_items:
  - httpd
  - mod_wsgi
            

Conditionals

Ansible supports the conditional execution of a task based on the run-time evaluation of variable, fact, or previous task result.


- yum:
    name: httpd
    state: latest
  when: ansible_os_family == "RedHat"
            

Tags

Tags are useful to be able to run a subset of a playbook on-demand.


- yum:
    name: "{{ item }}"
    state: latest
  with_items:
  - httpd
  - mod_wsgi
  tags:
     - packages

 - template:
     src: templates/httpd.conf.j2
     dest: /etc/httpd/conf/httpd.conf
  tags:
     - configuration
            

Blocks

Blocks cut down on reptitive task directives, allow for logical grouping of tasks and even in play error handling.


- block:
  - yum:
      name: "{{ item }}"
      state: latest
    with_items:
    - httpd
    - mod_wsgi

  - template:
      src: templates/httpd.conf.j2
      dest: /etc/httpd/conf/httpd.conf
  when: ansible_os_family == "RedHat"
            

Demo Time:
A More Practical Playbook

Workshop:
Practical Playbook Development

Roles

Roles are a packages of closely related Ansible content that can be shared more easily than plays alone.

  • Improves readability and maintainability of complex plays
  • Eases sharing, reuse and standardization of automation processes
  • Enables Ansible content to exist independently of playbooks, projects -- even organizations
  • Provides functional conveniences such as file path resolution and default values

Project with Embedded Roles Example


site.yml
roles/
   common/
     files/
     templates/
     tasks/
     handlers/
     vars/
     defaults/
     meta/
   apache/
     files/
     templates/
     tasks/
     handlers/
     vars/
     defaults/
     meta/
          

Project with Embedded Roles Example


# site.yml
---
- hosts: web
  roles:
     - common
     - apache
          

Ansible Galaxy

http://galaxy.ansible.com

Ansible Galaxy is a hub for finding, reusing and sharing Ansible content.

Jump-start your automation project with content contributed and reviewed by the Ansible community.

Demo Time:
A Playbook Using Roles

Workshop:
Your First Roles

Next Steps

  • It's easy to get started
    ansible.com/get-started
  • Join the Ansible community
    ansible.com/community
  • Would you like to learn a lot more?
    redhat.com/en/services/training/do407-automation-ansible