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”