Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 683
Cory Avatar asked Jan 01 '16 22:01

Cory


People also ask

How do I find my Ansible host name?

In this post, we are going to see two built-in variables of ansible mostly used in Ansible playbooks and they are inventory_hostname and ansible_hostname while both these variables are to give you the hostname of the machine.

How do I change my IP address on Ansible?

Ansible playbook is preferred. @Panki has it -- just add a new_ip host var for each host, then use the playbook to change them. Or a script: for s in LIST-OF-SERVERS; do ssh $s ip a add NEWADDR/PREFIX dev NIC; ssh $s ip a del OLDADDR/PREFIX dev NIC; done . This assumes it's the same NIC for all servers.

How do you get Ansible facts?

To access the variables from Ansible facts in the Ansible playbook, we need to use the actual name without using the ansible keyword. The gather_facts module from the Ansible playbook runs the setup module by default at the start of each playbook to gather the facts about remote hosts.


2 Answers

{{ ansible_env['SSH_CLIENT'].split() | first }}

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).

like image 114
belonesox Avatar answered Oct 20 '22 16:10

belonesox


The easiset way is to add connection local

---
 - name: get my public IP
   ipify_facts: api_url=http://api.ipify.org
   connection: local

 - firewalld: rich_rule='rule family=ipv4 source address={{ ipify_public_ip }} accept' permanent=no state=enabled timeout=300
   become: true
like image 45
Suire Avatar answered Oct 20 '22 18:10

Suire