4

I have a rather simple ansible adhoc command using shell to run chfn:

ansible all -i ./inventory/all  -s -K -m shell -a 'chfn -f "$HOSTNAME root" root'

chfn needs the double quotes, and I've tried several different ways to escape them with no luck. I've tried wrapping the shell command in double quotes and single quotes, and using / to escape the double quotes and tried single quotes as well. Running chfn -f "$HOSTNAME root" root works just fine but I can't figure out how to get ansible to run it this way. (I know it's an option, but I'd rather not turn it into a shell script and run it that way via ansible if possible)

techraf
  • 64,883
  • 27
  • 193
  • 198
Blake
  • 131
  • 3
  • 10

2 Answers2

1

When you have nested quotes, like in the sample below, you can escape the single quote by escaping it with a another single quote.

Make the surrounding quotes single quotes ' , then you dont need to escape the doublequotes " and you can escape the single quotes within your command with another single quote like ''

 - name: Notify on slack
    command: 'curl -X POST -H ''Content-type: application/json'' --data ''{"text":"{{inventory_hostname}} has been updated"}'' https://hooks.slack.com/services/XXXX/YYY/ZZZ'
    when: inventory_hostname == 'host1.de' or inventory_hostname == 'host.de'
    delegate_to: localhost
0

ansible is tricky about this in ad hoc commands. if you want to pass it as is, you have to escape the quotes. some examples below:

ansible localhost -a 'echo \"$HOSTNAME\"'
localhost | SUCCESS | rc=0 >>
"$HOSTNAME"

ansible localhost -a "echo $HOSTNAME"
localhost | SUCCESS | rc=0 >> 
my_hostname
Steve Miskiewicz
  • 1,114
  • 1
  • 10
  • 23