how to get the controller ip address

hello all

i am trying to get the controller ip address that is used to run the playbook.
The ip is the one when the ssh connection establishes to remote.

debug: msg=“{{ (ansible_env|default({})).SSH_CLIENT|default(‘’)}}”

the SSH_CLIENT in my case is always empty. yes, i have gather facts and still empty.

i have to workaround this by

  • name: Get the IP of the controller
    shell: “ss -4 -ntp 2> /dev/null | head -2 | grep sshd | awk ‘{print $4}’ | awk -F: ‘{print $1}’”
    ignore_errors: yes
    no_log: yes
    register: ssh_ip

but this is not reliable because there can be other users connected and the above only gets the first item

any help is appreciated, thanks in advance

ehab

i am trying to get the controller ip address that is used to run the
playbook.
The ip is the one when the ssh connection establishes to remote.

  debug: msg="{{ (ansible_env|default({})).SSH_CLIENT|default('')}}"

the SSH_CLIENT in my case is always empty. yes, i have gather facts and
still empty.

Thats because SSH_CLIENT is not a fact so your default filter is kicking in.

i have to workaround this by

   - name: Get the IP of the controller
     shell: "ss -4 -ntp 2> /dev/null | head -2 | grep sshd | awk '{print
$4}' | awk -F: '{print $1}'"
     ignore_errors: yes
     no_log: yes
     register: ssh_ip

but this is not reliable because there can be other users connected and the
above only gets the first item

any help is appreciated, thanks in advance

You could use delegated_facts

https://docs.ansible.com/ansible/latest/playbooks_delegation.html#delegated-facts

Thanks Kai

i solved my problem this way

  • name: get ansible env
    setup: filter=ansible_env
    register: a_env
    delegate_to: “{{ target_hosts }}”
    become: false
    delegate_facts: true

thanks for pointing the delegate part.

have a nice week.
my regards
ehab