Search code examples
chef-infracookbook

Chef: run two recipes with different users in same cookbook


I have a Chef cookbook that needs to call two recipes: one as root, that will create a new user and add it to /etc/sudoers, and another recipe which is supposed to run using the newly created user.

I understand I can easily execute commands as a certain user using the bash resource, but in this case I need to call include_recipe in both cases (root and new user).

Any ideas?


Solution

  • Chef-client runs as rootuser and you cannot simply run a recipe as another user.

    It is completely legitimate to create a user and then do couple of things in the name of this user, e.g:

    user "foo"
    
    directory "/usr/local/foo" do
      owner "foo"
    end
    
    execute "install foo" do
      command "whatever-foo"
      user "foo"
    end
    

    However, if you have a recipe that you really want to include two times and that should really do the exact same things, just for different users (e.g. in their home directory), then forget the idea that recipes are everything. Use a custom resource that has a user property.

    Then, you can call this resource two times, once for every user:

    %w{root otheruser}.each do |u|
      mycookbook_myresource "do-it-for-user-#{u}" do
        user u
      end
    end