Run commands in Opsworks Instances using chef recipe

Using Custom Recipes in Opsworks

MY Recipe

Create the follwoing DIR structure:

myCookbookRepo -> myCustomCookbook -> recipe -> myCustomRecipe.rb

The name “recipe” must not be changed, remaining we can give the names we like.

vim myCustomRecipe.rb

execute 'bundle install' do
cwd '/srv/www/testapp/current'
end

Save it.

ZIP the directory myCookbookRepo.zip and upload to S3 Bucket.

In Opsworks, Click “Stack” , Click “Stack Settings” , Click “Edit

Paste the AWS S3 URL for myCookbookRepo.zip and AK , PK as well.

Now Click “Run Command” and Select “Execute Recipes” from the Command drop down list and mention the following in “Recipes to execute” box

cookbook::recipe (eg. myCustomCookbook::myCustomRecipe.rb)

Click “Execute Recipes

DONE!

Reference:
https://docs.getchef.com/resource_execute.html
http://docs.aws.amazon.com/opsworks/latest/userguide/workingstacks-commands.html

Execute “rake task” in Opsworks

All the Opsworks Instances have GEMS installed in 2 locations
 
  1. System-Wide Location (/usr/local/lib/ruby/gems/2.0.0/gems)
  2. User-Home Location, in Opsworks its Deploy user (/home/deploy/.bundler/galaxylifecms/ruby/2.0.0/gems)

The GEMS listed in Gemfile are installed in the User-Home location by Bundler

If you need to execute a custom ruby script like 

#rake my_custom_script

Chances are high that you would run into GEM dependencies errors even though you had mentioned all the required GEMS in Gemfile. 

To verify if the GEM in error have been installed by bundler or not, 

# grep gem_name Gemfile.lock

IF it exist , then the issue is the custom ruby script is pickingup up the wrong environment ie System-Wide location and not User-Home location. 

Solution :

#bundle exec rake my_custom_script

The “bundle exec” will ensure the custom rake task picks up the GEM used by the Bundler environment.