Ansible snippets - manipulating JSON data

Ansible snippets - manipulating JSON data

Recently while working with Ansible, I needed a clean way to extract JSON values and manipulate that data in a very Ansible-esque way. In this particular case, reading JSON files/variables and treating them as if they were Ansible variables, converting that list into a comma-seperated string. Turns out Ansible can handle that pretty easily, using Jinja filters. scenario and demo The following steps will use the example playbook json_example.yml. Let’s say you need to extract JSON values from a file (or variable), for use somewhere else.

Ansible Jinja expressions

Use a default variable: # Sets the region variable to the value of "my_region" or defaults to 'us-east-1'. region: "{{ my_region | default('us-east-1') }}" # Sets the region variable to the value of "my_region" or defaults to whatever "your_region" is. region: "{{ my_region | default(your_region) }}" Convert an Ansible variable to an integer and increment it. # convert to an integer and increase by 1. # this is a string, not an integer string: "3" # this will equal 4.