简体   繁体   English

AWS OpsWorks中的Chef“模板”资源:测试目标文件是否存在

[英]Chef “template” resource in AWS OpsWorks: test that target file exists

I have a following problem. 我有以下问题。 The chef recipe code snippets below does not behave equally although they look the same to me in terms of pure logic. 以下厨师食谱代码段的行为不尽相同,尽管就纯逻辑而言,它们在我看来是相同的。

template "Create a file if not exists" do
  path "#{site_docroot}/somefile.php"
  source 'somefile.php.erb'
  action :create_if_missing
end

VS. VS。

if !File.exists? "#{site_docroot}/somefile.php"
    template "Create a file if not exists" do
      path "#{site_docroot}/somefile.php"
      source 'somefile.php.erb'
      action :create
    end
end

Both should create a file if it does not yet exist. 两者都应创建一个文件(如果尚不存在)。 But in context of a custom recipe in Amazon OpsWorks "setup" stage, the first sollution works as expected. 但是在Amazon OpsWorks“设置”阶段的自定义配方的情况下,第一种解决方案可以按预期工作。 But the second sollution delivers a "false positive" exactly every second time I run the recipe. 但是第二种解决方案恰好每运行我第二遍配方就会产生一次“误报”。 The "if" statement delivers false but the file does not exist at the end. “ if”语句传递false,但文件末尾不存在。

So I would like to know if there is any reason for that in chef or/and ruby with nesting "template" resource inside "if" block. 因此,我想知道在厨师或/和红宝石中是否有任何理由在“ if”块内嵌套“模板”资源。 Does "template" ressource run some kind of asynchronous? “模板”资源是否运行某种异步?

the short answer is that chef actually runs in 2 phases. 简短的答案是厨师实际上分两个阶段运行。 You have a compile phase and an execution (or sometimes called convergence) phase. 您有一个编译阶段和一个执行(或有时称为收敛)阶段。
What this means is depending on the presence of the file the template will get inserted or not in the recipe at compile time. 这意味着什么取决于模板的存在,即模板在编译时是否会插入到配方中。

Further reading: 进一步阅读:
https://docs.chef.io/chef_client.html https://docs.chef.io/chef_client.html
https://serverfault.com/questions/604719/chef-recipe-order-of-execution-redux https://serverfault.com/questions/604719/chef-recipe-order-of-execution-redux

So what happens in your case: 那么在您的情况下会发生什么:

  • first there is not file. 首先没有文件。 The chef recipe (via compile phase) decides there should be a file and creates the file in the converge phase. 厨师配方(通过编译阶段)决定应该有一个文件,并在融合阶段创建该文件。
  • on the 2nd run, there is a file and the chef recipe decides (via compile again) that there should not be a file (ie missing template). 在第二次运行中,有一个文件,厨师配方决定(通过再次编译)不应有一个文件(即缺少模板)。 When the node converges in the 2nd phase chef removes the file as it's trying to bring the node to the desired state. 当节点在第二阶段收敛时,chef会在尝试将节点置于所需状态时将其删除。

That explains the flipping back and forth that you a see (every other run) 这就解释了您来回翻转(每次其他运行)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM