How to load variables Dynamically in Ansible
--
Well it's very easy to load variables by the use of when keywords, then why there is a need for the article as it is already in ansible docs.
Here we will use another approach to load the variables dynamically and in a customized way so that there is no need to use ‘when’ keyword the files will load automatically according to the os needs, here we use the ansible facts and also get to know the importance of tags.
Task
- Create a single role for configuring the webserver
- Must be able to configure more than one distributions
Here my instances are running on AWS which is of different distributions (RedHat and Ubuntu). Now here the main challenge is of the remote user which is different for the different os. So, how we can dynamically load the remote_user?
We can solve this challenge by the use of tags, with each host there is a lot of variables attached with it, and one of them is tags for ex. in both the os i have attached two tags (user, name)
Tags for RedHat distribution
name = webserveruser = ec2_user
Tags for Ubuntu distribution
name = webserveruser = ubuntu
Now in remote_user we can pass the variable (ec2_tag_user) to provide the dynamic value of the user.
Task File
Here is the task file for the webserver configuration
---
# tasks file for dynamic_var
- include_vars: "{{ansible_distribution}}.yml"- name: installing http webserver
package:
name: "{{ package_name }}"
state: present- name: starting service
service:
name: "{{service_name}}"
state: started- name: copying templates
template:
src: "{{ansible_distribution}}.html.j2"
dest: "/var/www/html/index.html"
notify: restart webserver
ansible_distribution is the part of ansible_facts which will tell us which distribution it belongs to, we can check the distribution by setup module
ansible all -m setup -a "filter=ansible_distibution"
You can see that there is no error while playing this add hoc cmd even though I haven't provided any remote_user in the configuration file, users were picked up automatically.
In the next we have to create the var files in the name of disributions
Var Files
RedHat.yml
package_name: httpd
service_name: httpd
Ubuntu.yml
package_name: apache2
service_name: apache2
Templates
RedHat.yml
Hello from {{ ansible_distribution}}
Ubuntu.yml
Hello from {{ ansible_distribution}}
Playbook
- hosts: tag_name_webserver
tasks:
- name: config webserver
include_role:
name: ../roles/dynamic_var
Remember the tag with name keyword which was the same for both the os, here I'm using the same tag to group the hosts (both RedHat and Ubuntu)
ansible-playbook test.yml
For any queries and suggestions plz comment below
Thank You!!!