So I'm running into quite some weird behaviour here, while I'm not sure if I approach this in a wrong way or there is a not-so-minor gap in the azure_rm
plugin for Ansible.
I want to build a dynamic inventory and only include certain VMs, not all of the VMs in my Azure account. Hence, I filter based on certain tags, but the plugin only provides an exclude_host_filters
options, so I have to filter out all VMs that do not fit the desired tag, which already seems strange to me:
plugin: azure_rm
include_vm_resource_groups:
- my-rg
auth_source: auto
keyed_groups:
- key: tags.Function
exclude_host_filters:
- tags.Environment != 'DEV'
When trying to create the inventory and my Azure account does have a VM without any tags, I'm actually getting following error and an empty inventory:
[WARNING]: * Failed to parse /home/azureuser/.../.../ansible/etc/azure_rm.yml with auto plugin: Error evaluating filter condition
'tags.Environment != 'DEV'' for host myinstance_4dcc: 'dict object' has no attribute 'Environment'
which is technically correct, the instance does in fact not have this tag. However, I don't understand why there's only the option to provide an exclude-filter. The aws_ec2
plugin approaches it the other way round, which makes way more sense to me: it's an include-filter, so all EC2 instances that fit the criteria explicitly are taken into the inventory, the rest is ignored.
This plugin however will lead to my Ansible runs failing whenever somebody creates any unrelated VM in my account and forgets the tags, I feel this cannot be right? Anyone faced this issue already or has an way to address this?
As pointed in the section describing the exclude_host_filters
parameter, this parameter does accept Jinja experssions:
Excludes hosts from the inventory with a list of Jinja2 conditional expressions. Each expression in the list is evaluated for each host; when the expression is true, the host is excluded from the inventory.
Source: https://docs.ansible.com/ansible/latest/collections/azure/azcollection/azure_rm_inventory.html#parameter-exclude_host_filters, emphasis, mine.
So, you can add whatever Jinja expression and filters you see fit.
In your case, using the default
filter would do the trick:
exclude_host_filters:
- tags.Environment | default('') != 'DEV'