Last active
May 26, 2021 07:00
-
-
Save renard/531d1d058067d7902357e10183b9d8bd to your computer and use it in GitHub Desktop.
Simple json_query example with ansible
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ansible-playbook -i localhost, | |
# Example on how to use json_query as asked by Hagen Bauer (@hbauer) | |
# https://twitter.com/hbauer/status/1366784668629139458 | |
# | |
# This requires jmespath python module (pip3 install jmespath). | |
# | |
# For further details have a look at: | |
# | |
# - https://jmespath.org/examples.html | |
# - https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html | |
# - https://www.middlewareinventory.com/blog/ansible_json_query/ | |
# | |
# | |
# This example is standalone assuming this file is executable. Simply run: | |
# | |
# ./test-json-query.yml | |
# | |
# An other version was proposed (https://gist.github.com/jpmens/02568d7dc89a838a59b5295a25a487dc) | |
# This version does not require any other variable creation. | |
- hosts: all | |
gather_facts: false | |
connection: local | |
become: false | |
vars: | |
# Minio configuration | |
minio_server: | |
- name: server1 | |
password: xyz | |
- name: server2 | |
password: abc | |
# As an example we want server1 password | |
wanted: server1 | |
tasks: | |
- name: get server2 hard-coded version | |
debug: | |
# String escaping is a mess. Rule of thumb: | |
# | |
# * Use simpl quote for the template string | |
# * Use double quote for json_query query string | |
# * Use back quote for string inside query. | |
# * Double simple quotes can also be used for strings inside query | |
# | |
msg: '{{ minio_server | |
| json_query("[? name==''server2''].password | [0]") | |
}}' | |
- name: get server1 parametric version | |
debug: | |
msg: '{{ minio_server | |
| json_query("[? name==`" + wanted + "`].password | [0]") | |
}}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment