Search code examples
ansiblejmespath

How do I use Ansible's `json_query_filter` (JMESPath) to extract a JSON value keyed by a dash?


I'm working with Ansible! I've got a nice data structure returned by

- name: list ec2 instances
  ec2_instance_facts:
    region: '{{aws_primary_region}}'
    filters:
      "tag:organization-tag-1": "specific-value"
  register: instances

I would like to transform these results to extract the value of org-specific-tag2. I can do something like

- name: extract instance tags
  set_fact:
    instance_tags: '{{instances | json_query(query)}}'
  vars:
    query: "instances[*].tags"

to get the tags as a data structure:

        {
            "Name": "box-1138", 
            "organization-tag-1": "specific-value", 
            "organization-tag-2": "value being queried"
        }, 
        {
            "Name": "box-999", 
            "organization-tag-1": "specific-value", 
            "organization-tag-2": "value being queried 2"
        }

I can use this in with_items and access item["organization-tag-2"]. This is not a problem. However, it'd be far more elegant for me to just set the list to ["value being queried", "value being queried 2"] to begin with. I just can't figure out how because the tag has a dash in it, and the syntax guide on the JMESPath documentation is... very opaque.

How do I extract the dash in the JSON query filter?


Solution

  • Take a look at JMESPath grammar:

    sub-expression    = expression "." ( identifier /
                                         multi-select-list /
                                         multi-select-hash /
                                         function-expression /
                                         "*" )
    identifier        = unquoted-string / quoted-string
    quoted-string     = quote 1*(unescaped-char / escaped-char) quote
    quote             = %x22   ; Double quote: '"'
    

    So you should be fine with:

    - name: extract instance tags
      set_fact:
        instance_tags: '{{instances | json_query(query)}}'
      vars:
        query: 'instances[*].tags."organization-tag-2"'