Single quotes in Ansible shell module

I’m trying to run a command using the Ansible shell module, but having some trouble. Basically, with this command, I want to list all postgres databases on a server, then run the psql -c ‘\dx’ command against them to find out what extensions are installed in each database in the cluster.

Unfortunately, I haven’t been able to find the right combination of quotes/single quotes to get the command to run successfully.

Example: host1 has 3 postgres databases on it: db1, db2, and db3

ansible ‘host1’ -m shell -a 'for database in $(psql -l | grep ‘^ db’ | awk ‘{print $1}’); do psql -c ‘\dx’; done

I’ve tried enclosing the whole ‘for… done’ command in double-quotes, etc, but no luck :frowning:

I’ve run into this too.

My workaround is to use the script module instead of the shell module. Then you don’t have to fight with Ansible about quotes.

Added benefit: you can put your script under Version Control.

ansible host1 -m script -a example.sh

This is not tested, but should work:

ansible 'host1' -m shell -a "for database in \$(psql -l | grep '^ db' | awk '{print \$1}'); do psql -c \"\dx \$database\"; done"

When I read the OP I was not sure, if the problem are the quotes or
the backslash inside before the dx, that has to be escaped...

Johannes

I need to run this command. How do i escape the commands.

find / -xdev ( -perm -4000 -o -perm -2000 ) -type f | awk ‘{print “-a always,exit -F path=” $1 " -F perm=x -F auid>=500 -F auid!=4294967295 -k privileged"}’

It usually involves trial and error until it works.
Escaping things Ansible would expand and alternating single and double quotes.

I recommend the easier way, make a script of the command and use the Ansible Script module to run it, then you don't have to escape anything.