I am trying to write a very flexible playbook that targets nodes based on the environment in which they are located. I use as many variables as possible, so the playbook can be reused for other projects / environments with minimal changes.
I have one application.yml
- name: Prepare app-server for "The app"
hosts: "{{'env'}}_super_app"
vars:
vars_files:
- "environments/{{env}}.yml"
sudo: yes
tasks:
- command: echo {{env}}
roles:
- common
- nginx
- php5-fpm
- nodejs
- newrelic
- users
- composer
- name: Install and configure mysql for "The super app"
hosts:
- "{{env}}_super_db"
vars:
vars_files:
- "environments/{{env}}.yml"
sudo: yes
roles:
- common
- mysql
- newrelic
Here is the directory structure for playback:
βββ environments
β βββ prod.yml << environment specific vars
β βββ stag.yml << environment specific vars
β βββ uat.yml << environment specific vars
βββ roles
β βββ common
β βββ composer
β βββ mysql
β βββ newrelic
β βββ nginx
β βββ nodejs
β βββ php5-fpm
β βββ users
βββ users
β βββ testo.yml
βββ prod << inventory file for production
βββ README.md
βββ application.yml << application playbook
βββ stag << inventory file for staging
βββ uat << inventory file for uat
Here is the contents of the uat inventory file:
[uat_super_app]
10.10.10.4
[uat_super_db]
10.10.10.5
When I run my book, I pass the environment as an additional variable:
ansible-playbook -K -i uat application.yml -e="env=uat" --check
Idea: If {{env}} is installed in uat, then /uat.yml environments will be used, and the hosts [uat_super_app] will target {{env}} _ super_app.
If I or someone makes a mistake and tries to run uat vars against production inventory, the hosts will not match and it will be impossible to start the playbook.
ansible-playbook -K -i prod application.yml -e="env=uat" --check
, .
, :
ansible-playbook -K -i uat application.yml -e="env=uat" --check -vvvv
SUDO password:
PLAY [Prepare app-server for "The app"] *******************************
skipping: no hosts matched
PLAY [Install and configure mysql for "The app"] **********************
skipping: no hosts matched
PLAY RECAP ********************************************************************