AlamHo
AlamHo

Reputation: 193

Ansible Conditional Variable

Before i start, let me give a bit detail on my ansible directory structure

so right now, if i want to deploy one apps to staging, i can just simply run this playbook command:

ansible-playbook -i environments/staging/hosts deploy-app.yml

for example, i defined the path for my app1 directory in staging/group_vars/webserver to "/var/www/staging.app1.com". but i also need to deploy to the same server for app2 but with different directory. Is it possible to use conditional variable in group_vars?

So if i run:

 ansible-playbook -i environments/staging/hosts deploy-app.yml --extra-vars "app_name=app1"

it will deploy to staging server on /var/www/staging.app1.com and:

 ansible-playbook -i environments/staging/hosts deploy-app.yml --extra-vars "app_name=app2"

it will deploy to staging server on /var/www/staging.app2.com

i know that the easiest way could just define app_dir variable when running playbook, but if possible, i prefer to define the app_name then app_dir will be used based on the specified app_name.

if app_name =  app1, then app_dir = /var/www/staging.app1.com

elif app_name = app2, then app_dir = /var/www/staging.app2.com

Please advise kindly

Upvotes: 1

Views: 1470

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68229

You can template app_dir in your group vars:

app_dir: '/var/www/staging.{{ app_name }}.com'

If you have more app-dependent variables and they are not templatable, you can use apps dict in your variable files:

apps:
  app1:
    dir: '/var/www/app1'
    key: 'klg23sdkjfsdf'
    db_host: '127.0.0.1'
  app2:
    dir: '/opt/apps/app2'
    key: 'askjh233423444'
    db_host: '127.0.1.1'

and use apps[app_name].dir when you need app_dir and so on.

Upvotes: 1

Related Questions