boaz barkan
boaz barkan

Reputation: 147

ansible playbook hosts, is there a way to filter by variable

I'm new to ansible so bear with me, if my question is a bit basic.

I have 10 WordPress sites with different themes, all of them are listed in the hosts file under 'production' group:

[production]

black.com

red.com

blue.com

Each site require different variables:

theme_name: black

Is there anyway that I can run a playbook on 'production' host group , using variable?

Upvotes: 1

Views: 4535

Answers (2)

cachonfinga
cachonfinga

Reputation: 890

Not sure your question is absolutely clear, but another possible answer to your questions might be:

You can assign variables directly to hosts or groups in the inventory, there is a good introduction as to how you can do this here.

Example lifted from the page, variables defined after the host entry:

[atlanta]
host1 http_port=80 maxRequestsPerChild=808
host2 http_port=303 maxRequestsPerChild=909

This should work fine for small amounts of hosts, although there are better approaches when working at scale.

hth.

Upvotes: 0

udondan
udondan

Reputation: 60059

You can not easily* filter by variables. But you could add your hosts to additional groups like so:

[production]
black.com
red.com
blue.com

[black]
black.com

[red]
red.com

[blue]
blue.com

Now for the theme name you an create group-vars files. For example, for the red group you create the file group_vars/red with the content:

theme_name: red

Now you can run your playbook with the black, red and blue groups.

* I guess there is a way, by running filters on the hostvars dict and reduce it to a list of hostnames matching your criteria. But this seems to be overhead and against best practice. If you want to target a specific set of hosts you should have a group for them in the inventory.

Upvotes: 3

Related Questions