Shashikant shah

Wednesday, 21 October 2020

Ansible conditional statement part-8

when => redhat os found then install httpd service.
when: ansible_os_family == "RedHat"
##############################
AND with when => Redhat and version match then install httpd
when: ansible_os_family == "RedHat" and ansible_distribution_version == "7.2"
##############################
OR with when => Redhat or ubuntu any one match then install httpd
when: ansible_os_family == "RedHat" or ansible_os_family == "ubuntu"
##############################
Conditionals in Loops
tasks:
      - name: install all the package
        yum:
         name: "{{ item }}"
         state: present
        with_items:
         - httpd
         - php
         - vsftpd
##########################
Error Handling :- ignore_errors option for if getting error single task then skip error task and run other task.
Rescue :- Rescue option use for if first task result is failed  then rescue task will be run. if first task successfully run then rescue task will do not run. 
Tag :- defind tags name in task.
register :-  run a command on a remote computer and then store the output in a variable and use a piece of information.
always :- first task is failed Or pass but  always task will be run..

1.Using When Operator

Redhat OS found then install httpd service.

---
- hosts: jenkins
  #remote_user: root
  become: true
  gather_facts: true
  tasks:
      - name: print OS family.
        debug:
          msg: "{{ ansible_os_family }}"
 
      - name: httpd install only redhat.
        yum:
          name: httpd
          state: latest
        when: ansible_os_family == "RedHat"

 











2.Using AND Operator with When

Redhat and version match then install httpd.

---
- hosts: jenkins
  #remote_user: root
  become: true
  gather_facts: true
  tasks:
      - name: print OS family.
        debug:
          msg: "{{ ansible_os_family , ansible_distribution_version }}"
        tags: print
 
      - name: httpd install only redhat.
        yum:
          name: httpd
          state: latest
        when: ansible_os_family == "RedHat" and ansible_distribution_version == "NA"











3.Using OR Operator with When
Example i) Redhat or ubuntu any one match then install httpd
---
- hosts: jenkins
  #remote_user: root
  become: true
  gather_facts: true
  tasks:
      - name: print OS family.
        debug:
          msg: "{{ ansible_os_family }}"
        tags: print
 
      - name: httpd install redhat or ubuntu.
        yum:
          name: httpd
          state: latest
        when: ansible_os_family == "RedHat" or ansible_os_family == "ubuntu"


Example ii)  OS redhat and ubuntu match then run disk space df -h command.
---
- hosts: jenkins
  #remote_user: root
  become: true
  gather_facts: true
  tasks:
      - name: print OS family.
        debug:
          msg: "{{ ansible_os_family }}"
        tags: print
 
      - name: check disk space usage on servers .
        shell: df -Th
        register: result
 
      - name: check OS on server then run disk space
        debug:
          var: result.stdout_lines
        when: ansible_os_family == "RedHat" or ansible_os_family == "ubuntu"


4.Conditionals in loops
Example 1 :-
---
- hosts: jenkins
  #remote_user: root
  become: true
  gather_facts: true
  tasks:
      - name: install all the package
        yum:
         name: "{{ item }}"
         state: present
        with_items:
         - httpd
         - php
         - vsftpd








Example 2 :-
Conditionals in Ansible Loops. True required will be install package , false required is disabled.
---
- hosts: jenkins
  #remote_user: root
  become: true
  gather_facts: true
  vars:
   packages:
   - name: httpd
     required: True
   - name: tree
     required: True
   - name: vsftpd
     required: False
 
  tasks:
      - name: install "{{ item.name }}" the package
        yum:
         name: "{{ item.name }}"
         state: present
        when: item.required == True
        loop: "{{ packages }}"   
  


5.Configure Error Handling
 
Example.1 :- ignore_errors option for if getting error single task then skip error task and run other task.
---
-        name: webserver
hosts:   webserver1, sqlserver
tasks:
-        name: ‘first task’
command: touch /tmp/jk.txt
ignore_errors: True
 
Example.2 :- Create a block for ignore error in group tasks.(if error any task then skip task and next task executed).
---
- hosts: jenkins
  become: true
  gather_facts: true
  tasks:
-        block:
-  command: “ls /tmp”
   register: result_1
-  command: “ls /jk”
   register: result_2
-  command: “ls /root”
    register: result_3
ignore_errors: yes/True
 
- debug: var= result_1
- debug: var= result_2
- debug: var= result_3
 
Example 3 :- Give to root privileges in group task.
      - task
- block:
   name: task1
    name: task2
    name: task3
become: yes
 
Example 4 :- rescue option use for if first task result is failed  then other task will be run.
---
- hosts: jenkins
  #remote_user: root
  become: true
  gather_facts: true
  tasks:
    - block:
      - name: finding files in /home/jk/shashi
        command: "ls /home/jk/shashi"
      rescue:
        - debug:
            msg: "the given path:/home/jk/shashi is not vailed..!"













Example 5: Task failed and success but always option execute always.

---

- hosts: jenkins

  #remote_user: root

  become: true

  gather_facts: true

  tasks:

    - block:

      - name: finding files in /home/jk/shashi

        command: "ls /home/jk/shashi"

      rescue:

        - debug:

            msg: "the given path:/home/jk/shashi is not vailed..!"

       always:

         - debug:

            msg: "this will always execute."


6.tag use in ansible-playbook .
---
 - name: Install httpd
   tags: Install and start
   hosts: all
   tasks:
    yum:
name: httpd
     state: Installed
   tags: Install
    - service:
name: httpd
state: started
 
# ansible-playbook playbook.yml -tags "Install"
# ansible-playbook playbook.yml --skip-tags "Install"
 
7.How to check if a file exists in Ansible?
---
- hosts: jenkins
  #remote_user: root
  become: true
  gather_facts: false
  tasks:
      - name: Check that the somefile.conf exists
        stat:
          path: /etc/file.txt
        register: stat_result
 
      - name: Create the file, if it doesnt exist already
        file:
          path: /etc/file.txt
          state: touch
        when: not stat_result.stat.exists 
                        OR
        when: stat_result.stat.exists == false 
 
8.How to include tasks from a file.
---
# ./roles/my_role/tasks/install.yml
 
- name: install dependencies
  apt:
    name: "{{ item }}"
    state: present
  become: true
  loop:
    - nginx
    - php7.2
 
---
# ./roles/my_role/tasks/configure.yml
 
- name: configure the application
  copy:
    src: my_app.conf
    dest: /etc/my_app.conf
  become: true
 
---
# ./roles/my_role/tasks/main.yml
 
- include_tasks: install.yml
 
- include_tasks: configure.yml
 
8.first check httpd version, if not install package then install httpd package and print httpd version.
 
---
- hosts: jenkins
  #remote_user: root
  become: true
  gather_facts: false
  tasks:
      - name: verify httpd version
        command: /usr/sbin/httpd -v
        register: version
        ignore_errors: true
 
      - name: print httpd version
        debug:
         msg: "{{ version }}"
        when: "version.rc == 0"
 
      - name: install httpd
        yum:
          name: "httpd"
          state: present
        when: "version.rc != 0 "
 
9.The playbook should install the package only if the package is not installed. If the pkg is already installed then "do nothing" .
 
# vim httpd.yml
---
 - name: Installing HTTPD
   hosts: jenkins
   become: true
   gather_facts: false
   vars:
     pkg: httpd
   tasks:
     - name: check httpd package
       shell: rpm -q httpd | head -n 1
       register: result
     - name: variable store Data type chapter
       set_fact:
        result: "{{ result.stdout }}"
     - name: package version showing
       debug:
        msg: "Is the {{ pkg }} installed: {{ result }}"
     - name: package install command
       yum:
        name: "{{ pkg }}"
        state: latest
       when: result | regex_search("not installed")
















10. In the above example we did fail the playbook based on a condition match but there was no output on the console so operator may get confuse if the playbook has a BUG or the failure was intentional. So we can use fail module instead of failed_when to be able to print a message on the console:

---

 - name: Installing HTTPD

   hosts: jenkins

   become: true

   gather_facts: false

   vars:

     pkg: httpd

   tasks:

     - shell: rpm -q httpd | head -n 1

       args:

         warn: false

       register: result

       changed_when: false

     - fail:

         msg: "Failed because {{ pkg }} is already installed"

       when: "'not installed' not in result.stdout"

     - debug:

        msg: do we get here

     - yum:

        name: "{{ pkg }}"

        state: present












11.What is Ansible strategies.

Strategies are a way to control play execution for all server

1. Liner :- default use Liner strategy. First task will be complete to all server after that second task execute for all server.

2. Serial :- This strategy any number set serial=2, parallel all task execute 2 server.

3. Free :- This strategy set strategy: free parallel all task to all server.

---

- hosts: jenkins

  become: true

  gather_facts: true

  serial: 2 

tasks:

name: “first task”

           yum: name=’httpd’  state=’present’

name: “second task”

command: touch /tmp/test.txt

     -     name: “third task”

          command: sleep 30

12.Asynchronous Actions and Polling :-

By default Ansible runs tasks synchronously, holding the connection to the remote node open until the action is completed. For example, a task may take longer to complete than the SSH session allows for, causing a timeout. Or you may want a long-running process to execute in the background while you perform other tasks concurrently. Asynchronous mode lets you control how long-running tasks execute.

async: 60  :- total 60 second execute time of task

poll: 15 :- task check every 15 second .

example 1:-

---

- hosts: target

  tasks:

    - shell: sleep 120

      async: 60 

      poll: 15

Example 2:-

---

- hosts: target

  tasks:

    - shell: sleep 120

      async: 60

      poll: 0


 Ansible Register

For any task output, which we register in a variable, it is stored in a pre-defined format in JSON. For different tasks we will get different output and it is stored in the way it is defined in ansible documentation. When we see the output we will see the values as per ansible documentation and some fields which will be shown in each output like changed.

For another reference for a playbook with content like below:

1. hosts: host-one tasks: name: check HTTP status command: service httpd status register: output_var
2. name: display the output of the above execution debug: var: output_var

you will see most of the fields in output, we try to explore some of those.

























Ansible run_once :-

Ansible run_once parameter is used with a task, which you want to run once on first host. When used, this forces the Ansible controller to attempt execution on first host in the current hosts batch, then the result can be applied to the other remaining hosts in current batch.

Example.1 :-
In this example, we have created a playbook with contents like below, here we are trying to download a tarball file from internet to Ansible control node. As this download is needed only once, so we will use run_once in this task. Also as this is to be done on local machine only, we need to mention delegate_to and pass localhost to it.

Then we will unarchive this tarball to remote machines, which will be done separately on both the hosts:

---
- hosts: all
gather_facts:
no tasks:
- name: Here we download a file from internet to controller node only once using run_once
get_url:
url: http://download.videolan.org/pub/videolan/vlma/0.2.0/vlma-0.2.0-bin.tar.gz
dest: /tmp/
run_once: true
delegate_to:
localhost
- name: Here we unarchive the downloaded file on remote machines.
unarchive:
src: /tmp/vlma-0.2.0-bin.tar.gz
dest: /tmp/


Example.2 :-

---
-hosts: all
gather_facts:
no tasks:
-name: here we are fetching facts about IPv4 from all setup:
filter:
ansible_default_ipv4
register: remote_ipv4
run_once: true
-debug:
var: remote_ipv4


No comments:

Post a Comment