如何将本地shell变量注入ansible [英] How to inject local shell variables into ansible

查看:33
本文介绍了如何将本地shell变量注入ansible的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的意图:

我在 Virtualbox 中有一个带有桥接网络的 VM linux,说它的 ip 是 192.168.1.11,并且我在托管的 mac 上运行了一个 http 代理,说它是 192.168.1.4:1087,由于主机mac的ip,192.168.1.4是dhcp地址,可能会改变.

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.

我在 mac 上创建了一个 update_http_proxy.sh 并使用 ansible 向 VM 运行它.

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

此文件将上传到 VM 并执行.但是如何在上传到远程虚拟机之前用 mac 上的环境变量 $http_proxy 替换 `{{ http_proxy }} ?

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?

推荐答案

此文件将上传到 VM 并执行.但是如何在上传到远程虚拟机之前用 mac 上的环境变量 $http_proxy 替换 `{{ http_proxy }} ?

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?

您正在寻找的是--extra-vars,或者将此类信息添加到动态库存脚本中

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

你也可以委托你的本地主机来获取它的 IP 地址,以避免做任何特殊的启动:

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

您可以选择使用 gather_facts: no 运行剧本以避免必须进行初始事实收集,因为由于 设置的怪癖,您必须重新收集事实: 总是覆盖 hostvars[inventory_hostname] 而不是 hostvars["localhost"] 正如人们可能期望那样 delegate_to:要做的

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

这篇关于如何将本地shell变量注入ansible的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆