Main Page

Tuesday, 9 February 2021

Ansible Playbooks

 What is an Ansible playbook?

An Ansible playbook is a blueprint of automation tasks which are complex IT actions executed with limited or no human involvement. Ansible playbooks are executed on a set, group, or classification of hosts, which together make up an Ansible inventory.

Ansible playbooks are essentially frameworks, which are prewritten code developers can use ad-hoc or as starting template. Ansible playbooks are regularly used to automate IT infrastructure (such as operating systems and Kubernetes platforms), networks, security systems, and developer personas (such as Git and Red Hat CodeReady Studio).

Ansible playbooks help IT staff program applications, services, server nodes, or other devices without the manual overhead of creating everything from scratch. And Ansible playbooks as well as the conditions, variables, and tasks within them can be saved, shared, or reused indefinitely.

How do Ansible playbooks work?

Ansible modules execute tasks. One or more Ansible tasks can be combined to make a play. Two or more plays can be combined to create an Ansible playbook. Ansible playbooks are lists of tasks that automatically execute against hosts. Groups of hosts form your Ansible inventory.

Each module within an Ansible playbook performs a specific task. Each module contains metadata that determines when and where a task is executed, as well as which user executes it. There are thousands of other Ansible modules that perform all kinds of IT tasks, such as:

Cloud management

oci_vcn creates, deletes, or updates virtual cloud networks in Oracle Cloud Infrastructure environments. Similarly, vmware_cluster adds, removes, or updates VMware vSphere clusters.

User management

selogin maps Linux operating system (OS) users to SELinux user, and gitlab_user creates, updates, or deletes GitLab users.

Networking

Dozens of modules handle application programming interfaces (APIs); Cisco IOS, NXOS, and IOS XR devices; as well as F5 BIG-IP services.

Security

Openssh_cert generates an OpenSSH host or user certificates, and ipa_config manages global FreeIPA configuration settings.

Configuration management

pip manages Python library dependencies while assemble consolidates configuration files from fragments.

Communication

mail can automatically send emails based on certain criteria, and snow_record creates, deletes, or updates a single record in ServiceNow.

How do I use Ansible playbooks?

Ansible uses the YAML syntax. Depending on whom you ask, YAML stands for yet another markup language or YAML ain’t markup language (a recursive acronym). There are also 2 different, but perfectly acceptable, YAML file extensions: .yaml or .yml.

There are 2 ways of using Ansible playbooks: From the command line interface (CLI) or using the Red Hat Ansible Automation Platform’s push-button deployments.

From the CLI

After installing the open source Ansible project or Red Hat Ansible Automation Platform (which is as straightforward as typing sudo yum install ansible in the Red Hat Enterprise Linux CLI), all you need to do is use the ansible-playbook command to run Ansible playbooks.

From within the platform

The Red Hat Ansible Automation Platform web-based user interface includes push-button Ansible playbook deployments that are used as part of larger jobs (or job templates). These deployments come with additional safeguards that are particularly helpful to users who are newer to IT automation or those without as much experience working in the CLI.

Intro to playbooks

Ansible Playbooks offer a repeatable, re-usable, simple configuration management and multi-machine deployment system, one that is well suited to deploying complex applications. If you need to execute a task with Ansible more than once, write a playbook and put it under source control. Then you can use the playbook to push out new configuration or confirm the configuration of remote systems.

Playbooks can:

  • declare configurations
  • orchestrate steps of any manual ordered process, on multiple sets of machines, in a defined order
  • launch tasks synchronously or asynchronously

Playbook syntax

Playbooks are expressed in YAML format with a minimum of syntax. A playbook is composed of one or more ‘plays’ in an ordered list. The terms ‘playbook’ and ‘play’ are sports analogies. Each play executes part of the overall goal of the playbook, running one or more tasks. Each task calls an Ansible module.

Playbook execution

A playbook runs in order from top to bottom. Within each play, tasks also run in order from top to bottom. Playbooks with multiple ‘plays’ can orchestrate multi-machine deployments, running one play on your webservers, then another play on your database servers, then a third play on your network infrastructure, and so on. At a minimum, each play defines two things:

  • the managed nodes to target, using a pattern
  • at least one task to execute

In this example, the first play targets the web servers; the second play targets the database servers:

---
- name: update web servers
  hosts: webservers
  remote_user: root

  tasks:
  - name: ensure apache is at the latest version
    yum:
      name: httpd
      state: latest
  - name: write the apache config file
    template:
      src: /srv/httpd.j2
      dest: /etc/httpd.conf

- name: update db servers
  hosts: databases
  remote_user: root

  tasks:
  - name: ensure postgresql is at the latest version
    yum:
      name: postgresql
      state: latest
  - name: ensure that postgresql is started
    service:
      name: postgresql
      state: started

Your playbook can include more than just a hosts line and tasks. For example, the playbook above sets a remote_user for each play. This is the user account for the SSH connection. You can add other Playbook Keywords at the playbook, play, or task level to influence how Ansible behaves. Playbook keywords can control the connection plugin, whether to use privilege escalation, how to handle errors, and more. To support a variety of environments, Ansible lets you set many of these parameters as command-line flags, in your Ansible configuration, or in your inventory. Learning the precedence rules for these sources of data will help you as you expand your Ansible ecosystem.

Task execution

By default, Ansible executes each task in order, one at a time, against all machines matched by the host pattern. Each task executes a module with specific arguments. When a task has executed on all target machines, Ansible moves on to the next task. You can use strategies to change this default behavior. Within each play, Ansible applies the same task directives to all hosts. If a task fails on a host, Ansible takes that host out of the rotation for the rest of the playbook.

When you run a playbook, Ansible returns information about connections, the name lines of all your plays and tasks, whether each task has succeeded or failed on each machine, and whether each task has made a change on each machine. At the bottom of the playbook execution, Ansible provides a summary of the nodes that were targeted and how they performed. General failures and fatal “unreachable” communication attempts are kept separate in the counts.

Desired state and ‘idempotency’

Most Ansible modules check whether the desired final state has already been achieved, and exit without performing any actions if that state has been achieved, so that repeating the task does not change the final state. Modules that behave this way are often called ‘idempotent.’ Whether you run a playbook once, or multiple times, the outcome should be the same. However, not all playbooks and not all modules behave this way. If you are unsure, test your playbooks in a sandbox environment before running them multiple times in production.

Running playbooks

To run your playbook, use the ansible-playbook command:

ansible-playbook playbook.yml -f 10

Use the --verbose flag when running your playbook to see detailed output from successful modules as well as unsuccessful ones.

Ansible-Pull

Should you want to invert the architecture of Ansible, so that nodes check in to a central location, instead of pushing configuration out to them, you can.

The ansible-pull is a small script that will checkout a repo of configuration instructions from git, and then run ansible-playbook against that content.

Assuming you load balance your checkout location, ansible-pull scales essentially infinitely.

Run ansible-pull --help for details.

Verifying playbooks

You may want to verify your playbooks to catch syntax errors and other problems before you run them. The ansible-playbook command offers several options for verification, including --check, --diff, --list-hosts, list-tasks, and --syntax-check.

ansible-lint

You can use ansible-lint for detailed, Ansible-specific feedback on your playbooks before you execute them. For example, if you run ansible-lint on the playbook called verify-apache.yml near the top of this page, you should get the following results:

$ ansible-lint verify-apache.yml

[403] Package installs should not use latest

verify-apache.yml:8

Task/Handler: ensure apache is at the latest version

The ansible-lint default rules page describes each error. For [403], the recommended fix is to change state: latest to state: present in the playbook.

No comments:

Post a Comment