Chris Weiss
Chris Weiss

Reputation: 157

Ansible: Create variables from json string

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.

Upvotes: 4

Views: 9282

Answers (1)

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22595

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}}"

Upvotes: 8

Related Questions