How to retrieve a specific result from multiple command registered to a variable

60 views
Skip to first unread message

Arthur Reyes

unread,
Mar 17, 2016, 7:49:50 PM3/17/16
to Ansible Project
I have a series of commands registered to the same var

- shell: ls -alh'{{ item }}'
 
register:cmd_output
with_items
:
 
- '/home/1'
 
- '/home/2'

For some plays, I only need to evaluate a specific stdout. Assuming I want to the results of 'ls -alh /home/2', my current method is to loop through cmd_output and return stdout when the cmd matches my criteria:

- debug:
  msg
: '{{ item.stdout }}'
 
when: ( '{{ item.cmd }}' == 'ls -alh /home/1' )
  with_items
: '{{ cmd_output.results }}'

Is there a way to do this instead of looping through cmd_output.results? 

Brian Coca

unread,
Mar 17, 2016, 10:10:11 PM3/17/16
to ansible...@googlegroups.com
no, but you can use map/select filters to loop over it instead of a `with_`


----------
Brian Coca

Arthur Reyes

unread,
Mar 17, 2016, 10:41:25 PM3/17/16
to Ansible Project
I think that's the clue I was looking for. I'll post a result tomorrow for others who come here looking for the same answer.

Arthur Reyes

unread,
Mar 18, 2016, 10:18:37 AM3/18/16
to Ansible Project
For anyone looking for a solution.

Given this code

- shell: ls -alh'{{ item }}'
  
register:cmd_output
with_items
:
  
- '/home/1'
  
- '/home/2'

I can retrieve the stdout of a specific command without looping through cmd_output, like so:

- debug:
  msg: '{{ cmd_output.results | selectattr("cmd", "equalto", "ls -alh /home/1" ) | map(attribute="stdout") | join("") }}'


Some caveats ... equalto wasn't a valid test in the CentOS 7.2 Python 2.7.5 package. I ended up compiling Python 2.7.10, then using pip to install ansible, which was an original design requirement which I just got back to fulfilling.

Brian Coca

unread,
Mar 18, 2016, 10:39:31 AM3/18/16
to ansible...@googlegroups.com
that is actually a jinja2 issue, 'equalto' would have been available by just upgrading jinja2 itself.


----------
Brian Coca

Arthur Reyes

unread,
Mar 18, 2016, 3:49:46 PM3/18/16
to Ansible Project
You aren't wrong.  But having spent a number of years sharing systems with Perl developers who also had sudo priviledges, makes me loathed to make changes to global packages. It's just been better, in my experience, to isolate your environment when your needs start to diverge from the standard distros.

Uditha Desilva

unread,
Mar 18, 2016, 4:00:14 PM3/18/16
to Ansible Project
Faced with a similar issue, I initially wrote a script to which I could pass all my parameters to be operated on, and then a custom module :-)
Reply all
Reply to author
Forward
0 new messages