Ansible Playbook Roles





In this article, we will read about ansible-playbook roles. what is this and how does it work.

Roles let you automatically load related vars, files, tasks, handlers, and other Ansible artifacts based on a known file structure. After you group your content into roles, you can easily reuse them and share them with other users.

Roles provide a framework for fully independent, or interdependent collections of variables, tasks, files, templates, and modules.

In Ansible, the role is the primary mechanism for breaking a playbook into multiple files. This simplifies writing complex playbooks, and it makes them easier to reuse. The breaking of the playbook allows you to logically break the playbook into reusable components.

An Ansible role has a defined directory structure with eight main standard directories. You must include at least one of these directories in each role. You can omit any directories the role does not use.

For example:

# playbooks
site.yml
webservers.yml
fooservers.yml
roles/
    common/
    tasks/
    handlers/
    library/
    files/
    templates/
    vars/
    defaults/
    meta/
    webservers/
    tasks/
    defaults/
    meta/


tasks/main.yml - the main list of tasks that the role executes.

handlers/main.yml - handlers, which may be used within or outside this role.

library/my_module.py - modules, which may be used within this role.

defaults/main.yml - default variables for the role. These variables have the lowest priority of any variables available and can be easily overridden by any other variable, including inventory variables.

vars/main.yml - other variables for the role.

files/main.yml - files that the role deploys.

templates/main.yml - templates that the role deploys.

meta/main.yml - metadata for the role, including role dependencies.

Process:-

[user@ip]# mkdir -p playbook/roles/webserver/tasks

[user@ip]# tree                      (It will show tree hierarchy of playbook roles)

[user@ip]# cd playbook/

[user@ip playbook]# touch roles/webserver/tasks/main.yml

[user@ip playbook]# touch master.yml

[user@ip playbook]# vi roles/webserver/tasks/main.yml

inside main.yml type

-name: install apache
yum: pkg=httpd state=latest


and the save it and exit

[user@ip playbook]# vi master.yml

--- #Playbook Roles
- host: all
  user: ansible
 become: yes
 connection: ssh
 roles:
    - webserver


and then save it and exit

[user@ip playbook]# ansible-playbook master.yml



 Ansible Playbook Vault


In this article, we will read about ansible-playbook vault. what is a vault and how to write code ansible-playbook vault.

Ansible allows keeping sensitive data such as passwords or keys in encrypted files rather than plain text in your playbooks.




Creating a new encrypted playbook
#ansible-vault create vault.yml

Edit the encrypted playbook
#ansible-vault edit vault.yml

To change the password encrypted playbook
#ansbile-vault rekey vault.yml

To encrypt an existing playbook
#ansible-vault encrypt vault.yml

To decrypt an encrypted playbook
#ansible-vault decrypt target.yml

Ansible Playbooks conditions

In this article, we will see ansible-playbook condition which is more important and whenever we have different scenarios, we put conditions according to the scenario.

                                                            


When statement

Sometimes you want to skip a particular command on a particular node.


--- # Condition Playbook

- hosts: demo
  user: ansible
  become: yes
  connection: ssh
  tasks:
        - name: install apache on debian
          command: apt-get -y apache2
          when: ansible_os_family=="Debian"
        - name: install apache for redhat
          command: yum -y install https
          when: ansible_os_family=="RedHat"

See diagram for your reference that how to write code in playbook and output after execution file.







Ansible Playbook

Playbooks are the files where Ansible code is written. Playbooks are written in YAML format. YAML stands for Yet Another Markup Language. It is human-readable data serialization language and commonly used for configuration files.

Playbook is like a file where you write codes consist of vars, tasks, handlers, files, templates and roles.

Each playbook is composed of one or more modules in a list and Module is a collection of configuration files.




Playbooks are divided into many sections such as -

Target Section = Defines that host against which playbooks task has to be executed



Variable Section = variables are names used to hold one or more values

Task Section = List of all modules that we need to run in order.

YAML (Yet another Markup Language)


For ansible, nearly every YAML files start with a list. Each item in the list is a list of key-value pairs commonly call a dictionary. 

All YAML files have to begin with "---" and end with "..."

All members of a listed line must begin with the same indentation level starting with "-"

for example:

--- # A list of fruits
    fruits:
        - Apple
        - Mango
        - Banana
        - Pineapple
        - Grapes



A dictionary is represented in a simple key: value form

for example:

--- # A list of customer
- customer:
        name: Rakesh
        job: Trainer
        skills: Ansible
        exp: 7 years

Extension for playbook files is .yml

Note:- There should be space between : and value

[user@ip]# vi target.yml

--- # First Test playbook
    - hosts: demo
      user: ansible
      become: yes
      connection: ssh
      gather_facts: yes

now to execute this playbook

[user@ip]# ansible-playbook target.yml








Ansible Ad-hoc commands





Ad-hoc commands are commands which can be run individually to perform quick functions.

These ad-hoc commands are not used for configuration management and development because these commands are of one-time usage.

The ansible ad-hoc commands use /usr/bin/ansible command line tool to automate a single task.

                           


Ad hoc commands Syntax


Syntax:

#ansible <hosts> -a <"arguments"> -u <username> [--become]

Ex:

#ansible demo -a “ls”

Explanation

Hosts: It can be an entry in the inventory file. For specifying all hosts in the inventory, use all or "*".

Arguments: We should pass values that are required by the module. It can change according to the module used.

Username: It specifies the user account in which Ansible can execute commands.

Become: It's an optional parameter specified when we want to run operations that need sudo privilege. By default, it becomes false.


Ad-hoc commands

To check ls on demo group of hosts :

[ansible@ip]#ansible demo -a “ls”


To create files on demo group of hosts :

[ansible@ip]#ansible demo -a “touch file1”


To create files on all group of hosts :

[ansible@ip]#ansible all -a “touch file2”


To check list of hidden file with detailed demo group of hosts :

[ansible@ip]#ansible demo -a “ls -al”


To install httpd on demo group of hosts :

[ansible@ip]#ansible demo -a “sudo yum install httpd –y”


To install httpd on demo group with sudo permission of hosts :

[ansible@ip]#ansible demo -ba “yum install httpd –y”


To uninstall httpd on demo group with sudo permission of hosts :

[ansible@ip]#ansible demo -ba “yum remove httpd –y”






Ansible Modules


Ansible modules are discrete units of code which can be used from the command line or in a playbook task. The modules also referred to as task plugins or library plugins in Ansible.

Ansible ships with several modules that are called module libraries, which can be executed directly or remote hosts through the playbook.




Users can also write their modules. These modules can control services, system resources, files, or

packages, etc. and handle executing system commands.





Ansible Modules Syntax


Syntax

# ansible <hosts> -b [sudo] -m <module_name> -a <"arguments"> -u <username>

Explanation

Hosts: It can be an entry in the inventory file. For specifying all hosts in the inventory, use all or "*".

Modules: There are hundreds of modules available in the Ansible, such as shell, yum, apt, file, and copy. By default, it is the command.

Arguments: We should pass values that are required by the module. It can change according to the module used.

Username: It specifies the user account in which Ansible can execute commands.

Become: It's an optional parameter specified when we want to run operations that need sudo privilege. By default, it becomes false.

Ansible Modules Commands



State use:
installed - present
remove - absent
update - latest


To install httpd on demo group with sudo permission :

[user@ip]#ansible demo -b -m yum -a “pkg=httpd state=present”


To update httpd on demo group with sudo permission :

[user@ip]#ansible demo -b -m yum -a “pkg=httpd state=latest”


To remove httpd on demo group with sudo permission :

[user@ip]#ansible demo -b -m yum -a “pkg=httpd state=absent”


To restart httpd service on demo group with sudo permission :

[user@ip]#ansible demo -b -m service -a “pkg=httpd state=started”


To create user on demo group with sudo permission:

[user@ip]#ansible demo -b -m user -a “name=raj”


To copy file on demo group with sudo permission:

[user@ip]#ansible demo -b -m copy -a “src=file1 dest=/tmp”




 Ansible Handlers, variable, Loops & Dry Run


In this article we are going to read about Ansible handlers, variable, loops, and Dry Run. what are these and how does it work. please read the article very carefully and let us know if any assist require.




Variable

Ansible uses variables that are defined previously to enable more flexibility in playbooks and roles they can be used to loop through a set of given values, access various information like the hostname of a system, and replaces it. certain strings in templates with specific values.

Variable in playbooks are very similar to using variables in any programming language. It helps you use and assign a value to a variable and use it anywhere in the playbook. One can put conditions around the value of the variables and accordingly use them in the playbook.

Put variable section above tasks so that we define it first & use it later.



[user@ip]# vi vars.yml

--- # My variable playbook

- hosts: demo
  user: ansible
  become: yes
  connection: ssh

var:
       pkgname: httpd
tasks:
    - name: install httpd server
      action: yum name=“{{pkgname}}” state=installed

now to execute this playbook

[user@ip]# ansible-playbook vars.yml




Handlers Section

A handler is exactly the same as a task, but it will run when called by another task.

Handlers are just like regular tasks in an ansible playbook but are only run if the task contains a notify directive and indicates that it changed.

[user@id]# vi handlers.yml

--- # handlers playbook

- hosts: demo
  user: ansible
  become: yes
  connection: ssh
tasks:
   - name: install httpd server
     action:yum name=httpd state=installed
     name: restart Httpd
handlers:
   - name: restart Httpd
     action: service name=httpd state=restarted

now execute this playbook

[user@id]# ansible-playbook handlers.yml





Dry Run

Check whether the playbook is formatted correctly or not.

[user@id]# ansible-playbook handlers.yml --check

Loops

Ansible offers the loop, with_<lookup>, and until keywords to execute a task multiple times. Examples of commonly-used loops include changing ownership on several files and/or directories with the file module, creating multiple users with the user module, and repeating a polling step until a certain result is reached.

--- # My Loops playbook

- hosts: demo
user: ansible
become: yes
connection: ssh
tasks:
    - name: add a list of users
      user: name=“{{username}}” state=present
      with_username:
            - Sachin
            - einstein
            - vasco

now to execute this playbook

[user@ip]# ansible-playbook loops.yml






Ansible Inventory Host Pattern





How to establish SSH connection between server to hosts

Go to AWS account => Create 3 EC2 instances in same AZ => Take access of all machines via putty.


 
Now go inside the ansible server and download ansible packages

=> wget https://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

Now do “ls” to check file download and run command to install

#yum install epel-release-latest-6.8.noarch.rpm
#yum update –y

Now we have to install the package one by one of ansible and dependencies 

#yum install git python python-level python-pip openssl ansible -y

Now go to hosts file mode ansible copy and paste private ip of host1 and host2

#vi /etc/ansible/hosts
[demo] (add any group name under group and ip address)
192.168.0.1
192.168.0.2

Now the host file is only working after updating ansible.cfg file

#vi /etc/ansible/ansible.cfg

Uncomment these things.

#inventory = /etc/ansible/hosts
#sudo-user = root

This step need when you don’t want to give root access to any one so you need to create an ansible user

Create one ansible users in all three instances:
#adduser ansible

Set password on the user:
#passwd ansible

Now switch as ansible user:
#su – ansible

Ansible user does not have sudo permission right now, if you want to give sudo permission to ansible user:

#visudo

Now go inside this file and type these line below root: (ansible means user) 

root ALL=(ALL) ALL
ansible ALL=(ALL) NOPASSWD:ALL


Now do this thing in other nodes also and go to ansible server and try to install httpd package as a ansible user:

#sudo yum install httpd –y

Establish connection between server and node go to ansible server:
#ssh <private ip address> error: permission denied 

We have to do some changes in sshd-config file go to ansible server
#vi /etc/ssh/sshd-config
#service sshd restart

Uncomment below lines
PermitRootLogin yes
&
PasswordAuthentication yes
& comment below next first line  
#PasswordAuthentication no

now you can access but it will ask for password every time when you connect host1 and host2 so will have to do next steps.

Generate RSA key and copy public key on both hosts: 

Now go to ansible server and create keys run the command as ansible user:

#ssh-keygen
#ls –a (see hidden file .ssh)
#cd .ssh/
#ls  (see public and private key as id_rsa & id_rsa_pub)

We need to copy the public key in both hosts

#ssh-copy-id ansible@192.168.0.1  (ansible is user and private ip address) 


#ssh-copy-id ansible@192.168.0.2  (ansible is user and private ip address)

Now verify so go to ansible user and check that you can take ssh access with any password and you can install any package with password

Host patterns



When you execute Ansible through an ad hoc command or by running a playbook, you must choose which managed nodes or groups you want to execute against. Patterns let you run commands and playbooks against specific hosts and/or groups in your inventory. An Ansible pattern can refer to a single host, an IP address, an inventory group, a set of groups, or all hosts in your inventory. Patterns are highly flexible - you can exclude or require subsets of hosts, use wildcards or regular expressions,
 and more. Ansible executes on all inventory hosts included in the pattern.

“all” pattern refer to all the machines in an inventory 

ansible all –list-hosts
ansible <group-name> --list-hosts
ansible <group-name>[0] --list-hosts

groupname[0] => picks first machine of group
groupname[1] => picks second machine of group
groupname[-1] => picks last name of group
groupname[0:1] => picks first two machine in the group
groupname[3:5] => picks 4,5 & 6 machine in the group

Group separated by colon can be used to use hosts from multiple groups
groupname1:groupname2     =>  i.e demo[1]:dev[1:4]





What is Ansible?


Ansible is an open-source IT Configuration Management, Deployment, and Orchestration Tool. It aims to provide large productivity gains to a wide variety of automation challenges. It’s an agentless tool and uses SSH for connectivity.

Then Ansible executed these modules and removed them after they finished. The library of modules can reside on any machine, and there are no daemons, servers, or databases required.

It’s work on push mechanism and uses YAML language which is human-readable language.





We can use this tool whether your servers are on-premised or in the Cloud.

It turns your code into infrastructure(IAC means – Infrastructure as code) i.e. your computing environment has some of the same attributes as your application.


Ansible History

  • Michael Dehaan developed ansible and the ansible project in February 2012
  • Redhat acquire the ansible tool in 2015
  • Ansible is available for RHEL , Debian, Centos, Oracle, Linux etc
  • Ansible tower is enterprise version where you will get GUI interface also and it’s paid.

Ansible Terms



Ansible Advantages and Disadvantages


Advantages:



  • Ansible is free to use.
  • Ansible is very consistent and lightweight and no constraints regarding the O.S or      underlying hardware present.
  • It is very secure due to its agentless capabilities and open SSH security features.
  • Ansible does not need any special system administrator skills to install and use it
  • It works on the Push mechanism.

Disadvantages:

  • An insufficient user interface, though ansible tower is in GUI.
  • Can not achieve full automation by ansible.
  • New to the market, therefore limited support and documentation are available.