pythonjsonansiblejmespathjson-query

How to escape colon character in json query using ansible


Running ec2_instance_facts Ansible module and registering it to a variable called ec2.

I have tags on ec2 instance which has colon characters in its key name.

I can grab environment tag value using this:

 set_fact:
    number_of_nodes: "{{ ec2.instances|json_query('[*].tags.environment') }}"

But cannot grab value of "aws:lc:sg", trying the following:

 set_fact:
    number_of_nodes: "{{ ec2.instances|json_query('[*].tags.aws:lc:sg') }}"

Also tried by putting \, \ , /, // characters before colon. Doesn't work.

Can someone help ? :(


Solution

  • When wanting to escape ? : - the ansible docs recommend quoting them with double-quotes ". (docs here In your case that's rather difficult as you should be using single quotes in the json_query filter. You can try replacing the arguments of that filter with a var and later when you declare that var, you can use double-quotes.

     set_fact:
        number_of_nodes: "{{ ec2.instances|json_query(the_var) }}"
     vars:
        the_var: [*]."tags.aws:lc:sg"
    

    I hope this helps! Cheers!