How to mention wildcard in ansible commands
Using ansible on the command line to execute ad hoc commands, a wildcard is very useful, e.g. to see if a file exists on all systems.
I too struggled to do:
$ ansible production -a "ls /mypath/*xxx*"
But wrapping it in bash -c '...' works:
$ ansible production -a "bash -c 'ls /mypath/*xxx*'"
A task defined like this would do the trick:
- name: Move internal directories and files
command: bash -c 'mv /tmp/parent-dir/* /opt/destination/'
As Larsks wrote the key is to use register
, but the code was not working on my current ansible version. So here is corrected one:
- shell: ls -d solr*
register: dir_name
- command: chdir={{ item }} some_command
with_items: dir_name.stdout_lines
No. The chdir=
parameter to, e.g., the command
module does not support wildcards.
You could accomplish what you want using a register variable to store the output of the ls
command:
- shell: ls -d solr*
register: dir_name
- command: some_command
args:
chdir: "{{ dir_name.stdout }}"
But this is, frankly, an ugly solution. You're better off just using the actual directory name. If it differs on different hosts, you can use host variables to set it appropriately.