Is there a way to abort a chef-client run if a particular condition is not met? [closed]

StackOverflow https://stackoverflow.com/questions/9233656

  •  28-04-2021
  •  | 
  •  

Question

Consider a simple app server / database server setup. You want to set some value on the app server that tells it where the database server is, and you want to set some permissions on the database server to only allow connections from the app server.

search(:node, "role:db-server")

and

search(:node, "role:app-server")

can work from either machine's recipe run to get you the information you need. But what if the one server doesn't exist at the time you do the search? Is there a way to say "don't continue this run" and mark it as not completed, so that the next time chef-client is run on that machine, it will try again?

Alternatively, is there some nifty chef-fu that I'm missing that serves this use case ("notifies" and "subscribes" seem like they'd almost be what I want, except as far as I can tell, they're only concerned with stuff happening within a node) better? The other thing I'm considering is trying to set up a sleep/check loop to effectively pause one execution run while the other server gets to where it needs to be, but that solution seems rather inelegant and prone to deadlock issues with more complex setups.

Was it helpful?

Solution

Figured it out. I'm sure this could be made a little more elegant, but here are the basics. Considering you have a file /etc/test.txt that has to be populated with some information from your db server once it has come up and registered itself with chef, you'd do something like the following for your app-server node's recipe:

ruby_block "edit test.txt" do
    block do
        db_server = search(:node, %Q{role:db-server})
        rc = Chef::Util::FileEdit.new("/etc/test.txt")
        rc.search_file_replace_line(/^replace_this/, "db_server: #{db_server[0][:hostname]}")
        rc.write_file
    end
    action :create
    ignore_failure true
end

The key part is "ignore_failure true". This causes the recipe to re-run every time you restart chef-client on that server. I haven't figured out how to get it to stop running once it's successful, but even if that turns out to not be possible, with proper checking, you could avoid re-modifying a file that should not be re-modified if that's a problem. Note that db_server[0] will cause the recipe to fail if there's no db server found (I believe this could be made a little more explicit by adding it in a not_if section and checking the length of the search results).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top