Monday, August 7, 2017

Developing recipes with local mode

If running your own Chef server seems like overkill and your not comfortable with using the hosted Chef,you can use local mode to execute cookbooks.

1. Create a cookbook named my_cookbook by running the following command:
local@workstation:~/chef-repo $ chef generate cookbook cookbooks/my_cookbook
Compliling Cookbooks....
Recipe: code_generator::cookbook
...TRUNCATED OUTPUT....

2.  Edit the default recipe of my_cookbook so that it creates a temporary file:
 local@workstation:~/chef-repo $ subl cookbooks/my_cookbook/recipes/default.rb
file "/tmp/local_mode.txt" do
content "created by chef client local mode"
action :create
end

How to do it?


run my_cookbook  on your local workstation using Chef client's local mode:

 local@workstation:~/chef-repo $ chef-client --local-mode -o my_cookbook
 one version per cookbook
 INFO: Forking chef instance to converge
Starting Chef client,version 12.14.89
INFO:***chef 12.14.89***
....TRUNCATED OUTPUT.....
Chef Client finished, 1/1 resources updated in 04 seconds


 2) Validate that the Chef client run creates the desired temporary file on your local workstation:

  local@workstation:~/chef-repo $ cat /tmp/local_mode.txt
  Created by chef client local mode


How it works?

The  --local-mode  (short form: -z) parameter switches the Chef client into local mode. Local mode uses chef-zero -a simple,in-memory version of the Chef server provided  by Chef DK -- when converging the local workstation.

By  providing the -o parameter,you override the run list of your local node so that the Chef  client executes the default recipe from my_cookbook.

There's more .....

Chef-zero saves all modifications made by your recipes to the local filesystem.It creates  a JSON  file containing all node attributes fro your local  workstation in the nodes directory.

This way,the next time you run the Chef client in local node,it will be aware of any changes  your recipes made to the node.

Running knife in local mode


You can use knife in local mode, too. To set the run_list of a node named local_workstation ( instead of having to override it with -o),you can run the following command:


  local@workstation:~/chef-repo $  knife node run_list add -z local@workstation 'recipe[my_cookbook]'

Moving to hosted Chef or your  own Chef server 

When your done editing and testing your cookbooks on your local workstation with chef-zero,you can seamlessly upload them to hosted Chef or your own Chef server:

Note:Make sure you bump the version number of modified cookbooks in their metadata.rb file and commit them to your version control system before uploading to the Chef server.




local@workstation:~/chef-repo $  berks upload 
Uploaded ....


















 





No comments:

Post a Comment