How to inject local shell variables into ansible

Here's my intention:

I have a VM linux in the Virtualbox with a bridge network, say it's ip is 192.168.1.11, and i run a http proxy on the hosted mac, say it's 192.168.1.4:1087, because the ip of the host mac, 192.168.1.4 is a dhcp address and may changed.

I created a update_http_proxy.sh on mac and run it towards the VM with ansible.

#!/bin/bash

cat /etc/profile | egrep -v 'http_proxy|https_proxy|no_proxy' > /tmp/profile_$$

cat >> /tmp/profile_$$ <<EOF

export http_proxy={{ http_proxy }} # this is not replaced with the mac variables
export https_proxy=http://192.168.1.4:1087 # this works but I have to edit the shell when the mac ip changed.
export no_proxy="127.0.0.1,localhost,192.0.0.0/8"
EOF
cp /tmp/profile_$$ /etc/profile

This file will be uploaded to the VM and executed. but how to replace the `{{ http_proxy }} with the env varialbe $http_proxy on the mac before uploaded to the remote VM?

1 answer

  • answered 2019-01-11 06:34 Matthew L Daniel

    This file will be uploaded to the VM and executed. but how to replace the `{{ http_proxy }} with the env varialbe $http_proxy on the mac before uploaded to the remote VM?

    The thing you are looking for is --extra-vars, or to add such information to a dynamic inventory script

    $ ansible-playbook --extra-vars "http_proxy=$http_proxy" ...
    

    You can also delegate to your localhost to grab its ip address, to avoid having to do any kind of launch specialness:

    - name: get the control host info
      setup:
      delegate_to: localhost
    - name: get the control host info
      set_fact:
        host_ip: '{{ ansible_default_ipv4.address }}'
    - name: re-gather facts of target host
      setup:
    - set_fact:
        http_proxy: http://{{ host_ip }}:1087
    

    You can optionally run the playbook with gather_facts: no to avoid having to do the initial fact gathering, since you'll have to re-gather the facts due to a quirk of setup: always overwriting hostvars[inventory_hostname] and not hostvars["localhost"] as one might expect that delegate_to: to do