# 設置環境變量
設置環境變量,可以使用lineinfile模塊
```bash
- name:
lineinfile: 指定環境變量
dest: ~/.bash_profile
regexp: ^ENV_VAR=
line: ENV_VAR=value
- name: 環境變量生效
shell: 'source ~/.bash_profile'
- name: 獲取環境變量 #通過register將環境變量保存到自定義的變量中,以便后續任務使用
shell: 'echo $ENV_VAR'
register: env_var
- name: 打印環境變量
debug:
msg: "{{env_var.stdout}}"
```
# 預定義環境變量
對于某一個play來說,我們可以使用`environment`指令來設置單獨的環境變量
例如:我們要為一個下載任務設置http代理
```bash
- name: 使用指定的代理服務器下載文件
get_url:
url: http://www.expmple.com/file.tar.gz
dest: /tmp/
environment:
http_proxy: http://example-proxy:80/
```
```bash
---
- hosts: 172.18.113.82
gather_facts: false
vars:
tasks:
- name: test
shell: "echo $username"
register: foo
environment:
username: wms
- name: print
debug:
msg: "{{foo}}"
```
我們可以將環境變量定義到vars指令中,或者外部的變量文件中
```bash
---
- hosts: 172.18.113.82
gather_facts: false
vars:
env_vars:
username: woms
tasks:
- name: test
shell: "echo $username"
register: foo
environment: "{{env_vars}}"
- name: print
debug:
msg: "{{foo}}"
```
# playbook級別設置環境變量
```bash
- hosts: testhost
roles:
- php
- nginx
environment:
http_proxy: http://proxy.example.com:8080
```