如何使用Ansible设置环境变量 [英] How to set environmental variables using Ansible
问题描述
我需要设置像JAVA_HOME
这样的变量并更新PATH
.有很多方法可以做到这一点.一种方法是使用 lineinfile 模块更新/etc/environment
变量并为JAVA_HOME
包含一行,然后直接在来宾操作系统(在我的情况下为CentOS)上运行命令源/etc/environment
.
I need to set the variables like JAVA_HOME
and update PATH
. There are a number of ways of doing this. One way is to update the /etc/environment
variable and include a line for JAVA_HOME
using the lineinfile module and then run the command source /etc/environment
directly on the guest OS (CentOS in my case).
另一种方法是执行导出命令,例如
Another way is to execute the export command e.g.
export JAVA_HOME=/usr/java/jre1.8.0_51
export PATH=$PATH:$JAVA_HOME
是否有一种更干净的方法来执行此操作,因为所有这些操作都需要直接在OS上操作文件并运行命令来更新环境变量?
Is there a cleaner way to do this as all these require manipulating files and running commands directly on the OS to update the environment variables?
推荐答案
是的,有一种更清洁的方法.您可以为每个任务设置环境变量:
Yes, there is a cleaner way. You can set environment variables per task:
tasks:
- shell: echo JAVA_HOME is $JAVA_HOME
environment:
JAVA_HOME: /usr/java/jre1.8.0_51
register: shellout
- debug: var=shellout
输出:
Output:
TASK: [shell echo JAVA_HOME is $JAVA_HOME] **********************************
changed: [localhost]
TASK: [debug var=shellout] ****************************************************
ok: [localhost] => {
"var": {
"shellout": {
"changed": true,
"cmd": "echo JAVA_HOME is \"$JAVA_HOME\"",
"delta": "0:00:00.005797",
"end": "2015-08-07 06:32:47.295061",
"invocation": {
"module_args": "echo JAVA_HOME is \"$JAVA_HOME\"",
"module_name": "shell"
},
"rc": 0,
"start": "2015-08-07 06:32:47.289264",
"stderr": "",
"stdout": "JAVA_HOME is /usr/java/jre1.8.0_51",
"stdout_lines": [
"JAVA_HOME is /usr/java/jre1.8.0_51"
],
"warnings": []
}
}
}
如果在任务中像上面一样设置环境变量,则该变量仅可用于此特定任务.在后续任务中,除非再次定义,否则它不存在.
If you set the environment variable like above in a task, it is only available for this specific task. In subsequent tasks it does not exist unless you define it again.
尽管您也可以定义每次播放的环境变量:
Though you can define env vars per play as well:
- hosts:
- localhost
gather_facts: no
environment:
JAVA_HOME: /usr/java/jre1.8.0_51
tasks:
...
现在它将可用于此剧的所有任务.
Now it's gonna be available for all tasks of this play.
Another example with a script task:
tasks:
- script: /tmp/script.sh
environment:
JAVA_HOME: /usr/java/jre1.8.0_51
register: shellout
- debug: var=shellout
该脚本仅包含以下内容:
Where the script simply has this content:
#!/bin/sh
echo JAVA_HOME is $JAVA_HOME
这篇关于如何使用Ansible设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!