Chef条件资源参数 [英] Chef conditional resource argument
问题描述
我正在通过Chef创建一个用户。他的属性存储在数据袋中:
I'm creating a user via Chef. His properties are stored in data bag:
{
"id": "developer",
"home": "/home/developer",
"shell": "/bin/zsh",
"password": "s3cr3t"
}
配方为:
developer = data_bag_item('users', 'developer')
user developer['id'] do
action :create
supports :manage_home => true
home developer['home']
comment developer['comment']
shell developer['shell']
password developer['password']
end
问题是如果 zsh
不是安装在节点上,我无法以 developer
身份登录。因此,我想有条件地为 user
资源应用参数,例如:
The problem is that if zsh
is not installed on node, I cannot login as developer
. So, I want to conditionally apply argument for user
resource, like:
user developer['id'] do
action :create
supports :manage_home => true
home developer['home']
comment developer['comment']
if installed?(developer['shell'])
shell developer['shell']
end
password developer['password']
end
如何我可以实现这一目标吗?
How can I achieve this?
推荐答案
为了补充@mudasobwa的答案,请在厨师中进行正确的选择,并避免丢失外壳由另一个配方或同一配方中的软件包资源安装,则必须使用惰性属性评估。
To complement @mudasobwa's answer the proper way to do it in chef and avoid missing the shell if it's installed by another recipe or a package resource in the same recipe you have to use lazy attribute evaluation.
长版的thoose对如何以及为什么感兴趣:
Long version for thoose interested on the how and why:
这是一面影响厨师的工作方式,这是第一次编译资源以构建集合,在此阶段,如果对食谱中的任何红宝石代码(在ruby_block资源之外)进行了评估。完成此操作后,资源集合将收敛(将所需状态与实际状态进行比较,并完成相关操作)。
This is a side effect on how chef works, there's a first time compiling the resources to build a collection, at this phase any ruby code in a recipe (outside of a ruby_block resource) if evaluated. Once that is done the resources collection is converged (the desired state is compared to the actual state and relevant actions are done).
以下方法可以做到:
package "zsh" do
action :install
end
user "myuser" do
action :create
shell lazy { File.exists? "/bin/zsh" ? "/bin/zsh" : "/bin/bash" }
end
发生了什么这是因为对shell属性值的评估被延迟到了收敛阶段,我们必须使用if-then-else构造(这里使用三元运算符,因为我发现它更具可读性)来回退到shell,我们确定将会出现(我使用了 / bin / bash
,但故障保护值将是 / bin / sh
)或shell属性将为nil,这是不允许的。
What hapens here is that the evaluation of the shell attribute value is delayed to the converge phase, we have to use a if-then-else construction (here with a ternary operator as I find it more readable) to fallback to a shell we're sure will be present (I used /bin/bash
, but a failsafe value would be /bin/sh
) or the shell attribute will be nil, which is not allowed.
使用此延迟的评估,在安装软件包之后对 / bin / zsh的存在进行测试并且该文件应该存在。如果包内有问题,用户资源仍会创建用户,但带有 / bin / bash
With this delayed evaluation the test on the presence of "/bin/zsh" is done after the package has been installed and the file should be present. In case there was a problem within the package, the user resource will still create the user but with "/bin/bash"
这篇关于Chef条件资源参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!