Artur Cichosz
Artur Cichosz

Reputation: 1054

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?

Upvotes: 0

Views: 261

Answers (1)

Mircea
Mircea

Reputation: 10566

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 (i.e. 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)

Upvotes: 1

Related Questions