Sunday, 30 October 2011

Pulling a file out a bag

I have been playing with Chef recently in order to replace the hand-crafted automatic deployment system that we've created over the last few years. There are plenty of cookbooks, recipes and examples available on the Internet but I wasn't able to find a recipe that would build a multi-line file from the contents of a data bag. So using a little bit of Ruby I was able to build an array of strings in memory before writing the whole thing out to a file.

Here's my example which builds the /root/.ssh/authorized_keys file from a data bag within Chef:
key_list = Array.new
ssh_users = data_bag("ssh-authorized_keys")
ssh_users.each do |id|
    ssh_user = data_bag_item("ssh-authorized_keys", id)
    key_list.push(ssh_user["key"])
end

file "/root/.ssh/authorized_keys" do
    content key_list.join("\n")
end

1 comment:

  1. Thanks a lot for that Scott! I didn't quite use what you had, but your script definitely helped my initiative. In a nutshell, your block of code taught me a lot!

    ReplyDelete