Chef在首次运行其他bash块之后运行bash块

时间:2018-05-28 22:23:06

标签: ruby bash chef chef-recipe

我正在使用厨师来做这件事:

我试图在前一个运行之后运行bash块,简单,我使用notify。我还希望在初始运行和第二次运行时检查锁定文件(是否有更好的方法确保它只在前一个bash块运行时运行?)。

这是我目前的厨师代码:

if not File.exist? tsm_login_lock
  bash 'login_tsm' do
    user tableau_user
    cwd tableau_user_home
    code <<-EOH
      source /etc/profile.d/tableau_server.sh
      tsm login -u #{tableau_user} -p #{password}
      tsm settings import -f  /home/analytics/setting_file.json
      tsm pending-changes apply
      tsm licenses activate -k #{key}
      tsm register --file #{registration}
      tsm pending-changes apply
    EOH
    notifies :run, "bash[tsm_init]", :immediately
  end
 file tsm_login_lock do
   mode '0644'
   content 'tableau server stareted'
 end
end

if not File.exist? tsm_init_lock
  bash 'tsm_init' do
    user tableau_user
    cwd tableau_user_home
    code <<-EOH
      tsm initialize --start-server --request-timeout 1800
    EOH
    notifies :run, "bash[tsm_2]", :immediately
  end
  file tsm_init_lock do
    mode '0644'
    content 'tableau server initialized'
  end
end

1 个答案:

答案 0 :(得分:1)

你想在这里结合几种方法:

  • 您希望确保通知的资源不是自行运行。因此,他们的行动应该设置为:nothing。这样他们就不会自己运行,然后被通知有条件地再次运行。您在subscribe中定义的操作是通知时将采取的操作。
  • 您还希望确保仅在锁定文件实际运行时才创建锁定文件。因此,它们也应设置为空,并通过:create操作通知。
  • 使用Chef Guards检查是否存在锁定文件。这样你仍然可以看到资源被跳过的特定输出(由于保护),而不是一起忽略。

使用您的代码的示例:

使用not_if防护,因此如果存在tsm_login_lock变量定义的文件,则资源将不会运行。另外通知要创建的锁文件。

bash 'login_tsm' do
  user tableau_user
  cwd tableau_user_home
  code <<-EOH
    source /etc/profile.d/tableau_server.sh
    tsm login -u #{tableau_user} -p #{password}
    tsm settings import -f  /home/analytics/setting_file.json
    tsm pending-changes apply
    tsm licenses activate -k #{key}
    tsm register --file #{registration}
    tsm pending-changes apply
  EOH
  notifies :run, "bash[tsm_init]", :immediately
  notifies :create, "file[#{tsm_login_lock}]", :immediately
  not_if { ::File.exist?(tsm_login_lock) }
end

除非资源锁定

,否则此资源本身不执行任何操作
file tsm_login_lock do
  mode '0644'
  content 'tableau server stareted'
  action :nothing
end

同样,此资源应该具有init_if保护,用于init锁定文件。此外,它应该具有默认操作,因为它从登录资源接收通知。最后,通知它要创建的锁文件。

bash 'tsm_init' do
  user tableau_user
  cwd tableau_user_home
  code <<-EOH
    tsm initialize --start-server --request-timeout 1800
  EOH
  action :nothing
  not_if { ::File.exist?(tsm_init_lock) }
  notifies :run, "bash[tsm_2]", :immediately
  notifies :create, "file[#{tsm_init_lock}]", :immediately
end

让这个init锁文件资源自己做什么都不做,只应该由它锁定的资源通知

file tsm_init_lock do
  mode '0644'
  content 'tableau server initialized'
  action :nothing
end

最后,我强烈建议您找出您认为成功登录Tableau和init的内容。如果您登录到服务器,请问自己如何检查这些内容。将这些验证用于防护而不是锁定文件。一般而言,您希望在需要时使用警卫来确保资源是幂等的。查看上面关于警卫的链接,了解警卫的工作方式。