How to get IP address from controller's /etc/hosts file?

I’m trying to get the IP address of one of my remote hosts by querying my controller machine’s /etc/hosts file which happens to contain the IP addresses of all the servers I build with Ansible. My Ansible playbook looks like this:

`

Note that my awk command should say “print $1” to get the IP address. I don’t see a way to edit my original question here to make this change.

Hi,

Not read everything but first thing is that if you have a pipe in a command call… you should use shell module instead… That should fix your first issue.

Regards,

JYL

Hi Robert,

Try using the shell module instead of the command module. The command module doesn’t execute a command in a shell, hence you cannot use shell functionality such as a pipes and redirections.

Hope that helps!

–Juerg

I neglected to mention that I did try the shell and it did not fix the problem. But thanks for the suggestion!

Hii

If you

  1. Properly format your playbook to be a list of plays
  2. Use shell
  3. Don’t use {{ }} around the var in your debug task

Then it works:

TASK [get file server’s IP address] ****************************************************************
changed: [villa → localhost]

TASK [debug] ***************************************************************************************
ok: [villa] =>
fs_ip_addr:
changed: true
cmd: grep prod-fs1 /etc/hosts | awk ‘{ print $0 }’
delta: ‘0:00:00.008973’
end: ‘2020-03-04 00:36:05.873228’
failed: false
rc: 0
start: ‘2020-03-04 00:36:05.864255’
stderr: ‘’
stderr_lines:
stdout: 10.10.10.20 prod-fs1
stdout_lines:

  • 10.10.10.20 prod-fs1

But I would also recommend:

  1. Dropping privilege escalation for local actions
  2. Use “print $1” as this will match the actual IP
  3. Use ‘stdout’ sa this will be the actual IP

Thus the playbook would be:

Dick,

Thank you very much! Your solution worked. I realized after I posted my question that I should have said “print $1” but I didn’t see a way to edit my question. I had also forgotten that when you do “debug: var=…” that you have to drop the double braces; they’re only used when you do “debug: msg=…”. Removing privilege escalation and using stdout were new to me. Thanks again.