Playbook in Ansible

A play book is a list of dictionaries , and dictionary is called play in the Ansible playbook.

Let’s take a playbook as example:

- name: Configure webserver with nginx
  hosts: webservers
  sudo: True
  tasks:
    - name: install nginx
      apt: name=nginx update_cache=yes
    - name: copy nginx config file
      copy: src=files/nginx.conf dest=/etc/nginx/sites-available/default
    - name: enable configuration
      file: >
        dest=/etc/nginx/sites-enabled/default
        src=/etc/nginx/sites-available/default
        state=link
    - name: copy index.html
      template: src=templates/index.html.j2
               dest=/usr/share/nginx/html/index.html mode=0644
    - name: restart nginx
      service: name=nginx state=restarted 

Every play must contain:
• A set of
hosts to configure
• A list of
tasks to be executed on those hosts

Tasks

In the example playbook, we have 5 tasks.

The first task of the play:

- name: install nginx
apt: name=nginx update_cache=yes

The name dictionary is optional, so it’s perfectly valid to write the first task like: - apt: name=nginx update_cache=yes
Every task must contain a key with the name of a module and a value with the arguments to that module. In the preceding example, the module name is apt and the arguments are name=nginx update_cache=yes.
These arguments tell the apt module to install the package named nginx and to update the package cache (the equivalent of doing an apt-get update) before installing the package.

Optional settings

name
  A comment that describes what the play is about. Ansible will print this out when the play starts to run.
sudo
  If true, Ansible will run every task by sudo’ing as (by default) the root user. This is useful when managing linux servers, since by default you cannot SSH as the root user.
vars
  A list of variables and values. We’ll see this in action later in this chapter.

Users and Connections

sudo( pre ansible 2.2) / become ( after 2.2): Set this to yes if you want Ansible to use sudo to become the root once it is connected to the machines in the play.

user: This defines the username to connect to the machine originally, before running sudo if configured.

sudo_user: This is the user that Ansible will try and become using sudo. For example, if we set sudo to yes and user to daniel, setting sudo_user to kate will cause Ansible to use sudo to get from daniel to kate once logged in. If you were doing this in an interactive SSH session, we could use sudo -u kate while you are logged in as daniel.

Connection: This allows us to tell Ansible what transport to use to connect to the remote host. We will mostly use ssh or paramiko for remote hosts. However, we could also use local to avoid a connection overhead when running things on the localhost. Most of the time we will be using either local, winrm or ssh here.

Password options

Always keep in mind that there are two password you need to handle: one for the connection and one for the execution. You may get prompt for password every time you run the playbook with below switches:

  • -k ( lower case) : ask for the connection password, which is password for the user.
  • -K ( upper case ): ask for the sudo password, which is for the sudo_user.

To run the playbook of the banner of the day, you use below command:

ansible-playbook -k -K /etc/ansible/playbooks/MOTD.ymal

You may get different error if one of them is wrong:

  • missing sudo password, which is -K option:
    ansible-playbook -k playbooks/MOTD.ymalSSH password: PLAY [websites] ******************************************************************************************************************

    TASK [Gathering Facts] ***********************************************************************************************************

    fatal: [xxxx.com]: FAILED! => {“msg”: “Missing sudo password”}

  • missing connection user password, which is -k option:
    ansible-playbook -K playbooks/MOTD.ymalBECOME password: PLAY [websites] ******************************************************************************************************************

    TASK [Gathering Facts] ***********************************************************************************************************

    fatal: [[email protected]]: UNREACHABLE! => {“changed”: false, “msg”: “Failed to connect to the host via ssh: [email protected]: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).”, “unreachable”: true}

    PLAY RECAP ***********************************************************************************************************************

    [email protected]            : ok=0    changed=0    unreachable=1    failed=0    skipped=0    rescued=0    ignored=0 

 

Variables

Variable declarations, which happen in the vars section, look like the values in the target section and contain a YAML dictionary or a list.

An example looks like the following code snippet:

vars:
  apache_version: 2.6
  motd_warning: 'WARNING: Use by ACME Employees ONLY'
  testserver: yes

External variable file: Variables can also be loaded from external YAML files by giving Ansible a list of variable files to load. This is done in a similar way using the vars_files directive.

Using vars_files, the files look like the following code snippet in our playbook:

  ---
  - hosts: websites
    become: yes
    user: frank
    vars:
      apache_version: 2.6
      testserver: yes
    vars_files:
      /etc/ansible/apache_vars.yml
    tasks:
      - name: setup a MOTD
        copy:
          dest: /etc/motd
          content: "{{ motd_warning }}"

In the previous example, Ansible looks for /etc/ansible/apache_vars.yml. The YAML file looks similar to the following code snippet:

---
motd_warning: "WARNING: Authorized access ONLY  Do not risk your future PLZ"

Interactive variable: Finally, we can make Ansible ask the user for each variable interactively.

Running state

When you run ansible-playbook, Ansible outputs status information for each task it executes in the play.
OKIf the state of the host matches the arguments of the module, then Ansible takes no action on the host and responds with a state of ok.
Changed – On the other hand, if there is a difference between the state of the host and the arguments to the module, then Ansible will change the state of the host and return
changed.

Reference

https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html

 

Issue:

 

| FAILED | rc=-1 >>

to use the 'ssh' connection type with passwords, you must install the sshpass program

Ansible says it needs sshpass to be able to run ssh commands without prompting passwords.

Ok, let’s do the last step by installing sshpass;

On Ubuntu

apt-get install sshpass

or if you’re running Ansible on OSX

brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb

 

 

Reference

YAML tutorial:  https://gettaurus.org/docs/YAMLTutorial/

YAML indentation: https://docs.saltstack.com/en/latest/topics/troubleshooting/yaml_idiosyncrasies.html