我正在尝试使用服务器角色将数据添加到模板中。我尝试了几种方法,但似乎无法使其正常工作。
这是角色代码块。
ruby_block 'get_main_role_attr' do
block do
require 'mixlib/shellout'
rolecmd = Mixlib::ShellOut.new("cat /var/chef/role | cut -d',' -f 1 | cut -c2-")
rolecmd.run_command
rolecmd.error!
node.normal['mainrole'] = rolecmd.stdout
end
end
template "/etc/ssh/sshd_config" do
source "ssh/sshd_config.erb"
owner "root"
group "root"
mode "0600"
action :create
variables(
:allowed_users_team1 => "AllowUsers user1 user2 user3",
) if node['mainrole'] == "role1"
notifies :restart, "service[sshd]", :immediately
variables(
:allowed_users_team2 => "AllowUsers user4 user5 user6",
) if node['mainrole'] == "role2" || node['mainrole'] == "role3" || node['mainrole'] == "role4"
notifies :restart, "service[sshd]", :immediately
end
方法1
variables(
:allowed_users => "AllowUsers user1 user2",
) if node['mainrole'] == "role1" || node['mainrole'] == "role2" || node['mainrole'] == "role3"
notifies :restart, "service[sshd]", :immediately
方法2
variables(
:allowed_users => "AllowUsers user1 user2",
) if node['mainrole'] == "role1" || "role2" || "role3"
notifies :restart, "service[sshd]", :immediately
方法3
variables(
:allowed_users_bidder => "AllowUsers user1 user2",
) if node['roles'].any? {|r| %w{role1 role2 role3}.include?(r)}
notifies :restart, "service[sshd]", :immediately
请让我知道我错了。。谢谢您的帮助
Thx
答案 0 :(得分:1)
Chef客户端运行分为两个部分:编译和收敛。在第一阶段,Chef创建应在节点上应用的资源集合,在第二阶段,Chef将应用更改。进一步了解on the Chef docs
您正在以收敛状态分配node.normal['mainrole']
,但在此之前的编译阶段检查了值(node['mainrole'] == "role1"
)。
您需要将分配移动到编译状态或将检查移动到收敛状态。
如何将支票转换为收敛状态的示例之一是使用not_if
或only_if
。在这种情况下,您将需要2个模板资源:
template "/etc/ssh/sshd_config for 1,2,3" do
path "/etc/ssh/sshd_config"
source "ssh/sshd_config.erb"
owner "root"
group "root"
mode "0600"
action :create
variables(:allowed_users_team1 => "AllowUsers user1 user2 user3")
only_if { node['mainrole'] == "role1" }
notifies :restart, "service[sshd]", :immediately
end
template "/etc/ssh/sshd_config for 4,5,6" do
path "/etc/ssh/sshd_config"
source "ssh/sshd_config.erb"
owner "root"
group "root"
mode "0600"
action :create
variables(:allowed_users_team2 => "AllowUsers user4 user5 user6")
only_if { %w[role2 role3 role4].include? node['mainrole'] }
notifies :restart, "service[sshd]", :immediately
end
另一种方法是在模板本身内部移动逻辑并传递2个不同的变量:
variables(:allowed_users_team2 => "AllowUsers user4 user5 user6",
:allowed_users_team1 => "AllowUsers user1 user2 user3",
:mainrole => node['mainrole'])