In this blog, we will discuss the group_vars variable in the Ansible playbook.
Problem Statement
Let's say I have a group of servers i.e. Server1 Server2 and Server3 which belong to the Dev environment on the other hand, we have Server4 Server5 and Server6 that belong to the Prod environment. Now Say I want to deploy my changes on dev environment servers only to test in this case we will use group_vars.
**************Important*********** :- Always remember that host_vars has more priority than the group_vars
Pre-Requisite:- Open AWS EC2 servers and do the initial setup. {Refer Part-1 for setup}
Firstly, make the entry in /etc/hosts of the Ansible Controller
Now, check the ansiblehosts file to understand the groups
Now, to use the group_vars we need to make a separate directory with the name group_vars inside where our all host files are already placed
Now, Inside the group_vars directory, we make the YAML as per the groups e.g. I have 2 groups dev and prod so I'll make dev.yaml and prod.yaml
--- subjects: "configuration managemenet on Dev"
Let's say the above file is dev.yaml
--- subjects: "Ansible on Prod"
Let's say the above file is prod.yaml
Now, where the host files are kept we'll make our main playbook there
--- - name: woring with Variables hosts: all tasks: - name: Printing the values of group_vars command: echo "The value of my Subjects are {{ subjects }}"
Now, let's run the playbook and see the results
Hence, we saw that how we can use group_vars
If you like my blogs, kindly like this blog and share it with your friends it'll give me motivation to post more content. You can find the code from below git hub repo