简体   繁体   中英

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.

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. 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.

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. 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://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.

That explains the flipping back and forth that you a see (every other run)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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