0

I'm trying to execute this on the Master Node

ansible all -m shell -a "/bin/ping -c3 `hostname`"

And instead of pinging remote hostname, it's pinging Master Node

e.g., Master Node hostname = Master

Remote Node hostname = Slave

The above command does this

/bin/ping -c3 Master (instead of /bin/ping -c3 Slave)

Please suggest on how to achieve this in Ansible.

k_vishwanath
  • 1,326
  • 2
  • 20
  • 28

2 Answers2

2

If you backquote the hostname like this: `hostname` then it is a command that will be executed on the localhost. If you really want to execute it on remote host, then use inventory_hostname

Try:

ansible all -m shell -a "/bin/ping -c3 {{inventory_hostname}}"

If you want to execute hostname in the target host, then escape the backquote so that it is not interpreted by the shell on local machine.

ansible all -m shell -a "/bin/ping -c3 \`hostname\`"
helloV
  • 50,176
  • 7
  • 137
  • 145
0

Adding to helloV answer,while inventory_hostname is taken from your inventory files, you might also want to look at

  • {{ ansible_nodename }} - hostname as the system reports it
  • {{ ansible_hostname }} - unqualified hostname that shows the string before the first period(.)

If you really want to use output of hostname command instead of ansible gathered facts, you should use single quotes in your command, like

ansible all -m shell -a '/bin/ping -c3 `hostname`'

Single quotes will preserve exact syntax to be passed to remote hosts, while when you are using double quotes, expression will be evaluated on master node before passed forward to managed hosts

See Difference between single and double quotes in Bash for future reference.

Also, so please use $(command) syntax instead of `command`, see https://unix.stackexchange.com/questions/126927/have-backticks-i-e-cmd-in-sh-shells-been-deprecated

Community
  • 1
  • 1
Andrew
  • 3,912
  • 17
  • 28
  • ansible all -m shell -a '/bin/ping -c3 `hostname` ' is preserving the command as it is. ping: unknown host `hostname` – k_vishwanath May 02 '17 at 16:19
  • http://www.grymoire.com/Unix/Quote.html has detailed info on single and double quotes – k_vishwanath May 02 '17 at 16:33
  • Are you sure? What is your target system? On both centos6 and opensuse respectively command ansible -i 10.0.8.82,127.0.1 -m shell -a '/bin/ping -c3 $(hostname)' produced desired result – Andrew May 02 '17 at 16:40
  • with backticks test comand on opensuse and centos 6 ansible -i 10.0.8.82,127.0.1 -m shell -a 'echo `hostname`: `uname -r`' all 127.0.1 | SUCCESS | rc=0 >> linux-4xmi: 4.4.57-18.3-default 10.0.8.82 | SUCCESS | rc=0 >> master: 2.6.32-642.el6.x86_64 – Andrew May 02 '17 at 16:44
  • I'm running the command on centOS 7 and neither the backticks nor the $ one helped here.. "$(hostname)" - taking Master hostname and not remote host name, and – k_vishwanath May 04 '17 at 12:10
  • '$(hostname)' - gives error, saying unknow host $(hostname) – k_vishwanath May 04 '17 at 12:11