Ansible Handlers, variable, Loops & Dry Run

 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






Share:

0 comments

Please leave your comments...... Thanks