Filtering multiple tags in Ansible dynamic assets

I think I saw the answer to this somewhere, but now I can not find it. I am creating a dynamic development inventory file for my EC2 instances. I would like to group all instances with Stack=Development tags. Moreover, I would like to specifically define the development API servers. They will have not only the Stack=Development tag, but also the API=Yes tag.

My main setup uses inventory folders:

 <root>/development β”œβ”€β”€ base β”œβ”€β”€ ec2.ini └── ec2.py 

In my base file, I would like to have something like this:

 [servers] tag_Stack_Development [apiservers] tag_Stack_Development && tag_API_Yes 

Then I could run this to ping all my development api servers:

 ansible -i development -u myuser apiservers -m ping 

Is there anything you can do? I know the syntax is wrong, but hopefully the intention is clear enough? I can’t imagine that I’m the only one who ever needed to filter by several tags, but I couldn’t find anything that takes me to where I am trying to go.

+8
ansible
source share
3 answers

This is not the answer that I had in my head, but sometimes what is in my head interferes. Since each inventory directory has its own ec2.ini , I simply filter the stack and then group together inside this filter.

 # <root>/development/ec2.ini ... instance_filters = tag:Stack=Development # <root>/development/base [tag_Role_webserver] [tag_API_Yes] [webservers:children] tag_Role_webserver [apiservers:children] tag_API_Yes 
+5
source share

See the Ansible documentation for the templates section . Instead of creating a new section, you can perform tag intersection when specifying hosts:

 [$] ansible -i development -u myuser tag_Stack_Development:&tag_API_Yes 

It also works in books.

+2
source share

The answer provided by xiong-chiamiov really works. I just used it in my indispensable deployment.

So, I have a tutorial with a dynamic inventory script. with this piece of code:

  --- - name: AWS Deploy hosts: tag_Environment_dev:&tag_Project_integration gather_facts: true 

And the process filters the hosts with both tags.

EDIT

In fact expanding this, you can also use variables to make a dynamic dynamic group. eg:

  --- - name: AWS Deploy hosts: "tag_Environment_{{env}}:&tag_Project_{{tag_project}}" sudo: true gather_facts: true 

I use {{env}} and {{tag_project}} vars from the variable files and arguments that are given at runtime. It successfully modifies the hosts that the player works with.

+1
source share

All Articles