Deep dive with Ansible variables

Variables in any programming language plays a very important role for customizing and optimizing the code which also improve readability .

Ansible support  variables that can store values which and be reused in files or we can say variables can provide a more convenient way to store dynamic values .

Most useful cases:


  1.  storing  users name
  2.  storing packages name
  3.  used in loops and conditional statement 

Sample playbook example :

i)    using with copy module 

root@xpert:/etc/ansible/playbooks# cat  vars.yml 
---
 - hosts: localhost
   remote_user: xpert
   vars:
    x: "hello Google "
   tasks:
    - name: testing hello vars 
      copy: content="{{ x }}" dest=/etc/motd


ii)   creating user

root@xpert:/etc/ansible/playbooks# cat  user.yml 
---
 - hosts: localhost
   remote_user: xpert
   vars:
    x: "dream"
   tasks:
    - name: testing hello vars 
      user: 
         name="{{ x }}" 
         state=present 
         shell=/bin/bash 
         password="$1$9y7.D67S$1YUykTsDFaZjyQUg8wjvo0"


Important :   Overriding  variables 


root@xpert:/etc/ansible/playbooks# ansible-playbook  user.yml  -e "x=adhoc"

PLAY ***************************************************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [testing hello vars] ******************************************************
changed: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0   



IMportant :  Defining  variables in Inventory  with group variables

[root@station147 user]# cat   /etc/ansible/hosts

[dc]
192.168.10.121
192.168.10.65
[dc:vars]
username=root1
password=$1$hJTfjIRI$N75O5l2yGXEVl86MduBoj0


Note:  we can use these variables in you playbooks

------------------------------

[root@station147 user]# cat   /etc/ansible/playbooks/uservarsfile.yml
---
 - hosts: all
   tasks:
    - name: adding user with passowrd
      user: name="{{ username }}" password="{{ password }}"  shell=/bin/bash state=present



Note:   Nested group variables

 [root@station147 user]# cat   /etc/ansible/hosts
[ub]
192.168.10.121

[red]
192.168.10.65

[nested:children]
red
ub
[nested:vars]
username=nupppp
password=$1$hJTfjIRI$N75O5l2yGXEVl86MduBoj0


Important :

Final use case :

i)  Inventory file

[root@station147 user]# cat /etc/ansible/hostgroupvars

[ub]
192.168.10.121

[red]
192.168.10.65

[nested:children]
red
ub








ii)    playbook

[root@station147 user]# cd /etc/ansible/playbooks/user/

[root@station147 user]# cat uservarsfile.yml
---
 - hosts: all
   tasks:
    - name: adding user with passowrd
      user: name="{{ username }}" password="{{ password }}"  shell=/bin/bash state=present


iii)  group and host variables

[root@station147 user]# cat  group_vars/nested  
username: ashutoshhh2
password: redhat3

[root@station147 user]# cat host_vars/192.168.10.65
username: hacked
password: google


Important :   This type of work flow generally work with Cisco and other networking devices

Define  category :

These variables can be define into 3 category 

  1.  Global scope
  2.  Play scope 
  3.   Host scope 


Register variables :

To store the output of running module and play then debug to dump it back on the screen
[root@localhost apache]# cat  web.yml
---
 - hosts: all
   vars:
    - x: httpd
   tasks:
    - name: Installing web server
      yum: name="{{ x }}" state=present
      register: outputvar
     
    - debug: var=outputvar



#  Magic variable :-

as we know to use variables either we need to define or need to extract from facts .

but there are some variables that can be used without defining although they are not even facts 


4  magic  variables:


i)  hostvars
Contains the variables for managed hosts, and can be used to get the values for another
managed host's variables. It won't include the managed host's facts if they haven't been
gathered yet for that host. 


Example: 

-bash-4.3$ ansible all  -m debug -a "var=hostvars"

192.168.10.55 | SUCCESS => {
    "hostvars": {
        "192.168.0.10": {
            "ansible_check_mode": false,
            "ansible_playbook_python": "/usr/bin/python2",
            "ansible_version": {
                "full": "2.4.1.0",
                "major": 2,
                "minor": 4,
 




ii)  group_namesLists all groups the current managed host is in. 



Example:

-bash-4.3$ ansible all  -m debug -a "var=group_names"
192.168.10.55 | SUCCESS => {
    "group_names": [
        "a",
        "c"
    ]
}
192.168.0.10 | SUCCESS => {
    "group_names": [
        "b",
        "c"
    ]
}



iii)  groups
Lists all groups and hosts in the inventory.


Example:

-bash-4.3$ ansible all  -u code -b -m debug -a "var=groups"
192.168.10.55 | SUCCESS => {
    "groups": {
        "a": [
            "192.168.10.55"
        ],
        "all": [
            "192.168.10.55",
            "192.168.0.10"
        ],
        "b": [
            "192.168.0.10"
        ],
        "c": [
            "192.168.10.55",
            "192.168.0.10"
        ],
        "ungrouped": []
    }
}



iv)    inventory_hostname

Contains the hostname for the current managed host as configured in the inventory. This
may be different from the hostname reported by facts for various reasons.
There are a number of other "magic variables" as well. For more information, see http://
docs.ansible.com/ansible/playbooks_variables.html. One way to get insight into their values is to
use the debug module to report on the contents of the hostvars variable for a particular host:




Using include option :


##  main playbook

-bash-4.3$ cat  playbook.yml
---
 - hosts: localhost
   become: true
   tasks:
    - name: including variables
      include_vars: vars/var.yml

    - name: task include
      include: tasks/env.yml

##  now  var.yml

-bash-4.3$ cat  vars/var.yml ---
firewall_pkg: firewalld
package: httpd
service: httpd
svc_state: started
 



## now   env.yml


-bash-4.3$ cat tasks/env.yml
---
  - name: installing  the {{ package }} package
    dnf:
     name: "{{ package }}"
     state: installed

  - name: starting the {{ service}}   service
    service:
     name: "{{ service }}"
     state: "{{ svc_state }}"





Comments

  1. This is really wonderful information, it really helpful for learners. Hope share more content on Devops Online Training Hyderabad

    ReplyDelete
  2. Thanks for sharing the descriptive information on Hadoop course. It’s really helpful to me since I'm taking Hadoop training. Keep doing the good work and if you are interested to know more on Hadoop, do check this Hadoop tutorial.https://www.youtube.com/watch?v=cY5AnQMdXhY

    ReplyDelete
  3. DevOps training in Chennai will prepare you for a career in DevOps, the fast-growing field that bridges the gap between software developers and operations.

    You’ll become an expert in the principles of continuous development and deployment, automation of configuration management, inter-team collaboration and IT service agility, using modern DevOps tools such as Git, Docker, Jenkins, Puppet, and Nagios. DevOps jobs are highly paid and in great demand, so start on your path today.

    DevOps training in chennai with placement | Best DevOps training in chennai | Best DevOps training Institute in chennai

    ReplyDelete
  4. Great and really helpful article! Adding to the conversation, providing more information, or expressing a new point of view...Nice information and updates. Really i like it and everyday am visiting your site..devops training



    ReplyDelete
  5. Thanks for your post, this is very nice, keep sharing!
    DevOps Online Training

    ReplyDelete
  6. This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.
    DevOps Training in chennai

    DevOps Training in Bangalore

    ReplyDelete
  7. All the points you described so beautiful. Every time i read your i blog and i am so surprised that how you can write so well.

    Tableau Training in Bangalore

    Tableau Training in Chennai

    ReplyDelete
  8. Hey thanks for this amazing post! Thank you so much for sharing the good post, I appreciate your hard work.Keep blogging.
    DevOps Training in Electronic City

    ReplyDelete
  9. Hi, I have just started to learn devops online training. This blog quite technical as I just started to learn, but I think this would be useful for my next class. Thank you for this informative blog!

    ReplyDelete
  10. Thanks for sharing such a great post. It is very useful and informative. Valuable information you have shared. Also, check out
    Devops Services

    ReplyDelete

Post a Comment