【问题标题】:How to susbstitute variable attribute value in CHEF如何在 CHEF 中替换变量属性值
【发布时间】:2023-04-30 09:07:01
【问题描述】:

用例,

我们正在尝试使用存储在脚本目录中的脚本自动创建目录,并且一旦将脚本复制到节点的 /tmp 目录,配方调用就是脚本。

attributereplacement/
├── Berksfile
├── LICENSE
├── README.md
├── attributes
    └── default.rb
├── chefignore
├── files
│   └── default
      └── unix.sh
├── metadata.rb
├── recipes

└── default.rb
├── spec
│       ├── spec_helper.rb
│       └── unit
│           └── recipes
│               └── default_spec.rb
└── test
└── integration
    └── default
        └── default_test.rb

in the Unix.sh under files directory we have the following

mkdir /tmp/'#{default['main']['a2']}' mkdir '/tmp/'#{default['main']['a2']}' "mkdir /tmp/'#{default['main']['a2']} '"`

在Attribute目录下我们有以下 node.default['main']['a2'] = "MY_DIR"

在食谱下,我们有以下内容:

cookbook_file '/tmp/unix.sh' do        
  source 'unix.sh'
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

execute 'script' do
  command './tmp/unix.sh'
end

cookbook 完成了执行,但它没有创建一个名为“MY_DIR”的目录,而是创建了一个名为 --> #{default['main']['a2']}

是否可以将属性值传递给脚本,或者是否有其他方法可以解决此问题。

注意:我知道我们可以使用 CHEF 资源创建一个文件/目录,但我对通过脚本执行此操作更感兴趣,因为我们有另一个用例要实现,这类似于将属性值传递给实际上将从 attributes.rb 文件中定义的属性值中提取

【问题讨论】:

    标签: chef-infra chef-recipe cookbook


    【解决方案1】:

    使用模板资源而不是 cookbook_file

    template '/tmp/unix.sh' do
      source 'unix.sh.erb'
      variables (dir: node['main']['a2'] )
      owner 'root'
      ‎group 'root'
      ‎mode '0755' 
    end
    

    在cookbook根目录中的templates/default中创建模板unix.sh.erb,内容如下

    mkdir /tmp/<%= dir %>

    【讨论】: