gpt4 book ai didi

chef-infra - 使用 Chef,如何在 "resource 1"之前执行 "resource 2",以 "resource 2"执行为条件?

转载 作者:行者123 更新时间:2023-12-04 20:39:33 29 4
gpt4 key购买 nike

我有一本包含多个食谱的 Chef 食谱,用于安装服务。 Chef-client 的工作方式是每 15 分钟(或其他固定时间间隔)重新收敛一次。现在我的食谱的第一步是停止服务,所以服务将每 15 分钟停止一次,但我真的想避免这种情况。问题是需要停止服务才能执行某些步骤。

如果我的食谱资源中只有一两个条件,我可以简单地做:

condition1 = ... # some true/false values
condition2 = ... #

service myservice do
only_if { condition1 or condition2 }
action :stop
end

resource1 do
only_if { condition1 }
end

resource2 do
only_if { condition2 }
end

但是由于我有十几个条件,在多个食谱中,它变得不优雅。有没有办法做这个伪代码的作用?
service_resource = service myservice do
# somehow don't execute this right now, but wait for
# signal from resource1 or resource2
action :stop
end

resource1 do
make sure service_resource executed first
only_if { condition1 }
end

resource2 do
make sure service_resource executed first
only_if { condition2 }
end

如果 Chef 中有一些“通知:之前”机制(而不是例如“通知:立即”),我可以使用它,但我没有找到任何类似的东西。有任何想法吗?

编辑:

在考虑更多之后,另一种方法,仍然不完美但更好,是通过定义一个被覆盖的单个属性来利用 Chef 的编译阶段。这样至少我们不必将所有条件都放在一个地方。
# in an "attributes" file:
default["stop_service"] = false

# in some recipe:
service myservice do
action :stop
only_if { node["stop_service"] }
end

# ... later, or in some other recipe file
condition1 = ... # true/false
if condition1
# I think this executes before the only_if of the "service" resource
override["stop_service"] = true
end

resource1 do
only_if { condition1 }
end

最佳答案

我会怎么做:

在“暂存”位置暂存配置,如果此更改,通知停止、复制文件、启动服务。

沿线的东西:

service "my_service" do 
action :nothing
end

template "/staging/conf1" do
[... usual attributes ...]
notifies :stop,"service[my_service]",:immediately
end

template "/staging/conf2" do
[... usual attributes ...]
notifies :stop,"service[my_service]",:immediately
end

remote_file "/opt/my_service/etc/conf1" do
source "/staging/conf1"
notifies :start,"service[my_service]" # delayed here to allow all conf files to be updated.
end

remote_file "/opt/my_service/etc/conf2" do
source "/staging/conf2"
notifies :start,"service[my_service]" # delayed here to allow all conf files to be updated.
end

我个人的喜好是使用相同的资源循环遍历此类选项的文件/模板定义哈希,例如:
node['my_namespace']['conf_files']['conf1'] = "template1"
node['my_namespace']['conf_files']['conf2'] = "template2"

然后循环
node['my_namespace']['conf_files'].each do |cfgfile,tmplname|
template "/staging/#{cfgfile}" do
source tmplname
notifies :stop,"service[my_service]",:immediately
end

remote_file "/opt/my_service/etc/#{cfgfile}" do
source "/staging/#{cfgfile}"
notifies :start,"service[my_service]"
end
end

对于更复杂的用例,您也可以使用散列而不是单个值

如果涉及的资源超过 2 个(在替换实际资源之前执行 conf 文件的特定命令以对其进行验证等),则可能适合定义。

另一种可能是在 load_current_resource 中完成所有暂存工作。的 LWRP,但对于所描述的用例,我可能走得太远了。

关于chef-infra - 使用 Chef,如何在 "resource 1"之前执行 "resource 2",以 "resource 2"执行为条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29125590/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com