通过~/.profile文件设置
env01.yaml
---
- hosts: ubuntu
tasks:
# 设置环境变量
- name: 设置环境变量
lineinfile:
dest: ~/.profile
regexp: ^export ENV_KEY=
line: export ENV_KEY=env_value
- name: 获取环境变量值 #指定bash shell,默认是使用/bin/sh,/bin/sh无法执行source命令
shell: bash -c 'source ~/.profile && echo $ENV_KEY'
register: env_key
- name: 打印环境变量,inventory_hostname 是当前主机在inventory清单文件中的名称,默认情况下会在playbook中显示出来,一般为ip,也可以自定义名称
debug:
msg: "this linux os {{ inventory_hostname }} env_key is {{ env_key.stdout }}"
- name: 打印环境变量 #ansible_env 变量不包含lineinfile模块设置的变量,不知道为什么
debug:
msg: "{{ ansible_env }}"
通过playbooke文件硬编码设置
env02.yaml
---
- hosts: ubuntu
tasks:
- name: 设置环境变量
get_url:
url: https://files.pythonhosted.org/packages/fa/de/02b54f42487e3d3c6efb3f89428677074ca7bf43aae402517bc7cca949f3/PyYAML-6.0.2-cp313-cp313-win_amd64.whl
dest: /tmp
environment:
http_proxy: http://1.1.1.1:80/
https_proxy: https://1.1.1.1:443/
通过playbooke文件变量设置
env02-1.yaml
---
- hosts: ubuntu
vars:
#为一个下载任务设置http代理
vars_proxy:
http_proxy: "http://1.1.1.1:80/"
https_proxy: "https://1.1.1.1:443/"
tasks:
- name: debug环境变量
debug:
var: vars_proxy
- name: 设置环境变量
get_url:
url: https://files.pythonhosted.org/packages/fa/de/02b54f42487e3d3c6efb3f89428677074ca7bf43aae402517bc7cca949f3/PyYAML-6.0.2-cp313-cp313-win_amd64.whl
dest: /tmp
environment: "{{ vars_proxy }}"
通过proxy_state状态控制变量状态
env03.yaml
---
- hosts: ubuntu
vars:
proxy_state: present
tasks:
- name: Configure the proxy.
lineinfile:
dest: /etc/environment
regexp: "{{ item.regexp }}"
line: "{{ item.line }}"
state: "{{ proxy_state }}"
with_items:
- { regexp: "^http_proxy=", line: "http_proxy=http://1.1.1.1:80/" }
- { regexp: "^https_proxy=", line: "https_proxy=https://1.1.1.1:443/" }
- { regexp: "^ftp_proxy=", line: "ftp_proxy=http://1.1.1.1:80/" }
在/etc/environment文件里配置的变量,再次登录时,会加载到env变量中,可直接通过echo $http_proxy打印出来
ansible ubuntu -m shell -a 'echo $http_proxy '
107.151.199.209 | CHANGED | rc=0 >>
http://1.1.1.1:80/
标签:https,http,1.1,ansible,proxy,设置,环境变量,name
From: https://www.cnblogs.com/anyux/p/18361631