Nishchal Dinesh
Nishchal Dinesh

Reputation: 163

Ansible dynamic Inventory filters for tags/labels

I am trying to run the dynamic inventory list using Ansible

ansible-inventory --list -i gcp.yaml
---
plugin: gcp_compute
projects:
  - <project name>
auth_kind: serviceaccount
service_account_file: /opt/ansible/inventory/peak-equator-SA.json
filters:
        - labels|list = "ansible"

Getting the below error

[WARNING]:  * Failed to parse /opt/ansible/inventory/gcp.yaml with auto plugin: [{'message': 'Invalid value for field \'filter\': \'labels|list = "ansible"\'. Invalid
list filter expression.', 'domain': 'global', 'reason': 'invalid'}]
[WARNING]:  * Failed to parse /opt/ansible/inventory/gcp.yaml with yaml plugin: Plugin configuration YAML file, not YAML inventory
[WARNING]:  * Failed to parse /opt/ansible/inventory/gcp.yaml with ini plugin: Invalid host pattern '---' supplied, '---' is normally a sign this is a YAML file.
[WARNING]: Unable to parse /opt/ansible/inventory/gcp.yaml as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available
{
    "_meta": {
        "hostvars": {}
    },
    "all": {
        "children": [
            "ungrouped"
        ]
    }
}

Upvotes: 1

Views: 2983

Answers (3)

Vadiraj k.s
Vadiraj k.s

Reputation: 59

may be try this:

filters:
  - labels.key=value AND labels.key=value AND labels.key=value AND labels.key=value

Upvotes: 0

jstaf
jstaf

Reputation: 26

After encountering this myself just now, the "filters" are not Ansible filters, but filters specific to the Google Cloud APIs: https://cloud.google.com/compute/docs/reference/rest/v1/instances/aggregatedList (Note: there's no in operator.)

I was able to use labels.ansible != "" as a workaround. Full dynamic inventory config for reference (GCP has the worst documentation for Ansible ever, so I know this will be useful to someone out there):

---
plugin: gcp_compute
projects: PROJECT_NAME_HERE

# auth using "gcloud auth application-default login"...
# you don't need a service account this way
auth_kind: application

keyed_groups:
  - key: labels
    prefix: label
  - key: zone
    prefix: zone
      
# drop any servers without an "ansible" label
# (ie. gke managed nodes)
filters:
  - labels.ansible != ""

# hostname shown in inventory
hostnames:
  - name

# ssh to hosts using private IP address
compose:
  ansible_host: networkInterfaces[0].networkIP

Upvotes: 1

Baptiste Mille-Mathias
Baptiste Mille-Mathias

Reputation: 2169

I never use this inventory module but according the module page, the filter should be something like that:

filters:
    - labels = ansible

Upvotes: 0

Related Questions