Ansible – grab a key from a dictionary (but not in a loop)


Another question regarding dictionaries in Ansible!

For convenience, I have certain values for mysql databases held in dictionaries, which works fine to loop over using with_dict to create the DBs and DB users.


However, I would like to use the key from one of the dictionaries in another task, but I don’t want to loop over the dictionaries, I would only like to use one at a time. How would I grab the key that describes the dictionary (sorry, not sure about terminology)?

problem task:

Error in ansible run:

I’m willing to believe with_items isn’t the best strategy here, but does anyone have any ideas what is the right one?

Thanks in advance, been stuck on this for a while now…


Given a nested dictionary…

You can either use dotted notation:

Or you can use a more Python-esque syntax:

It looks like you tried to use an unholy hybrid:

In this case, you are trying to dereference a variable named db1,
which presumably doesn’t exist and would lead to a “variable is
undefined” sort of error.


Your question is unclear because in your example you have…

…which looks like you are trying to do exactly what I have described here. If what you actually want to do is iterate over the keys of the mysql_dbs dictionary, remember that it is simply a Python dictionary and you have available all the standard dictionary methods, so:

The output of which would be:

Leave a Reply