Marius Melzer
Marius Melzer

Reputation: 1064

Ansible: Configure global variable which "environments" to set up

I want to be able to setup via ansible different "environments" (sets of same variables), e.g. production, testing, staging, etc.

I would like to:

  1. define which environments to set up (setup_environments) at some global place
  2. run a role r1 once for each environment in setup_environments
  3. run a role r2 without setting its environment, but r2 should have access both to the variable setup_environments AND be able to load the defined environments for certain tasks.

Is this possible? 3. should be possible with include_vars, but I mention it to show that I really need the "setup_environments" variable and can't simply run ansible multiple times including each environment separately with -i.

Upvotes: 0

Views: 530

Answers (1)

U880D
U880D

Reputation: 11999

Reading your requirement it seems that you need to structure your inventory only. Let's assume your inventory looks like

inventory.ini

[environment:children]
prod
qa
dev

webserver
database

[environment:vars]
# No global variables here / yet

[prod:children]
webserver_prod
database_prod

[qa:children]
webserver_qa
database_qa

[dev:children]
webserver_dev
database_dev

# Logical services nodes

[webserver:children]
webserver_prod
webserver_qa
webserver_dev

[database:children]
database_prod
database_qa
database_dev

# List of all hosts

# [prod:children]

[webserver_prod]
web.prod.example.com

[database_prod]
primary.prod.example.com
secondary.prod.example.com

# [qa:children]

[webserver_qa]
web.qa.example.com

[database_qa]
primary.qa.example.com
secondary.qa.example.com

# [dev:children]

[webserver_dev]
web.dev.example.com

[database_dev]
primary.dev.example.com
secondary.dev.example.com

you may get familar with the structure than by

ansible-inventory dev --graph
ansible-inventory database_dev --graph
...

It will be possible to apply playbooks, tasks, etc. just to certain nodes via

ansible-playbook database_dev ...

Furthermore you should introduce group_vars like

all
prod
qa
dev
webserver_prod
database_prod
...

All depdends on the structure of the inventory but makes it easier afterwards.

Upvotes: 1

Related Questions