I need to collect some hostnames from a MariaDB database but don’t know exactly how to properly parse the result of my query… Could somebody help?
This how the tasks look like:
name: Collect devices in down state
community.mysql.mysql_query:
login_db: cacti
query: SELECT hostname FROM host WHERE status=1
login_unix_socket: /run/mysqld/mysqld.sock
register: cacti_query
name: print query result
debug:
msg: “{{ cacti_query.query_result }}”
And this is the output:
The contents of this message and any attachment(s) are confidential, proprietary to the City of Edmonton, and are intended only for the addressed recipient. If you have received this in error, please disregard the contents, inform the sender of the misdirection, and remove it from your system. The copying, dissemination, or distribution of this message, if misdirected, is strictly prohibited.
“msg”: “<generator object do_map at 0x7fe0c4e9f2b0>”
Looking around I found that {{ cacti_query.query_result | map(attribute=‘hostname’) | list }} would be the solution for the message above, but instead I got:
“msg”: “[AnsibleUndefined]”
Would that possibly be caused by Ansible/Python versions?
We have Ansible 2.9.7 and Python 3.6.8.
That’s twice this morning a working solution was inapplicable b/c someone was still running Ansible 2.9. I know people don’t always get to pick the version of whatever software they have to use because of factors beyond their control. We were stuck on 2.9 far longer than we would have liked.
However, if it’s at all possible, IMO, any time spent trying to make stuff work under 2.9 rather than moving to a later version is time seriously wasted. There have been so very many improvements.
Adding “| list” as you did should have been enough, though. It makes me wonder what was in your registered result on that particular run.
Sorry I can’t offer any actionable suggestions. Good luck,
Is giving me:
"The task includes an option with an undefined variable. The error was: list object has no element AnsibleUndefined(hint=None, obj=missing, name=‘hostname’).
Could you give one last insight about that?
(I have no intention to drag this out for longer and keep bothering our list with something that I understand is simple but I don’t have yet the knowledge to solve.)
You’d need to show what’s registered to cacti_query. It appears to be saying it doesn’t contain anything named “hostname”. It may not contain “query_result” either. Like I said before, it makes me question what’s registered by your query in that particular run. Stick another debug task before that showing what’s being registered by the db query task.
The issue was the oversight of “[0]” on cacti_query.query_result.
Just in case…
For a few of those still having to deal with 2.9, going with “{{ cacti_query.query_result[0] | map(attribute=‘hostname’) | list }}” also produced the same result.