Transform data easily with Ansible
Using Ansible, I will give you a little trick to transform data like a wizard!
Method 1: Ansible Jinja filters
Filters let you transform JSON data into YAML data, split a URL to extract the hostname, get the SHA1 hash of a string, add or multiply integers, and much more. You can use the Ansible-specific filters documented here to manipulate your data, or use any of the standard filters shipped with Jinja2
filters are really nice if the use case is matching available filters!
Method 2: Ansible templating + JSON (or YAML)
What about a really complicated transformation that dont fit?
Example use case:
“playbook must read YAML files in a directory, then generate an Ansible variable of type Dict: { FILE_NAME : FILE_CONTENT } ”
Solution :
Here, we include all YAML files are variables and register the results as a variable.
Then, we create a JSON string using Ansible (jinja) templating engine.
End, from_json will transform the JSON string into Ansible variable!
Another example using YAML:
more readable.
Et voilà!