Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: Create variables from json string

Tags:

json

ansible

In Ansible, is there a way to convert a dynamic list of key/value pairs that are located in a JSON variable into variable names/values that can be accessed in a Playbook without using the filesystem?

IE - If I have the following JSON in a variable (in my case, already imported from a URI call):

{
        "ansible_facts": {
            "list_of_passwords": {
                "ansible_password": "abc123",
                "ansible_user": "user123",
                "blue_server_password": "def456",
                "blue_server_user": "user456"
            }
}

Is there a way to convert that JSON variable into the equivelant of:

vars:
  ansible_password: abc123
  ansible_user: user123
  blue_server_password: def456
  blue_server_user: user456

Normally, I'd write the variable to a file, then import it using vars_files:. Our goal is to not write the secrets to the filesystem.

like image 503
Chris Weiss Avatar asked Jan 30 '23 00:01

Chris Weiss


1 Answers

You can use uri module to make a call and then register response to variable:

For example:

- uri:
    url: http://www.mocky.io/v2/59667604110000040ec8f5c6
    body_format: json
  register: response
- debug:
    msg: "{{response.json}}"
- set_fact: {"{{ item.key }}":"{{ item.val }}"}
  with_dict: "{{response.json.ansible_facts.list_of_passwords}}"
like image 153
Krzysztof Atłasik Avatar answered Feb 03 '23 08:02

Krzysztof Atłasik