Best way to get the IP address of the Ansible control machine

Question:

I am using Ansible and ufw to setup a firewall on my servers. As part of the ufw rules I would like to allow SSH from the Ansible control machine, but not from anywhere else. My question is – what is the best way to get the IP address of the control machine itself so I can put it into the rule?

I’m aware that I can use facts to get the IP address of the machine I am running the playbook on, but I don’t see any easy way to get it automatically for the machine that is running ansible.

I’d like to avoid adding a new variable to represent this if possible since it would be nice if it was automatically discoverable, though if that’s the only known best way to do it then I will just do that.

Answer:


works, but you have to gather facts about connection variables from default user, so eighter:

  • Set «gather_facts: yes» and not «become: yes» on playbook level
  • More reliable: run «setup» task (without «become: yes» and before this «ansible_env» usage — better on «pre_tasks» section).

If you run «gather/setup» with «become», you will later get «One or more undefined variables: ‘dict object’ has no attribute ‘SSH_CLIENT’» (this is becase sudoed «setup» can catch only small set of variables).

Leave a Reply