You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在chef-client运行命令时传递属性值?附代码示例

在Chef-Client运行时传递属性值的方法

先给你指出当前Recipe里的几个小问题,避免影响后续效果:

  • 第二个execute 'just_test1'的命令语法错误,你写的#{/tmp/node['main']['a2']}完全不对,应该是把属性值作为文件名的一部分,改成/tmp/#{node['main']['a2']}才对
  • 第三个execute 'just_test2'的命令只是在控制台输出内容,如果要保存到文件,需要加上重定向,比如echo '#{node['main']['a2']}' > /tmp/a2_output.txt

接下来给你说几种在运行chef-client时传递属性值的常用方法,这些方法都会覆盖你在属性文件里定义的node.default['main']['a2'] = "hello world"默认值:

方法一:用--set-attribute直接在命令行传递

Chef 12及以上版本支持直接通过命令行参数覆盖属性,运行命令时这样写:

chef-client --set-attribute 'main.a2="my custom runtime value"'

或者用JSON格式传递:

chef-client --set-attribute '{"main": {"a2": "my custom runtime value"}}'

方法二:用-j参数传递JSON属性文件

如果需要传递多个属性,推荐用JSON文件的方式:

  1. 创建一个JSON文件,比如override_attrs.json,内容如下:
{
  "main": {
    "a2": "from json file"
  }
}
  1. 运行chef-client时指定这个文件:
chef-client -j override_attrs.json

方法三:通过环境变量传递(需要Recipe配合)

如果你想用环境变量来传递,可以先修改Recipe,让属性优先读取环境变量的值:

# Recipe:: default
# Copyright (c) 2018 The Authors, All Rights Reserved.

# 优先读取环境变量MAIN_A2,不存在则用默认值"hello world"
node.default['main']['a2'] = ENV['MAIN_A2'] || "hello world"

execute 'just_test' do
  command 'touch /tmp/a2345'
end

execute 'just_test1' do
  command "touch /tmp/#{node['main']['a2']}"
end

execute 'just_test2' do
  command "echo '#{node['main']['a2']}' > /tmp/a2_output.txt"
end

然后运行chef-client前设置环境变量:

export MAIN_A2="from environment variable"
chef-client

修正后的完整Recipe示例

上面的代码已经是修正后的版本了,它会根据你运行时传递的属性值来执行对应的命令,比如如果用--set-attribute传递main.a2="test_value",那么just_test1会创建/tmp/test_value文件,just_test2会把test_value写入/tmp/a2_output.txt。

内容的提问来源于stack exchange,提问作者anish anil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:15:01