Ansible - Passing environment variables through files

Hi All,

I’ve have searched literally all the available medium on internet for this issue but could not find the solution. So decided to raise the problem in this group.

I’ve a project having number of environments such as dev1, dev2, dev3, sit1, sit2 and so on, with total of 20 environments. These environments also share some servers between them.
I’m using Ansible for application deployment.

Problem: Before starting the deployment, I need to set the environment variables by declaring the key:value pair under “environment” section. It is not a problem if I have couple of environments to deploy but problem arises when environment multiplies.
It is surely not feasible to create 20-30 main playbooks for each environment and declaring the environment variables to use for that deployment on playbook, as we need to source the .bashrc / .bash_profile for each environment.

In my current set-up, I’ve created server_groups with environment names like dev1, dev2 etc. And, assigned servers to that group on Ansible Tower.
To trigger the app deployment, I’m passing environment name(for eg. dev1 ) which is then assigned to variable “env_name” in site_main.yml and deployment is done based on the servers in dev1 group.
Environment variables for dev1 are declared under environment keyword in site_main.yml. But that becomes very clumsy if I have to manage n number of playbooks for n number of environments.

Is there any way where I can create n number of environment files under vars or group_vars directory having variables of that environment? And, I can dynamically call the environment file such as

environment: "{{ env_name }}.yml"

I have seen examples such as below but env_name is hardcoded below and NOT dynamic:


vars:
 dev1:
  variable1: "{{ value1 }}"
  variable2: "{{ value2 }}"

environment: "{{ dev1 }}"

Can someone please suggest me the solution or any other better approach?

Thanks,
Ashish

Not sure this is useful (you seem way ahead of me) but I pass e.g. “-e env=blah” to ansible-playbook.

In my playbook (or wherever) I have include_vars:, and I specify e.g. “path/to/{{env}}.yaml”.

As long as all the environment files have the same variables in them (with different values), it works fine.

To switch between groups of related environments I pass an additional variable and use something like “path/to{{group}}/{{env}}.yaml”

I also have groups of unrelated environments; to select between those I set an environment variable something like “{{ansible_env.MY_ENV}}/path/to/{{env}}.yaml”

Bad syntax above, but you know what I mean :slight_smile:

Not sure I see what you mean by having to source bash_rc…? Maybe I am confusing shell environment with “meta groupof variables”…

Regards, K.

Thanks Karl!!

I’ll give it a try.

Thanks,
Ashish