Search code examples
ansibleansible-2.xansible-inventory

select group_var variable file in top level playbook


I have defined all my variables in group_vars/all/vars_file.yml and my playbook is as below:

---
# Top level play site.yml
- hosts: webclient

  roles:
    - common
    - nginx
    - nvm
    - deploy_web_client

- hosts: appserver
  roles:
    - common
    - gradle
    - tomcat
    - deploy_sb_war

Now I have 3 environments dev / staging / production. Depending upon the environment i used to change the vars_file.yml under group_vars and then run the ansible-play.

Is there any way I can keep 3 files like "group_vars/dev" , "group_vars/staging", "group_vars/production" and specify it in my main site.yml

I have 3 inventory files as below, and depending upon the environment during ansible-play i specify the inventory file name

[webclient]
10.20.30.40

[appserver]
10.20.30.41

Solution

  • Instead of using inventory files saved in a single directory, use inventory files in separate directories and put group_vars inside each of them.

    .
    ├── dev
    │   ├── group_vars
    │   │   └── all
    │   │       └── vars_file.yml
    │   └── inventory
    ├── production
    │   ├── group_vars
    │   │   └── all
    │   │       └── vars_file.yml
    │   └── inventory
    └── staging
        ├── group_vars
        │   └── all
        │       └── vars_file.yml
        └── inventory
    

    Then point to the directory in the ansible-playbook call:

    ansible-playbook -i dev <the_rest>