Using variables in hosts declaration inside playbooks

When you declare in which hosts do you want to run a playbook you usually do it like this:

- hosts: databases

But let’s say that you want to be more flexible and you want to have some variable inside your hosts declaration. How can you do that? One possible solution is using extra vars.

If we decide to call our variable ‘env’ we should define our hosts inside the playbook like:

- hosts: "{{ env }}_master"

And then run the playbook as follows:

ansible-playbook -i inventory/databases binlogs.yml --extra-vars "env=database01"

Obviously inside your inventory file, these hosts must exist:

database01_master ansible_host=db01
database02_master ansible_host=db03
database03_master ansible_host=db05



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s