[英]Chef - Pass value from one resource to other resource
这是我的主厨 ruby 代码的一段,我试图将一个值从一个块传递到另一个块。 我们有多个端口在服务器上运行,下面的代码将检查端口,如果它没有运行,它将尝试执行第二个块。 我附上了代码和错误。 请帮助我哪里出错了。
ports.each do |port|
bash "Check_port_running_#{port}" do
code <<-EOH
pidval=$(ps -ef | grep /opt/redis/src/redis-server | grep *:#{port} | grep -vc grep)
if (($pidval == 0));then
portval_#{port}=true
else
portval_#{port}=false
fi
EOH
end
bash "Starting_redis_after_crash_for_port - #{port}" do
only_if { "portval_#{port}" }
code <<-EOH
rm -f #{port}.pid
sudo service redis@#{port} start
EOH
end
end
错误:低于错误
================================================================================
Error executing action `run` on resource 'bash[Starting_redis_after_crash_for_port - 54321]'
================================================================================
Errno::ENOENT
-------------
No such file or directory - portval_54321
Resource Declaration:
---------------------
# In /tmp/kitchen/cache/cookbooks/csg_orderservices_redis/recipes/configure.rb
184: bash "Starting_redis_after_crash_for_port - #{port}" do
185: only_if "portval_#{port}"
186: code <<-EOH
187: rm -f #{port}.pid
188: sudo service redis@#{port} start
189: EOH
190: end
191: end
Compiled Resource:
------------------
# Declared in /tmp/kitchen/cache/cookbooks/csg_orderservices_redis/recipes/configure.rb:184:in `block in from_file'
bash("Starting_redis_after_crash_for_port - 54321") do
action [:run]
default_guard_interpreter :default
backup 5
interpreter "bash"
declared_type :bash
cookbook_name "csg_orderservices_redis"
recipe_name "configure"
code " rm -f 54321.pid\n sudo service redis@54321 start\n"
domain nil
user nil
only_if "portval_54321"
end
我的意见是避免为此使用 bash 资源。 这是为了确保您的 Chef 配方是幂等的,并且可以简化您的代码,因为大多数繁重的工作都由 Chef 客户端完成。 我只使用 bash、powershell 等资源作为最后的手段。
例如,如果 PID 不存在,我的建议是如何重新启动 redis 服务:
在说明书中的库文件夹中创建一个名为 redis.rb 的库文件。 我更喜欢命名我的库来帮助组织我的方法。 这个redis_active?
方法可以在包含此模块的食谱中的任何地方使用。
图书馆/redis.rb:
# Replace CookbookName with actual cookbook name
module CookbookName
module Redis
include Chef::Mixin::ShellOut
def redis_active?(port)
cmd = "ps -ef | grep /opt/redis/src/redis-server | grep *:#{port} | grep -vc grep"
pid_exists = shell_out(cmd).stdout.strip.to_i
return true if pid_exists > 0
end
end
end
在你的 redis 配方中, file
资源只会在redis_active?
方法为指定端口返回false,然后file
资源将收敛并删除pid文件。 当这个资源收敛时,会通知service
资源立即重启redis server服务。
食谱/redis.rb:
# Replace CookbookName with actual cookbook name
Chef::Resource::File.send(:include, CookbookName::Redis)
ports.each do |port|
file "/path/to/#{port}.pid" do
action :delete
not_if { redis_active?(port) }
notifies :restart, "service[redis@#{port}]", :immediately
end
service "redis@#{port}" do
action :nothing
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.