In this blog , we will see how we can manage Ansible Playbook for multiple environments.
Problem Statement:
- How we can write the role in ansible which has to refer different values for each environment (dev,pvs,production) ? Example — database details
Solution:
- To resolve this issue,we will be using different files for each environment and pass that as a variable while running the ansible playbook.
How to do:
- Install Ansible if not already installed
- Use Ansible Roles
Create the directory structure as shown below:
- configs — This folder will have separate file for each environment which stores all the environment specific values.
- group_vars — This will have one file which is used to store all the variables which are common across environments.
- inventories — This folder will have host file for each environment
- roles — Task which you will have for your application like install java
- ansible.cfg — You can use this file if you have to override any default configuration. Example:
host_key_checking = False ( You will not see this error "The authenticity of host “hostname” can’t be established." if you specify this variable.
Now in your main.yml file call the roles as mentioned below:
gather_facts: True (This will check the connectivity between master and other nodes)
---
- hosts: all
gather_facts: True ( This will check the connectivity between master and other nodes)
become: true
vars:
java_version: "{{ java_version}}"
roles:
- role: install-java
Run ansible playbook as shown below :
ansible-playbook main.yml -i inventories/dev/hosts -k -K -e '@configs/dev.yml' -e 'java_version=1.8'
Finally congratulations!! You have successfully followed each and every step for Managing Ansible Playbook for multiple environments.