Ansible


What is ansible?
Ansible is an opensource IT configuration management, deployment and orchestration tool. It aims to provide large productivity gains to a wide variety of automation challenges.

Ansible History:
  • Michael Dehaan developed ansible and the ansible project began in February 2012.
  • Redhat acquired the ansible tool in 2015.
  • Ansible is available for RHEL, Debian, cent OS and oracle Linux.
  • We can use this tool whether your servers are in on-premises or in cloud.
  • It turns your code into infrastructure i.e. your computing environment has some of the same attributes as your application.
Advantages:
  • Ansible is free to use by everyone.
  • Ansible is very consistent and light weight and no constrains regarding the OS or
  • underlying hardware are present.
  • It is very secure due to its agentless capabilities and open SSH security features.
  • Ansible doesn't need any special system administrator skills to install and use it.
  • It is push mechanism.


Disadvantages:
  • Insufficient user interface, though ansible tower is GUI, but it is still in development stage.
  • Cannot achieve full automation by ansible.
  • New to the market, therefore limited support and document is available.
Terms used in Ansible:
  • Ansible Server: the machine where ansible is installed and from which all tasks and Playbooks will be run.
  • Module: basically, a module is a command or set of similar commands meant to be executed
  • on the client side.
  • Task: a task is section that consist of a single procedure to be completed.
  • Role: a way of organizing tasks and related files to be later called playbook.
  • Fact: information fetched from the client form the global variables with the gather facts
  • operation.
  • Inventory: file containing data about the ansible client servers.
  • Play: execution of playbook.
  • Handler: task which is called only if notifier is present.
  • Notifier: section attributed to a task which calls a handler if the output is changed.
  • Playbooks: it consists code in YAML format which describes tasks to be executed.
  • Host: nodes which are automated by ansible.
Installation:
Fallow link you can install based on the distribution you can install using below link

https://docs.ansible.com/ansible/latest/installation_guide/installation_distros.html 

Ad-hoc Commands:
  1. Ad-hoc commands are commands which can be run individually to perform quick functions.
  2. These ad-hoc commands are not used for configuration management and deployment, because these commands are of one-time usage.
  3. The ansible ad-hoc commands uses the /usr/bin/ansible command line tool to automate a single task.
https://docs.ansible.com/ansible/latest/user_guide/intro_adhoc.html

Syntax:

ansible [-i INVENTORY] [server] [-m MODULE] {-a MODULE_OPTIONS}
root@ip-172-31-23-165:/home/ubuntu# ansible all -m ping
localhost | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
root@ip-172-31-23-165:/home/ubuntu# ansible all -a "mkdir a" -b
localhost | CHANGED | rc=0 >>

root@ip-172-31-23-165:/home/ubuntu# ansible all -a "ls -ltr " -b
localhost | CHANGED | rc=0 >>
total 16
-rw-r--r-- 1 root   root      0 Nov 17 06:33 ansible.cfg
-rw-r--r-- 1 root   root     36 Nov 17 06:35 hosts
-rwxr-xr-x 1 ubuntu ubuntu  587 Nov 17 10:47 docker.sh
drwxr-xr-x 5 root   root   4096 Nov 17 11:35 MyResumeDocker
drwxr-xr-x 2 root   root   4096 Nov 17 12:41 a

Ansible Modules: 

Ansible ships with a number of modules (called module library) that can be executed directly on remote hosts or through "playbooks". Your library of modules can reside on any machine and there are no servers, daemons or databases required. 

Q. where ansible modules are stored? The default location of the inventory file is /etc/ansible/hosts.


Below module used to check ansible slave status while pinging

root@ip-172-31-23-165:/home/ubuntu# ansible all -m ping localhost | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python3" }, "changed": false, "ping": "pong" }

root@ip-172-31-23-165:/home/ubuntu#  ansible all -m shell -a uptime
localhost | CHANGED | rc=0 >>
 12:25:45 up 1 min,  2 users,  load average: 0.43, 0.26, 0.10
root@ip-172-31-23-165:/home/ubuntu# ansible all -m shell -a "free -m"
localhost | CHANGED | rc=0 >>
               total        used        free      shared  buff/cache   available
Mem:             966         261         309           1         395         550
Swap:              0           0           0

root@ip-172-31-23-165:/home/ubuntu# ansible all -m apt -a "name=apache2 state=present" -b
localhost | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "cache_update_time": 1668682184,
    "cache_updated": false,
    "changed": false
}

Playbook: 

Playbooks in ansible are written in YAML format. It is human readable data serialization language and is commonly used for configuration files. Playbook is like a file where you write codes consists of variables, tasks, handlers, files, templates and roles. Each playbook is composed of one or more 'modules' in a list. Module is a collections of configuration files. 

Playbooks are divided into many sectors like 

a. Target section: defines the host against which playbooks task has to be executed.
b. Variable: define variables
c. Task section: list of modules that we need to run in an order.


YAML (Yet Another Markup Language): For ansible nearly every YAML files starts with a list. Each item in the list is a list of key-value pairs commonly called as a directory. All YAML files have to begins with "---" and ends with ". All members ofa list lines must begin with same indentation level starting with - 

For e.g:

 --- # a list of fruits
Fruits:
   Mango
   Strawberry
   Banana
   Grapes
   Apple

sample playbook that will install nginx and visuvalise resume 
---
- hosts: all
  #user: root
  become: yes
  gather_facts: yes
  connection: ssh

  tasks:
    - name: installation apache2
      apt: pkg=apache2 state=present
    - name: version check
      apt: pkg=apache2 state=latest
    - name: clone the git directory
      ansible.builtin.command: git clone https://github.com/GudditiNaganjaneyulu/MyResume.git
    - name: copy files to workdir
      copy: src=/root/ansible/MyResume/  dest='{{workdir}}'
    - name: remove Html code after copying
      ansible.builtin.command: rm -rf /root/ansible/MyResume/
      notify: service starting
    - name: service starting
      service: name=apache2 state=restarted
Variables:
Ansible uses variables which 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 host name of a system and replace certain strings in templates with specific values.
Put variable section above tasks so that we define it first and use it later.

---
- hosts: all
  #user: root
  become: yes
  gather_facts: yes
  connection: ssh
  vars:
    workdir: /var/www/html/
  tasks:
    - name: installation apache2
      apt: pkg=apache2 state=present

    - name: version check
      apt: pkg=apache2 state=latest
    - name: clone the git directory
      ansible.builtin.command: git clone https://github.com/GudditiNaganjaneyulu/MyResume.git
    - name: copy files to workdir
      copy: src=/root/ansible/MyResume/  dest='{{workdir}}'
    - name: remove Html code after copying
      ansible.builtin.command: rm -rf /root/ansible/MyResume/
      notify: service starting
    - name: service starting
      service: name=apache2 state=restarted

Handlers Section:
A handler is exactly the same as a task, but it will run when called by another task.
Or
Handlers are just like regular tasks in an ansible playbook, but are only run if the task contains a 'notify' directive and also indicates that it changed something.

---
- hosts: all
  #user: root
  become: yes
  gather_facts: yes
  connection: ssh
  vars:
    workdir: /var/www/html/
  tasks:
    - name: installation apache2
      apt: pkg=apache2 state=present

    - name: version check
      apt: pkg=apache2 state=latest
    - name: clone the git directory
      ansible.builtin.command: git clone https://github.com/GudditiNaganjaneyulu/MyResume.git
    - name: copy files to workdir
      copy: src=/root/ansible/MyResume/  dest='{{workdir}}'
    - name: remove Html code after copying
      ansible.builtin.command: rm -rf /root/ansible/MyResume/
      notify: service starting
  handlers:

    - name: service starting
      service: name=apache2 state=restarted

DRY-RUN:
Check whether the playbook is formatted correctly or not.
Anible-playbook handlers.yml --check

Loops:
Sometimes you want to repeat a task multiple time. In computer programming this is called as loops. 
Common ansible 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 certain result is reached.



---
- hosts: all
  #user: root
  become: yes
  gather_facts: yes
  connection: ssh
  
  tasks:
    - name: creation of users
    - user: name=“{{item}}” state=present
       with item:
         - mini
         - sana
         - ravi

Conditions:

Whenever we have different different scenarios, we put conditions to the scenario. We put conditions in ansible by "when" statement.

---
- hosts: all
  become: yes
  gather_facts: yes
  connection: ssh
  tasks:
    - name: install nginx if family is debian
      command: apt install nginx -y
      when: ansible_os_family == "Debian"
      name: install nginx if family is Redhat
      command: yum install nginx -y
      when: ansible_os_family == "Redhat"


Vault:
Ansible allows keeping sensitive data such as passwords or key in encrypted files, rather that a plaintext 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:
$ ansible-vault rekey vault.yml

To encrypt on existing playbook:

root@ip-172-31-23-165:~/ansible# ansible-vault encrypt playbook.yml
New Vault password:
Confirm New Vault password:
Encryption successful

root@ip-172-31-23-165:~/ansible# cat playbook.yml
$ANSIBLE_VAULT;1.1;AES256
32623235343734643566343131386338376430376162356466326662616434376234353463666638
3834326466393037373463623661313864643731653461380a353363323033353538313364376664
34643735393164653237333032663134643135396632326365636633366337346661333765646535
3035646465323335320a336436336530623963313066623930623962386130643234363466636631
30666261633531623035363164303737343834626332336665386665646332623266353137616130
61363938303363326563336661636138353336346339343364336130393639353339303436643665
33616233663532323039333237323930653031653062613065643633623063663138333161393338
39663561663637663933323833383561363861306130313534373137333130643435626233363831
65333239343635316638323364376533313631363337353464303662363166336164336130303033
66363464363339653636313738333433356630666336326231333631326431333562333439373264
62623335303930303736343332303039646336386463646634633136656464363432633962653661
64363762313937653334306639356664646130613131323835316532396632313036313438323139
35353434646531666636656438323635666230616233333839616436363463373561333531396635
33366464363563623938663734646530316564663866376530623566643066656135323265376134
66333865343237323037623939306262343235336132373539383765326261636164386664616531
65383232353938363561646138313931356230366564653036373466393566386265643364393836
63336164353635663938303237343634643730346565386663643236666431656539306339363663
66643433613161666136343934326238666332303062306564393234343265323263326535323832
66653034373862666639643464623163373965396564663964616138613862356533643832346665
63663563613533303337613862656230323235303161383537653561643237663763386134633166
36343337353537623035613839303432333165663662646638663466303935373230643737663139
61636663653662363934343862636538333037386561323734633962386231366636316333303535
35303937626164373139656463363136336463656132636363323463626539643934633233626561
63623865396532373266646634626631326632643939333664643031663164656133366430323966
39326338613464653633626534333065323633313064366664663434623631316663393964323864
61376237316163626631666638626533303062633833303163333532356531653430316436613433
64316262623837383730653066333931373934383531336264636532336136333962613836346334
66303062393633396363613233333638326632306265643838613066303933663339613937353261
38323162313632666163393535373130663963323864653262313834323034623839313934303462
63393732306237333237333835393238326134396164376136303064613334656464636239303031
65343830633038653730623162306639346365313935333030626430333034623839336463396165
66633762316336616133356461646562656662313634323732343665366136333361666263633034
30393662613833336135623362636437646336363935323837386263396634306630306230656637
38366365623831636562346238663736653539306662323930373162343539623864383439626136
33646333633430386330626638326265323735343662303964613134633964626263333839656630
30633734646438363934386461626133623733613766336261633236313764366565313332326361
38373239333236363530386565343935633133363635663431316265613463633137306263623764
66373132376631663465613266383834396564376136386135653766356530656161383263623763
33393062663532326435643663333562633134316636626236313466366331666662346131663330
32306466383133623134363438323335316431326137303635313065393163626232643465376564
3435

To decrypt an encrypted playbook:

root@ip-172-31-23-165:~/ansible# ansible-vault decrypt playbook.yml
Vault password:
Decryption successful

Roles:
  • We can use two techniques for reusing a set of tasks: includes and role.
  • Roles are good for organizing tasks and encapsulating data needed to accomplish those tasks.
  • We can organize playbook into a directory structure called roles.
  • Adding more and more functionality to the playbooks will make it difficult to maintain in a single file.
Ansible Roles:
  • Default: it stores the data about role/ application. Default variables e.g: if you want to run
  • to port 80 or 8080 then variables need to define in this path.
  • Files: it contains files need to be transferred to the remote VM (static files).
  • Handles: they are triggers or task. We can segregate all the handlers required in playbook.
  • Meta: this directory contains files that establish roles dependencies. E.g: author name,
  • supported platform, dependencies if any.
  • Tasks: it contains all the tasks that is normally in the playbook. E.g: installing packages and copies files etc.
  • Vars: variables for the role can be specified in this directory used in your configuration
  • files. Both vars and default stores variables.

Make directory like below structure 
├── playbook
│   └── roles
│       └── webservers
│           └── tasks


root@ip-172-31-23-165:~/ansible/playbook# tree
.
├── master.yml (master file configurations it holds)
└── roles
    └── webservers
        └── tasks
            └── main.yml  ( holds tasks)




root@ip-172-31-23-165:~/ansible/playbook# ll
total 28
drwxr-xr-x 3 root root  4096 Nov 18 08:10 ./
drwxr-xr-x 3 root root  4096 Nov 18 08:03 ../
-rw------- 1 root root 12288 Nov 18 08:08 .master.yml.swp
-rw-r--r-- 1 root root    95 Nov 18 08:10 master.yml
drwxr-xr-x 3 root root  4096 Nov 18 08:03 roles/

root@ip-172-31-23-165:~/ansible/playbook# cat master.yml
---
- hosts: all
  become: yes
  gather_facts: yes
  connection: ssh
  roles:
    - webservers

# it holds master permission to execute the task binded to roles

root@ip-172-31-23-165:~/ansible/playbook# tree
.
├── master.yml
└── roles
    └── webservers
        └── tasks
            └── main.yml

3 directories, 2 files

root@ip-172-31-23-165:~/ansible/playbook# cat roles/webservers/tasks/main.yml
- name: install apache2
  apt: name=nginx state=present
- name: start apache2
  service: name=nginx state=started

# it holds tasks which need to execute 


Execute the above playbook will get same like response 

root@ip-172-31-23-165:~/ansible/playbook# ansible-playbook master.yml

PLAY [all] *********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************************************
ok: [localhost]

TASK [webservers : install apache2] ********************************************************************************************************************
ok: [localhost]

TASK [webservers : start apache2] **********************************************************************************************************************
ok: [localhost]

PLAY RECAP *********************************************************************************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

root@ip-172-31-23-165:~/ansible/playbook#



***


Comments

Popular posts from this blog

Remote Friendly Companies

Docker Image Vulnerabilities and Scanner Guide: A Quick Overview

Introduction to Istio, Kiali, Jaeger, Grafana, and Prometheus