cancel
Showing results for 
Search instead for 
Did you mean: 
Razique
Flight Engineer Flight Engineer
Flight Engineer
  • 5,871 Views

Quick tip for the uri module to work with integers

I wanted to share this nice tip that I was able to use today.

What I needed to do is to interact with the Ansible Tower API to associate a host to a group. I retrieved the host ID by parsing the JSON dictionnary. However, when I invoked later on the uri module, I noticed that Jinja2 would always return a string, whereas I needed an integer.

The int filter would not work "as is"  - the solution is rather neat, and only requires to send the JSON body to Ansible directly:

 

- name: Associate host to group
  uri:
    url:  "https://localhost/api/v2/groups/{{ group_id.json.results[0].id }}/hosts/"
    method: POST
    user: admin
    password: "{{ towerpass }}"
    body:
# Notice the construct - this allows me to ass the ID as an integer
# instead of a string '{ "id": {{ host_id.json.results[0].id | int }} }' body_format: json validate_certs: False force_basic_auth: yes status_code: - 200 - 204 - 400 register: response changed_when: response.status == 20

Happy Ansibl'ing!

 

Labels (1)
4 Replies
littlebigfab
Starfighter Starfighter
Starfighter
  • 5,858 Views

Hi @Razique !

 

That's a nice one, thanks ! Maybe useful for my upcoming EX447 :D

I found another way to do it:

body: "{{ host_id.json.results | json_query('[].{id:id}') | first }}"

 

You can replace the | first filter by a more advanced query inside the brackets to exactly match the host you want.

I don't like it very much either. I hope the | int filter will be improved in the future so that the natural construction key: value | int would just work as it should ;)

Razique
Flight Engineer Flight Engineer
Flight Engineer
  • 5,804 Views

So, this one uses the native JSON parser to access the id entry? How does the id:id work?

0 Kudos
littlebigfab
Starfighter Starfighter
Starfighter
  • 5,798 Views

Hi! :)

Yes exactly.

The idea here is to extract the key/value pair at once, so that Ansible does not transform the value type to string from integer.

The id:id is a JMESpath multiselect (second example). The first id is an arbitrary name that you want to use as the key name in the resulting key/value list, in this case the key name which is needed in the body of your uri request. The second id is the key to get the value from in your input json structure (for each item of host_id.json.results).

I regularly use this syntax to select only a few interesting key/value pairs from a list of larger dictionaries.

Razique
Flight Engineer Flight Engineer
Flight Engineer
  • 5,698 Views

This is pretty cool @littlebigfab thanks for sharing this cool tip :)

0 Kudos
Join the discussion
You must log in to join this conversation.