如何使用ansible扩展Windows路径变量 [英] how to extend windows path variable using ansible
问题描述
使用 win_environment,可以向 Windows 主机添加/删除环境变量.但是要修改已经存在的变量, win_environment 似乎没有用,因为您无法读取旧值来修改和更新变量.对吗?
Using win_environment, it is possible to add/remove environment variables to a windows host. But to modify variables that are already there, win_environment does not seem to be useful as u can't read old value to modify and update a variable. right?
推荐答案
从 Ansible 2.3 开始,win_path 模块为您完成所有繁重的工作.只需给它一个路径中应该存在的项目列表,它就会确保它们存在并且按照您指定的相对顺序.
Since Ansible 2.3, the win_path module does all the heavy lifting for you. Just give it a list of items that should be present in the path and it'll make sure they're present and in the relative order you specified.
(如果你还在使用旧版的 Ansible,下面的方法仍然可行)
(if you're still using an ancient version of Ansible, the following is still the way to go)
要使其正常工作,您需要结合替换和搜索过滤器,以便仅在没有您想要的值时才进行更改.例如(这是针对 Ansible 1.9):
To get this to work sanely, you'll want to combine with a replace and search filter to only make the change if the value you want isn't in there. For instance (this is for Ansible 1.9):
- raw: echo %PATH%
register: path_out
- win_environment:
name: path
value: "{{ path_out.stdout | regex_replace('[\r\n]*', '') + ';C:\\\\newpath' }}"
state: present
level: machine
when: not (path_out.stdout | search("(?i)c:\\\\newpath"))
这比它应该的要困难得多 - 我有一半的想法为 2.0 编写一个 win_path 模块以使其更容易......
This is a lot harder than it should be- I've got half a mind to hack up a win_path module for 2.0 to make it easier...
对于 2.0,raw
在 Powershell 下运行,因此您需要 Get-Item env:PATH
代替.
For 2.0, raw
runs under Powershell, so you'd want Get-Item env:PATH
instead.
这篇关于如何使用ansible扩展Windows路径变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!