I’ve seen a few other questions that are similar to my need, however I’m still having a really hard time figuring out how I need to get exactly what I need from this json. Here’s my ansible debug task:
- debug: msg: "{{ foreman_environments.stdout }}"
and here’s the output:
ok: [127.0.0.1] => { "msg": "[{'id': 12, 'name': 'CDE', 'label': 'CDE', 'permissions': {'readable': True}}, {'id': 7, 'name': 'QA3', 'label': 'QA3', 'permissions': {'readable': True}}, {'id': 4, 'name': 'Library', 'label': 'Library', 'permissions': {'readable': True}}, {'id': 6, 'name': 'Development', 'label': 'Development', 'permissions': {'readable': True}}, {'id': 8, 'name': 'Production', 'label': 'Production', 'permissions': {'readable': True}}]" }
I need to essentially capture the ‘id’ value where the ‘name’ key is equal to x. In this exact case I want to get the ID of QA3, but I might need to capture the ID of other environments as well. So I need to take this list of environments and return the value of id where name == some name. Then I need to search for that ID in a different list that contains all the different versions.
Here’s what I’ve tried:
- debug: msg: "{{ foreman_environments.stdout | selectattr('name', 'equalto', 'QA3') | list | last | to_json }}"
and here’s the output I get:
{"msg": "The task includes an option with an undefined variable. The error was: 'str object' has no attribute 'name'nnThe error appears to be in '/opt/git/ci_cd_ansible/playbook_publish_foreman_view.yml': line 36, column 7, but maynbe elsewhere in the file depending on the exact syntax problem.nnThe offending line appears to be:nnn - debug:n ^ heren"}
I need to be able to register the result and then use that registered result to functionally do this same thing but against a different set of data. Can someone help me understand what I’m missing?
EDIT:
I’ve changed my method to use "{{foreman_environments.stdout | selectattr('name', 'equalto', 'QA3') }}"
and that returns a generator object. If I try to translate that to a list, though, i get an error:
fatal: [127.0.0.1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'str object' has no attribute 'name'nnThe error appears to be in '/opt/git/ci_cd_ansible/playbook_publish_foreman_view.yml': line 36, column 7, but maynbe elsewhere in the file depending on the exact syntax problem.nnThe offending line appears to be:nnn - debug:n ^ heren"}
2
Answers
Here's the answer I was looking for. Took me all day to get it.
Trying to use .stdout I think is what messed me up. Something about that output format just wasn't working as expected. I just used the original json output and filtered it down to the same chunk then selectattr() worked as expected. I also had to figure out that the parentheses needed to go around the entire statement, but inside of the {{}} in order to get the ['id'] to work.
The filter json_query gives the same result
Example of a complete playbook for testing
gives