Bootstrap FreeKB - Ansible - Store JSON value in variable
Ansible - Store JSON value in variable

Updated:   |  Ansible articles

Let's say you have the following json and you want to store the value (bar) in a variable.

{
  "foo": "bar"
}

 

You would have likely used the vars and lookup modules or register module to store the raw json in a variable. Lets say the json is store in a variable named raw_json. 

The set_fact module can be used to store the value "bar" in a variable named "var1", and the debug module can be used to print the "var1" variable. Notice the double curley braces {{ ... }}. Jinja2 uses double curley braces for variables.

- name: set_fact value
  set_fact:
    var1: "{{ raw_json.foo }}"

- name: print var1
  debug: 
    msg: "{{ var1 }}"

 

Running this play should return the following.

TASK [print var1]
ok: [server1.example.com] => {
      "msg": "bar"
}

 


Array

Let's say you have the following json and you want to store the value of foo (hello) in a variable. In this example, the [ ] characters mean the data is in an array.

[
  {
    "foo": "hello",
    "bar": "world"
  }
]

 

The set_fact module and loop modules can be used to store the value of foo (hello) in a variable named "var1", and the debug module can be used to print the "var1" variable.

- name: set_fact value
  set_fact:
    var1: "{{ item.foo }}"
  loop: "{{ raw_json }}"

- name: print var1
  debug: 
    var: var1

 

Running this play should return the following.

TASK [print var1]
ok: [server1.example.com] => {
      "var1": "hello"
}

 

when statement

Additionally, you could use a when statement to do something when the value variable evaluates to true or false, like this.

- name: set_fact value
  set_fact:
    var1: "{{ raw_json.foo }}"

- name: return value
  debug: 
    msg: "var1 contains a value of 'hello'"
  when: "var1|string == 'bar'"

 

Or let's say you have the following JSON array, where there are no keys, just values.

"results": [
  "hello world",
  "goodbye world"
]

 

The set_fact module and loop modules can be used to store the value of foo (hello) in a variable named "var1", and the debug module can be used to print the "var1" variable.

- name: set_fact value
  set_fact:
    var1: "{{ item }}"
  with_items: "{{ results }}"
  when: item is search 'hello'

- name: print var1
  debug: 
    var: var1

 

Running this play should return the following.

TASK [print var1]
ok: [server1.example.com] => {
      "var1": "hello world"
}



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter b8418f in the box below so that we can be sure you are a human.