Register data from script Ansible.

I am going to keep this post short and sweet and hope someone can help me wrap my head around how to grab values from key,value pairs returned by a script I an running.

I use the ansible “shell:” module to run a script that generates and API key and ID and prints the results to stdout and then I use register to save the data.

Lets say I use register: or set_fact: to save the results of the following command to ‘keyobject’:

./script generatekey bar --bw --obj
{
“app”: “bar”,
“id”: “3aa234234dfadsf2348351”,
“key”: “aeb46dasdfasdfcc9c5e2b031edsdddd2e56c33c7d61efbb071fb06”
}

When I attempt to do a simple debug: msg=“{{ keyobject” }} it will print everything out no problem (with some extra stuff added). But if I try something like {{ keyobject[‘key’] }} or keyobject.key or any other multitude of variations on that I am not having much success. It seems the json gets mangled or extra info added like ‘msg’.

I am too worn out now to post all of the different things I have tried and their resulting failures. I’ve gotten close but not further than close. If this isn’t possible let me know and I will stop torturing myself.

Based on the above output what would you try? I’ve also tried from_json and some other things. I was certain I would have this pegged within a few hours but after reading a million posts and trying to figure it out unsuccessfully with a co-worker I am feeling defeated :slight_smile:

Thanks!

Hi Jimmy,

I think that if you do:

  • name: set the fact
    set_fact:
    keyobject: “{{ registerVar|from_json }}”

You should then be able to do keyobject[key]. The “complex arguments” form works because Ansible (for reasons I am not fully understanding) will preserve the data structure when passed this way, but not using the all-in-one-line form with the equals signs.

Hope this helps!

-Tim

The debug msg keyword is really only there to print simple strings, this works better:

  • debug: var=foo

It can’t take complex expressions, but will dump a top level variable.

Hey all,

Timothy,

I think I tried your way but I will give it another go.

Michael,

I’ve tried both. I’m using debug: var/msg to figure out what {{ foo.value }} I need to put elsewhere then I was going to remove it.

I’ll just get some flags added to the script so that it returns exactly the value I want instead of a dict after I try the above suggestions.

Thanks for the replies!