Use Ansible control master's IP address in Jin

2019-07-01 10:08发布

I would like to insert an IP address in to a J2 template which is used by an Ansible playbook. That IP adress is not the address of the host which is being provisioned, but the IP of the host from which the provisioning is done. Everything I have found so far covers using variables/facts related to the hosts being provisioned. In other words: the IP I’d like to insert is the one in ['ansible_default_ipv4']['address'] when executing ansible -m setup 127.0.0.1.

I think that I could use a local playbook to write a dynamically generated template file containing the IP, but I was hoping that this might be possible “the Ansible way”.

3条回答
smile是对你的礼貌
2楼-- · 2019-07-01 10:24

You can force Ansible to fetch facts about the control host by running the setup module locally by using either a local_action or delegate_to. You can then either register that output and parse it or simply use set_fact to give it a useful name to use later in your template.

An example play might look something like:

   tasks:
    - name: setup
      setup:
      delegate_to: 127.0.0.1

    - name: set ansible control host IP fact
      set_fact:
        ansible_control_host_address: "{{ hostvars[inventory_hostname]['ansible_eth0']['ipv4']['address'] }}"
      delegate_to: 127.0.0.1

    - name: template file with ansible control host IP
      template:
        src: /path/to/template.j2
        dest: /path/to/destination/file

And then use the ansible_control_host_address variable in your template as normal:

...
Ansible control host IP: {{ ansible_control_host_address }}
...
查看更多
3楼-- · 2019-07-01 10:42

This is how I solved the same problem (Ansible 2.7):

- name: Get local IP address
  setup:
  delegate_to: 127.0.0.1
  delegate_facts: yes

- name: Add to hosts file
  become: yes
  lineinfile:
    line: "{{ hostvars['127.0.0.1']['ansible_default_ipv4']['address'] }}   myhost"
    path: /etc/hosts

Seems to work like a charm. :-)

查看更多
Deceive 欺骗
4楼-- · 2019-07-01 10:44

Just use this:

{{ ansible_env["SSH_CLIENT"].split()[0] }}
查看更多
登录 后发表回答