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.
EDIT: I found this duplicate question which is the same as mine, however it also is unanswered so will leave this open for a bit.
works, but you have to gather facts about connection variables from default user, so eighter:
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).
The easiset way is to add connection local
The "ipify_facts" method described in a different answer should work if:
If either of the above conditions is not met (that is, if your control host has multiple interfaces and/or your control host as well as your remote host are both behind NAT and using private addresses), then a different (albeit slightly more complex) way is to replicate the following in Ansible:
This will show you the interface and the source address (172.26.232.125) to be used for reaching towards a specific destination (203.0.113.4).
One way to implement this in Ansible would be:
Output:
This should also work if you have multiple remote hosts reachable via different interfaces.
An additional step in the "shell" action would be needed if your inventory_hostname was a DNS hostname as opposed to a numerical IP address.
I just hacked this solution and it worked. Is this something you are looking for?