【问题标题】:Chef conditional resource argumentChef 条件资源参数
【发布时间】:2015-07-07 12:13:23
【问题描述】:

我正在通过 Chef 创建一个用户。他的属性存储在数据包中:

{
    "id": "developer",
    "home": "/home/developer",
    "shell": "/bin/zsh",
    "password": "s3cr3t"
}

配方是:

developer = data_bag_item('users', 'developer')

user developer['id'] do
  action :create

  supports :manage_home => true
  home developer['home']
  comment developer['comment']
  shell developer['shell']
  password developer['password']
end

问题是如果节点上没有安装zsh,我就不能以developer 登录。所以,我想有条件地为user 资源应用参数,例如:

user developer['id'] do
  action :create

  supports :manage_home => true
  home developer['home']
  comment developer['comment']
  if installed?(developer['shell'])
    shell developer['shell']
  end
  password developer['password']
end

我怎样才能做到这一点?

【问题讨论】:

  • 安装 zsh 与包资源不是一个选项吗?
  • @Tensibai,好吧,实际上我使用那本食谱安装了zsh。我只是不想过分依赖它。
  • 在这种情况下,@mudasobwa 的答案是正确的(如果答案包括关于 ruby​​ 代码如何为未来读者工作的小解释,我会投赞成票)
  • @MarkO'Connor,我不是 Ruby / Chef 方面的专家,但看起来像 opscode/users has the same problem:如果指定的 shell 不存在,则用户已“损坏”。
  • @Tensibai,我刚刚对其进行了测试,如果您在一次厨师运行期间运行zsh 配方和我的问题中的配方,它实际上不起作用。 Looks like in this case File.exist? developer['shell'] evaluates to false,然后安装zsh,然后运行我的配方。我正在尝试解决这个问题,并将评论@mudasobwa 的答案。

标签: ruby chef-infra chef-recipe


【解决方案1】:

为了补充@mudasobwa 的回答,以正确的方式在厨师中执行此操作并避免丢失外壳,如果它是由另一个配方或同一配方中的包资源安装的,您必须使用lazy attribute evaluation

为那些对如何以及为什么感兴趣的人准备的长版:

这是 chef 工作方式的副作用,第一次编译资源以构建集合,在此阶段,如果评估,配方中的任何 ruby​​ 代码(在 ruby​​_block 资源之外)。一旦完成,资源收集就会收敛(将所需状态与实际状态进行比较并完成相关操作)。

以下食谱可以:

package "zsh" do
  action :install
end

user "myuser" do
  action :create
  shell lazy { File.exists? "/bin/zsh" ? "/bin/zsh" : "/bin/bash" }
end

这里发生的情况是 shell 属性值的评估延迟到收敛阶段,我们必须使用 if-then-else 构造(这里使用三元运算符,因为我觉得它更易读)回退到shell 我们确定会出现(我使用了/bin/bash,但故障安全值将是/bin/sh)或者shell 属性将为nil,这是不允许的。

通过这种延迟评估,“/bin/zsh”是否存在的测试是在安装包并且文件应该存在之后完成的。如果包内出现问题,用户资源仍将创建用户,但使用“/bin/bash”

【讨论】:

    【解决方案2】:

    实现您想要的最简单的方法是显式检查外壳是否存在:

    shell developer['shell'] if File.exist? developer['shell']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      相关资源
      最近更新 更多