Chef Ruby块中添加日志:customerId未定义时输出严重错误
在Chef Ruby块中添加
customerId未定义的严重错误日志 嘿,这事儿不难搞定!我们只需要在你的Ruby块开头加上属性检查逻辑,用Chef自带的日志模块输出严重级别错误,甚至可以直接让Chef运行终止,避免后续做无用功。
具体操作思路和修改后的代码如下:
核心逻辑说明
- 在API请求逻辑执行前,先检查
customerId是否未定义或为空 - 用
Chef::Log.fatal()输出严重级别错误日志,这个级别会在Chef运行日志里醒目显示 - 同时抛出异常终止Chef流程,因为
customerId缺失属于必须修复的前置问题,没必要继续执行后续操作
修改后的完整代码
ruby_block 'Run Curl API' do block do require 'net/http' require 'uri' require 'json' # 新增:检查customerId属性是否存在且有效 if customerId.nil? || customerId.empty? Chef::Log.fatal("customerId 属性未定义或未提供,无法执行API请求!") raise "Missing required attribute: customerId" # 抛出异常终止Chef运行 end uri = URI.parse("http://#{server}") request = Net::HTTP::Post.new(uri) request.content_type = "application/json" request.body = JSON.dump({ "customerId" => "#{customerId}", "cloudName" => "#{cloudName}", "vpcId" => "#{vpcId}", }) req_options = { use_ssl: uri.scheme == "https", } response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http| http.request(request) end # 可选:如果需要,也可以添加响应日志 # Chef::Log.info("API请求响应状态码: #{response.code}") # Chef::Log.debug("API响应内容: #{response.body}") end action :run end
额外提示
如果还需要检查cloudName、vpcId这类其他必填属性,可以照搬这个检查逻辑,把变量名替换一下就行,保持代码风格统一。
内容的提问来源于stack exchange,提问作者anish anil
相关产品推荐
相关产品推荐

