Saturday, October 21, 2017

How to create users using the chef cookbook?


Manual process:
useradd Sai  (To create the new user)
id sai (This is to verify,whether the user has created or not).
(uid=1002(sai) gid=1002(sai) groups=1002(sai))


Chef process using Recipe in the users cookbook:

user 'kevin' do
  comment 'default user'
  home '/home/kevin'
  shell '/bin/bash'
  password 'kevin'
end

This should be mentioned in the Chef - Recipe (default.rb).


How to write a test condition for the users cookbook?

describe user('Sai') do
it { should exist }
its('uid') { should eq 1001 }
its('shell') { should eq '/bin/bash' }
end

where we need to place this piece of code?

users (cookbook) >   test (directory) >  smoke  (directory) >   default  (directory) > default_test.rb

What is the necessity of test condition (Inspec test)?(the test condition will checkin for every 30mins on to the node,to know the status of the node and make sure whether it is satisfying the test condition or not).

whenever anything is not working properly/it is overrided / it is been removed/deleted,the test condition will fail,whenever there is a failure of test condition automatically the Chef-recipe is again applied on to the nodes and fulfill the requirement of the users cookbook.

Chef Infrastructure


Chef Infrastructure

A cookbook is a collection of all components  needed to change something on  a server.Things such as installing MySql or configuring  SSH can be done by cookbooks.The most important part of the cookbook is recipes, which tell chef which resources  you want to configure on your host.

You need to deploy cookbooks to the nodes that you want to change,Chef offers multiple methods for this task.Most probably ,you will use a central  Chef server.You  can either run your  own server  or signup for hosted chef.

The Chef server is the central registry ,where each node  needs to be registered .The chef server distributes the cookbooks you uploaded to it, to your nodes.

Knife is Chef's command line tool to interact with the chef server.You run it on your local workstation and use it to upload the cookbooks  and manage other aspects of chef.

On your nodes, you need to install chef client - the program that runs on your nodes, retrieving cookbooks from the chef server  and executing them on the node.

Using Version control system

A  version control system  is a fundamental part of any infrastructure automation.there are multiple solutions to manage source version control.

1)You will need Git installed on your local workstation.use your operating system's package manager (such as Apt on Ubuntu or Homebrew  on OS X ,or simply  download the  installer  from www.git-scm.org)


Installing the Chef  Development kit on your workstation

If you want to use Chef,you will need to  install  the Chef  Development kit (DK) on your local workstation first.You  will have  to develop  your configuration  locally and use Chef  to distribute them to your chef server.

Chef provides  a fully  packaged version, which does not have any external prerequisites.This fully packaged chef is called the omnibus installer.

How to do it?

To install the Chef Development kit:

1) Visit this page: https://downloads.chef.io/chefdk/.  The Chef Development kit supports macOS,Red Hat Enterprise linux, Ubuntu  and Microsoft Windows.

2) Select a platform  and then a package. (Chef-docs uses the MacOS setup within the documentation .)

3) Click the download button

4) Follow the steps in the installer and install the chef  development kit on your machine.The chef development kit is installed to /opt/chefdk / on your unix/linux system.

5) When finished, open a command window  and enter the following:

      $ chef verify


Using the Hosted chef platform


if  you want to get started  with Chef right away  (with out the need to install your own chef server) or  want  a third party  to give  you a Service level agreement  (SLA)  for your chef server, you can signup  for hosted chef  by Chef Software , Inc . Chef Software , Inc . operates  Chef as a cloud service .It's quick to setup  and gives  you full control ,using users and groups  to control access permissions to your Chef setup. We will configure knife, chef's command line to interact with the hosted chef,so that you can start managing your nodes.

Before being able to use  hosted chef, you need to sign up for the service.There is  a free account for up to five nodes:

Visit  http://manage.chef.io/signup  and registering for  a free account.

How to do it?

Download Chef-starter kit  from hosted chef  or carry out the following steps  to interact with the hosted chef

1.Create the configuration directory for your Chef client on your local workstation:

local@workstation:- $  cd  ~/chef-repo
mkdir .chef


2. Generate the knife config and put the downloaded knife.rb  into .chef directory  inside your chef-repo  directory.

Make sure  you have your  user's private key  saved as  .chef/< YOUR USERNAME>.pem ,If needed you can reset  it at  https://id.chef.io/id/profile and short name you chose for your organization  in your knife.rb file:
(osr is the organization name).
current_dir = File.dirname(_FILE_)
log_level:info
log_location    STD_OUT
node_name      "kau_osr"
client_key        "#{current_dir}/kau_osr.pem"
chef_server_url  "https://api.chef.io/organsations/osr "
cache_type          'BasicFile'
cache_options(  :path= >  "#{ENV['HOME']}/.chef/checksum"  )
cookbook_path    ["#current _dir}/../cookbooks"]NOTE



Note:

    You should add the following code to your .gitignore file inside chef-repo  to avoid your credentials ending up in your repository.


 .chef/*.pem


3.  Use knife to verify that you can connect to your hosted chef  organization .It should have any clients ,so far :



local@workstation:- $  knife client list 


How it works?

The following line of code in your knife.rb file  tells knife  where to find  your users private key .

It is used to authenticate you with the chef-server :

Client_key         "#{current_dir}/kau_osr.pem"


Also,the following line of code in your knife.rb file tells knife that you are using the hosted chef.

You will find your  organization name as the last part of the url:

chef_server_url   "https://api.chef.io/organsations/osr"




Using the knife.rb file  and your user's key ,you can now connect  to your organization hosted by chef software inc.


There's more

  This setup is good for you, if you dont want to worry about running, scaling and updating your own chef server  and if your happy with saving all your configuration data in the cloud  and under the control of chef software  inc .

Note

If you need to have all your configuration data in your own network boundaries, you can install Chef server onpremises  by choosing  ON PREMISES CHEF  at https://www.chef.io/chef/chooseyourversion/ or install  the Open source version of chef server directly from Github  at https://github.com/chef/chef .

Inspecting files on your Chef Server with knife


 Knife is the command-line interface for the chef server,It uses the Restful API  exposed by the chef server to do its work and helps  you to interact  with the chef server.


Sometimes,you may want to peek into files  stored on your chef server.You might not be sure about an implementation detail of the specific cookbook version currently installed on your chef server and need to look it up.Knife can help you out by letting you show  various  aspects of life stored on your Chef server.


Install the iptables community cookbook by executing the following command


local@workstation:~ $ knife cookbook site install iptables

Installing iptables to /Users/mma/work/chef-repo/cookbooks

When you execute the command, we get the error.

ERROR: IOError cannot open or read  ..../chef-repo/cookbooks/iptables/metadata.rb !

Note:If you get the preceding error, your cookbook only has a metadata.json file.Make sure that you delete it and create  a valid metadata.rb, file instead.

Upload the iptables cookbook on your chef server by executing the following command:

local@workstation:~ $   knife cookbook upload iptables  --include-dependencies 
 uploading iptables
 uploading combat_resources
 uploading  2 cookbooks


Lets find out how knife can help you to look in to the cookbook stored in your chef server?


1)  First, you want to find out the current version  of the cookbook  your interested in.In  our case, we are interested  in the iptables cookbook:


local@workstation:~ $   knife cookbook show iptables 
iptables  3.0.0.0.14.1 

2) Then, you can look up the definitions  of the iptables cookbook , using the version number that you found in the previous step.


local@workstation:~ $  knife cookbook show iptables  0.14.1  definitions
                 checksum
                  name
                  path
                  specificity
                  url:    https://s3-external-1.amazonaws.com:443/opscode-platform



3)  Now,you can even  show the contents of the iptables_rule.rb  definition file  as stored on the server:

   
local@workstation:~ $  knife cookbook show iptables  0.14.1  definitions  iptables_rule.rb 

# Cookbook_Name::iptables
#  Definition::iptables_rule
#
#
define :iptables_rule,  :enable => true,  :source => nil,  :variables =>  {},  :cookbook => nil do


How it works


The knife cookbook show subcommand helps you what exactly is stored  on the Chef Server.It lets you drill down in to specific sections of your cookbook and see the exact contents of the files stored in your Chef Server.



You can pass patterns  to the knife show command  to tell it exactly what you want to see.
Showing the attributes defined by the cookbook can be done as follows:




local@workstation:~ $  knife show cookbooks/iptables/attributes/*
cookbooks/iptables/attributes/default.rb

#
# Cookbook  Name::iptables
#  Attribute:: default
Truncated  OUTPUT

To  find  some more  examples  on knife show , visit https://docs.chef.io/knife_show.html

Defining Cookbook Dependencies 

Quite often, you might  want to use features  of other cookbooks in your cookbooks. For example, if you want to make sure that all packages  required for compiling software written in  c are installed, you want to include the build essential cookbook, which does just that.
The  Chef Server  needs to know  about such dependencies  in your cookbooks. You declare them in a cookbook's metadata.

Make sure you have a cookbook named  my_cookbook  and the run_list  of your node includes my_cookbook, as described  in the creating and using cookbook.

How to do it


Edit the  metadata  of your cookbook in the file  cookbooks/my_cookbook/metadata.rb  to add a dependency  to the build-essential cookbook:


local@workstation:~/chef-repo $ subl cookbooks/my_cookbook/metadata.rb

...

depends 'build-essential', ' >= 7.0.3'


How it works

If you want to use a feature  of another cookbook inside  your cookbook, you will need to include the other cookbook in your recipe using the include_recipe  directive:

include_recipe 'build-essential'


To  Tell the Chef Server  that your cookbook  requires the  build-essential cookbook, you need to declare that dependency in the metadata.rb file.If you uploaded  all the dependencies  to your chef server either using the  knife cookbook  upload  my_cookbook  --include-dependencies  or berks install  and berks upload, as described  in the Managing  cookbook  dependencies with Berkshelf 
recipe, the chef server will then send all the required cookbooks to the node.

The depends function call tells the Chef Server that your cookbook  depends on a version greater than or equal to 7.0.3  of the build-essential cookbook

You may use  any of these version constraints with depends calls:

<  (less than)
<=  (less than or equal to)
=  (equal to)
>=  (greater than or equal to)
~> (approximate greater that)
>  (greater that)



Note:

If you include another recipe  inside  your recipe,withour declaring the cookbook dependency in your metadata.rb file,   FOODCRITIC will warn you:


local@workstation:~/chef-repo $    foodcritic cookbook/my_cookbook

FC007:  Ensure recipe dependencies  are reflected  in cookbook metadata:
cookbooks/my_cookbook/recipes/default.rb:9

This  is where  Berkshelf  comes into play. It works like Bundler for ruby gems,managing cookbook dependencies for you. Berkshelf downloads all the dependencies you defined  recursively  and helps you to upload all cookbooks to your Chef server.


Instead of polluting your chef repository, it stores all the cookbooks in a central location.You just commit your Berkshelf  dependency file (called  Berksfile)  to your repository  every colleague  or build server can download and install all those dependent cookbooks based on it.

Lets see how to use  Berkshelf  to manage dependencies  of your cookbook.


Make sure you have a cookbook named  my_cookbook  and run_list of your node includes my_cookbook  as described in the  Creating and using cookbook.


How to do it?

Berkshelf helps you to keep those utility cookbooks out of your chef repository.this makes it much easier  to maintain  the important cookbooks.

Lets see how to write a cookbook  by running  a bunch of utility  recipes and manage the required cookbooks with Berkshelf :

1) Edit  your cookbook's metadata 


local@workstation:~/chef-repo  $ subl  cookbooks/my_cookbook/metadata.rb

.....

depends  "chef-client"
depends  "apt"
depends  "ntp"


2) Edit your cookbook's default recipe

local@workstation:~/chef-repo  $   subl  cookbooks/my_cookbook/recipes/default.rb

.....

include_recipe "chef-client"
include_recipe  "apt"
include_recipe  "ntp"


3) Run Berkshelf  to install all the required cookbooks:

    local@workstation:~/chef-repo  $ cd cookbooks/my_cookbook
    local@workstation:~/chef-repo/cookbooks/my_cookbook $ berks install 
    Resolving cookbook dependencies
    Fetching 'my_cookbook'  from source at .
    Fetching cookbook index  from https://supermarket.chef.io
    Installing apt  (4.0.2)

 4)  Upload all the cookbooks on the chef server
       local@workstation:~/chef-repo/cookbooks/my_cookbook $   berks upload 
       Using my_cookbook  (0.1.0)
        Truncated  output

How it works ? 


Berkshelf comes with  the Chef  DK

We edit our cookbook  and tell it use  a few basic cookbooks

Instead of making us manually install all the cookbooks using  knife cookbook site install,Chef  generates  a Berksfile,besides the metadata.rb file.

The Berksfile is simple .It tells Berkshelf to use the Chef supermarket as the default source for all the cookbooks:

source "https://supermarket.chef.io"
  
       
    And the Berksfile tells Berkshelf  to read the metadata.rb file to find all the required cookbooks.This is the simplest way when working inside a single cookbook, please see the below to see more advanced usage of Berksfile.

After telling Berkshelf where to find all the required cookbook names, we use it to install all those cookbooks:

       berks install 




Note:Berkshelf stores cookbooks in  ~/.berkshelf/cookbooks, by default.This keeps your chef repository clutter free (means confusion/disorder state free).Instead of having to manage all the required cookbooks inside your own chef repository,Berkshelf takes care of them.You simply need to check in Berksfile  with your cookbook  and everyone using your cookbook can download all the required cookbooks using Berkshelf.

To make sure the that there's no mixup  with different cookbooks versions when sharing your cookbook,Berkshelf creates a file called Berksfile.lock alongside Berksfile.

Note:

 Don't commit the Berksfile.lock to the version control .If you use berks generate it will automatically populate the .gitignore  for you.Otherwise you need  to add Berksfile.lock  to your  .gitignore  manually.


Here you will find exact versions  of all the cookbooks that Berkshelf installed:

Dependencies 
my_cookbook
path: .
metadata true

GRAPH
apt (4.0.2)
compact_resource (>=12.10)
chef-client (6.0.0)
cron (>=1.7.0)
logrotate (>=1.9.0)
windows (>=1.42.0)
..
..
..

Berkshelf will only use the exact versions specified  in the Berksfile.lock file,if it finds this file.

Finally we use the Berkshelf to upload all the required cookbooks to the Chef server.

berks upload

Berkshelf integrate with the vagrant:


Berkshelf integrates tightly with Vagrant via the vagrant-berkshelf plugin.You can setup the Berkshelf and Vagrant in such a way that Berkshelf  installs and uploads all the required cookbooks on your chef server whenever you execute  vagrantup or vagrant provision.You will save all the work  of running berks  install and berks upload manually before creating you node with the vagrant.

How you can integrate  Berkshelf and vagrant ?


1)local@workstation:~/chef-repo  $  vagrant plugin install vagrant-berkshelf
Installing the  'vagrant-berkshelf'  plugin.This can take a few minutes
Installed the plugin 'vagrant-berkshelf (5.0.0)'!


2)Then you have to say the vagrant to make use of the plugin.You do this by enabling the plugin in Vagrantfile :

local@workstation:~/chef-repo  $ subl (sublime) Vagrantfile
config.berkshelf.enabled = true

3)Then you need a Berksfile in the root directory of your chef repository  to tell Berkshelf  which cookbooks  to install  on each vagrant run:

local@workstation:~/chef-repo  $ sublBerksfile
source 'https://supermarket.chef.io'
cookbook  'my_cookbook',path: 'cookbook/my_cookbook'

4) Eventually you can start your VM using vagrant.Berkshelf  will first download  and then install the cookbooks in the Berkshelf  and upload them to the Chef server.Only after all the cookbooks are made available on the Chef server by Berkshelf will vagrant go on:

local@workstation:~/chef-repo  $  vagrant up 
Bringing machine server  with virtual box provider

==> default:  Updating  Vagrant's Berkshelf...
==> default:   Resolving cookbook dependencies
==> default:   'Fetching  'my_cookbook' from  source at  cookbooks/my_cookbook
==> default:   'Fetching cookbook index  from https://supermarket.chef.io.....

5) This way using Berkshelf  together with  Vagrant  saves a lot of manual steps  and gets faster cycle times for your cookbook development.If your using your manual vagrant setup  instead of Test kitchen 

References:

http://berkshelf.com/
https://github.com/berkshelf/berkshelf
Vagrant Berkshelf  plugin source code  at
https://github.com/berkshelf/vagrant-berkshelf

Using Custom knife plugins


Knife comes with a set of commands  out-of-the box.The built-in commands  deal with the elements of Chef-like cookbooks, roles,databags  and so on.How ever, it would be nice  to use  knife for more than just the basic stuff.
Knife comes with a API plugin and there are already a host of useful knife plugins built by the makers of chef and chef community.

Knife-ec2plugin

There are knife plugins for the most of the cloud providers.

which knife plugins are available to manage the AWS instances.

1) list the knife plugins that is shipped as Ruby gems using the chef command-line tool.

local@workstation:~/chef-repo $ chef gem search -r knife-
***REMOTE GEMS ***
...TRUNCATED OUTPUT
knife-azure  (1.6.0)
...TRUNCATED OUTPUT
knife-ec2   (0.13.0)
...TRUNCATED OUTPUT

2) Install the Ec2 plugin to manage servers in the AWS cloud 

local@workstation:~/chef-repo $ chef gem install knife-ec2
Building native extensions,This could take a while
...TRUNCATED OUTPUT
Fetching knife-ec2 plugins ............

6 gems installed


3) List all the available instance types in AWS using the knife ec2 plugin.Please see your own credentials  instead of XXX and YYYYY.


local@workstation:~/chef-repo $ knife ec2 flavour list  --aws-access-key-id XXX  --aws-secret-key-id YYYYY

id                                name                                    Arch     RAM         Disk  cores
c1.medium           HIGH-CPU-MEDIUM         32-bit      1740.8     350GB      5


How it works?

Knife looks for plugins in various places:

First,it looks in to the .chef directory, which is located inside your current chef repository, to find the plugins specific to this repository.

./.chef/knife/plugins/


Then it looks for the plugins in your .chef directory, which is located in your home directory to find plugins that you want to use chef repositories:


~/.chef/knife/plugins/



Finally,it looks for installed gems.Knife  will load all the code from any /chef/knife/ directory found in your installed ruby gems.This is the most common ways of using the plugins developed by chef and chef community.

Deleting a node from the Chef Server


Every node managed by a Chef server has a corresponding client object on the Chef server.Running the Chef client on your node uses the client object to authenticate itself against the Chef server on each run.

Additionally,to register a client, a node object is created on the Chef server.The node object is the main data structure,which you can use to query node data inside your recipes.

Make sure you have at least one node registered on your Chef server that is safe to remove.

How to do it?

delete the node and client object to completely remove a node from the Chef server.

1)Delete the node object
local@workstation:~/chef-repo $ knife node delete my_node 
Do you really want to delete my_node? (Y/N) y
Dleted node[my_node]

2) Delete the client object:
local@workstation:~/chef-repo $  knife client delete my_node
Do you really want to delete my_node? (Y/N) y
Deleted client[my_node]

 How it works?

To keep your Chef server  clean,it's important to not only manage your node objects but to also take care of your  client objects,as well.

Knife connects to the Chef server and deletes the node object with a given name,using the Chef server  RESTful API.

The same happens while deleting the client object on the Chef server.

After deleting both objects,your node is totally removed from the Chef server.Now you can reuse the same node name with a new box or virtual machine.

Having to issue two commands is a bit tedious and error-prone.To simplify things,you can use a knife plugin called playground .

1)Run the chef command-line tool to install the knife plugin:

local@workstation:~/chef-repo $  chef gem install knife-playground
..TRUNCATED OUTPUT...
Installing knife-playground (0.2.2).

2) Run the knife pgclientnode delete subcommand:

local@workstation:~/chef-repo $  knife pgclientnode delete my_node 

Deleting CLIENT my_node....

Do you really want to delete my_node? (Y/N) y
Delete client[my_node]
Deleted node[my_node]


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 ....

Freezing cookbooks


Uploading broken cookbooks that override your working ones is a major pain and can result in widespread outages throughout your infrastructure.If you have a cookbook version,you tested successfully with Test kitchen,it's a good idea to freeze this version so that no one can overwrite the same version with broken code.When used together with version constraints  that are specified in your environement manifests,freezing cookbooks can keep your production servers safe from accidental changes.

Note : Berkshelf takes care of freezing  cookbooks sutomatically.

Getting ready:

Make sure you have at least one cookbook (I will use the ntp cookbook) registered with your Chef server.

 Lets see what happens if we freeze a cookbook.

1) Upload a cookbook and  freeze it =:

local@workstation:~/chef-repo $ knife cookbook upload ntp --freeze
uploading  ntp   [3.2.0]
Uploaded 1 cookbook.


2)Trying to upload the same  cookbook version again:

local@workstation:~/chef-repo $  knife cookbook upload ntp
Uploading ntp  [3.2.0]
ERROR: Version 3.2.0 of cookbook ntp is frozen. Use --force to override 
Warning: Not updating  version constraints for ntp in the environment as the cookbook is frozen.
ERROR:  Failed to upload 1 cookbook.

3) Change the cookbook version:


local@workstation:~/chef-repo $  subl cookbooks/ntp/metadata.rb
.......
version  "3.2.1"

4) Upload the cookbook again:
local@workstation:~/chef-repo $ knife cookbook upload ntp
Uploading ntp   [3.2.1]
Uploaded  1 cookbook

 How it works?

By  using the --freeze option when uploading a cookbook,you tell the Chef server that it should not accept any changes to the same version of the cookbook anymore.This is important  if your using environment and want to  make sure that your production environment cannot be  broken  by uploading a corrupted cookbook.

By changing the version number of your cookbook,you can upload the new version.Then you can make,for example,your staging environment use that new cookbook version.

There's more....

To support  a more elaborate workflow,you can use the knife-spork  knife plugin,which comes pre-installed  with Chef DK.It helps multiple developers work on the same chef server  and repository  without treading on each other's toes.You can find more information about it at
https://docs.chef.io/plugin_knife_spork.html


 Running the Chef client as a daemon:

While you can run the Chef client on your nodes manually whenever you change something in your Chef repository,it's sometime preferable to have the Chef client run automatically every so often.Letting the Chef client run automatically makes sure that no node misses out any updates.

Getting ready

You need  to have a node registered with your Chef server.It needs to be able to run chef-cleint without any errors.

How to do it?

Lets see how to start the Chef client in daemon mode so that it runs automatically:

1) Start the Chef client in daemon mode,running every 30 minutes:

 osr@server:~$ sudo chef-client -i 1800

2) Validate that the Chef client runs as a daemon:
osr@server:~$ psauxw | grep chef-client




How it works?

The -i parameter will start the Chef client as a daemon.The given number is the seconds between each Chef client run.In the  previous example,we specified 1,800 seconds which results in the Chef client running every  30minutes.

You can use the same command in a service startup script.

 Note:
You can use the chef-client cookbook to install  the Chef client as a service.
See: https://supermarket.chef.io/cookbooks/chef-client for details

There's more....

Instead of running the Chef  client as a daemon.you can use a Cronjob to run it every so often:
osr@server:~ $ subl /etc/cron.d/chef_client
 PATH=/usr/local/bin:/usr/bin:/bin
# m h dommondow user command
*/15 * * * *root chef-client -l warn | grep -v 'retrying[1234]/5 in'

This cronjob will run the Chef client every 15mins and swallow the first four retrying warning messages.This is important to avoid Cron sending out e-mails if the connection to the Chef server is a little slow and the Chef client needs a few retries.

Note:

It is possible to initiate a Chef client run at any time by sending the SIGUSR1 signal to the Chef client daemon:


osr@server:~$ sudokillall -USR1 chef-client

Evaluating and troubleshooting Cookbooks and Chef runs


Developing cookbooks and making sure your nodes converge to the desired state is a complex endeavor.You need transparency about what is happening.From running basic checks on your cookbooks to a fully test-driven development approach,we will see what the Chef ecosystem has to offer.

Testing your Chef cookbook with cookstyle and Rubocop 

You know how annoying this is: you tweak a cookbook,run Test Kitchen and boom! it fails.What's even more annoying is that it fails only because you missed  a mundane comma in the default recipe of the cookbook you just tweaked .Fortunately there a quick and easy way to find such simple glitches before you go and try to ru your cookbooks on Test kitchen.

Install the ntp cookbook by running the following command:

local@workstation:~/chef-repo $ knife cookbook site install ntp
Installing ntp to /Users/mmmmma/work/chef-repo/cookbooks
....TRUNCATED OUTPUT

Cookbook ntp version 3.2.0  successfully installed 


How to do it?

Carry out the following steps  to test your cookbook; run cook style on the nap cookbook.

local@workstation:~/chef-repo $  cookstyle cookbook/ntp
Inspecting 5 files
...C
offenses:
cookbook/ntp/recipes/default.rb:25:1  C: Extra blank line detected.

5 files inspected, 1 offenses completed.

How it works?

Cookstyle is a wrapper around Rubocop  and executes a Ruby syntax check an all Ruby files with in the cookbook.Rubocop is a linting and style checking tool built for Ruby.Cookstyle defines same rules for Chef cookbooks.

There's more

There exist a whole ecosystem of additional tools  such as Chefspec  (behavior driven testing for chef) and an Test kitchen (an integration testing tool to run cookbooks on virtual servers).


References:

https://docs.chef.io/rubocop.html

source code for rubocop: https://github.com/bbatsov/rubocop/

more about cook styles: https://github.com/chef/cookstyle/


Flagging problems in your chef cookbooks with Foodcritic


You might wonder what are the proven ways to write a cookbooks are.Foodcritic tries to identify possible issues with the logic and style of your cookbooks.

How to use Foodcritic with your existing cookbooks?

Getting ready:

Install version 6.0.0 of the mysql cookbook by running the following code:


local@workstation:~/chef-repo $ knife cookbook site install mysql 6.0.0
Installing mysql to /Users/mma/chef/work/chef-repo/cookbooks/
TRUNCATED OUTPUT
Cookbook mysql version 6.0.0 successfully installed.

How to do it?

lets see how foodcritic reports findings


local@workstation:~/chef-repo $   foodcritic ./cookbooks/mysql
TRUNCATED OUTPUT
FC001: Use strings in preference to symbols to access node attributes
./cookbooks/mysql/libraries/helpers.rb:243
FC005: Avoid repetition of resource declarations
./cookbooks/mysql/libraries/provider_mysql_service.rb:77
TRUNCATED OUTPUT

2) Get a detailed list of the reported sections inside the mysql cookbook by using the C flag:

local@workstation:~/chef-repo $   foodcritic -C ./cookbooks/mysql
TRUNCATED OUTPUT
FC001: Use strings in preference to symbols to access node attributes
    @pkginfo.set[:suse][11'3]['5'5][:server_package] = 'mysql'
     @pkginfo
     end
./cookbooks/mysql/libraries/provider_mysql_service.rb:77
FC005: Avoid repetition of resource declarations
end

#support directories 
directory  "#{new_resource.name}  :create #{etc_dir}" do
path etc_dir
owner new_resource.run_user
group  new_resource.run_group

 How it works?

Foodcritic defines a set of rules and checks your recipes against each of them.It comes with rules concerning various areas: style, correctness,attributes,strings,portability,search,services,files,metadata and so on.Running Foodcritic against a cookbook tells you which of  its rules matched a certain part of your cookbook.By default,it gives you a short explanation of what you should do along the concerned file and line number.

If you run foodcritic -C,it displays excerpts of the places where it found the rules to match.

In the preceding example,it did not like it that the mysql cookbook version 6.0.0 uses symbols to access node attribute instead of strings:

@pkginfo.set[:suse]['11.3']['5.5'][:server_package] = 'mysql'

This could be rewritten as follows:

@pkginfo.sst['suse']['11.3']['5.5']['server_package']  = 'mysql'

Some of the rules,especially those from the styles section, are opinionated.You are able to exclude certain rules or complete sets of rules,such as style when running Foodcritic:


local@workstation:~/chef-repo $   foodcritic -t '~style' ./cookbooks/mysql
local@workstation:~/chef-repo $

 In this case,the tilde negates the tag selection to exclude all rules with the style tag.Running without the tilde would run the style rules exclusively.


local@workstation:~/chef-repo $ foodcritic -t style ./cookbooks/mysql


Note:

If you want to run foodcritic  in a continous integration (CI) environment,you can use the -f parameter  to indicate which rules  should fail the build:


local@workstation:~/chef-repo $ foodcritic -f style ./cookbook/mysql
...TRUNCATED OUTPUT....
FC001: Use strings in preference to symbols to access node attributes:
./cookbooks/mysql/libraries/helpers.rb:273
FC005: Avoid repetition of resource declarations
 ./cookbooks/mysql/libraries/providers_mysql_service.rb:77
 local@workstation:~/chef-repo $ echo$?

In this example,we  tell Foodcritic to fail if any rule in the style group fails.In our case,it  returns a non-zero exit code instead of zero,as it would if either no rule matches or we omit the -f parameter.That non-zero exit code would fail your build on your continous integration server.You can use -f any if you want foodcritic to fail on all warnings/



References:

Foodcritic and its rules at http://www.foodcritic.io
Testing your chef cookbooks with cookstyle and rubocop receipe.
Checkout strainer,a tool to simultaneously test multiple things,such as foodcritic,knife test and other stuff  at http://github.com/customink/strainer

Chef Node object





when the chef-client is executed will pull down the node object from the server.

This is the first chef-client for the node.

After the node object is pulled down from the server.

The client rebuilds the node object.

So whenever we use information about the node.these node  objects,based off of the last chef client run.

Node attribute:

A  node attribute is the specific piece of data,about the node.

For example,CPU information….etc of which we learn how to query with the tool called ohai.

How does the node object formed?

The chef-client when executed.will pull down the node object from server,if this is the first chef-client for the node,there will not be a node object to pull down.

After the node object is pulled down from the server.client rebuilds the node object.

So,whenever we use,information about the node.this node objects,this is based on the off the base chef-client run.

So,if more memory or swap is added.hostanme has changed .

What happened is ,since we can use the node object.

An attribute information about the node,with in our recipes.

The node object is the first thing to compile.

The chef-client rebuild the node object.this is the first time it does when the chef-client runs.

node object is stored in a JSON file on the server.


Node object is the representation of the system.

Stores all of this runlist and information about our system.

It is available with all of our recipes.

When we are writing code.

Applying chef resources



To know,which user we are dealing.

[local@workstation:~]#   whoami
root
[local@workstation:~]# 

now,we are dealing with the root user.

We have a central server,that is the enterprise server.

We have to be familiar with the linux configurations:

We are going to create a basic ruby file:

We are going to create a basic recipe:

The first resource type:package resource type.

The resource name will also act as a package name.

The package for the apache should be the httpd.

Since we are not going to define the package name.it can not only assume the resource name apache,

package 'apache' do
end
~

ruby  -c learn.rb  this will test the ruby syntax

[local@workstation:~]#  ruby -c learn.rb

this does not test,whether the chef syntax is correct.

For example:whether the package is the really resource type.

We can test the chef syntax,using the foodcritic 

[local@workstation~]# foodcritic learn.rb
FC011: Missing README in markdown  format:  ../README.md:1
FC031: Cookbook with out metadata file:  ../metdata.rb:1
FC045:  Metadata does not contain cookbook name: ../metadata.rb:1
[local@workstation~]#


we don’t have the readme and metadata with the cookbook information.

Chef-client is a tool that runs the convergence,remember all of the work is done on the machine.

Convergence is going to test the package apache is installed and kept installed if not.

Apache is not the real package name,we will get the error,when we run.

[local@workstation~] # chef-client --local-mode learn.rb
WARN: No config  file found or specified  on command-line, using command line options
WARN: No cookbook directory found at or above current directory 
Starting chef client
resolving cookbooks.

Chef important introduction


Whole purpose of the configuration management tool:
To create the environment.
(I want a operating system,with java installed).
That environment,what we called as the infrastructure,on the top of that,we will run the application.
For dot.net application,IIS server should be configured.
Every application,whatever your company is developing would require certain environment to run it.
It would be as simple as commandline application.
Even for that,you may require python to run it.
Or probably,some users to be created.so it can be anything,it can be software installation or 
It can be folder creations.
And generally,we do these things on our servers.
(these kind of configurations,we do on our servers).
Whenever we do that,on a broader way:
Historically we have two ways of doing it:
First one is the manual.
(you will ask the dev team,to write the set of instructions to be done for the installation).
And admin will do the configuration,based on the instructions given by the dev guys).
That was the first approach.
(example:I want linux server,tomcat).
Second is the writing a  shell/batch files in the windows.
(this creates some amount of automation).
In future the batch will be replaced by the powershell.

These are the traditional ways followed.

We are speaking about the configuration management tools:

Claim Infrastrcture is written as code (IAC).

The code can be different from different tools.

(writing your infrastructure as a code).

Whenever we do this,first,

Converting infrastructure to code you have some syntantical  items.

(syntactical ways of telling it).

If you want something to be installed.

Probably the way you tell differs.

(but your intenstion is same across tools).

When you write a code,you can execute it multiple times.
(what will be advantage of this code,these are consistent).

Whenever we write code,we can store it in version control system.

Whatever you write in the configuration management tool are bounded to be the version control.

Important characterstic  of any configuration management tool.

Idempotance

For example,shell file,I have written some types.
I will create folder and in that folder I am writing some files.

I will try to excute second time,it will create another file and fails.

The best thing is the scalable,you can apply this to multiple servers.

Some times you write instructions,which will work in multiple flavours of the linux.

The command which you write to start the service.

Centos 6 and centos 7 changes.

If you run one time or many a times you will get the same result.

They want the end result to be consistent.

Flipcart is a webapplication.
For any webapplication we  need a webserver.

Basically I need to write a infrastructure as a code,to create that environment.

Node or the server are the same.

We have three servers these where we want to create our environment.

Chef server will take care of the responsilibilities.applying configurations to your machines.

Once you create the chef-server
And after that you will install one chef component.
(and that component we called it as the chef-client).

The servers on which,we run our business. Is production.

The servers on which we test our applications. Us dev.

Chef-client software is configured to chef server periodically.

Chef-client is configured to ask,questions,it asked very simple question,do you have any job to do ?

(chef-client will ask questions to the chef-server).

Chef-client is configured for the periodic time.

Chef-client for every 30 mins will ask questions to the chef-server.

And chef-server responds back by saying,if yes or no, if yes it will say what work has to be done.

So,who is intiating the request.

Client is intiating the request.

Basically these models are called the PULL MODELS.

Client is asking for the details.

This is pull kind of configuration management.

So for every 30 mins,client will ask the chef-server do I need to do anything.

Your system where you develop the scripts.that is the workstation.

(chef will have one more architecturial component called the chef-workstation).

Chef only have this architectural component called workstation.

In earlier  chef we have only the knife,now we have the knife/chefdk.

But we are going to call as a chefdk(chef developmentkit).

To work on chef,on our machines we should have the chefdk to install.

we are installing the package tree on the linux servers.

When you apply anything from  localworkstation  to chef-server it did not apply directly to the nodes/server.

In chef,the script goes and it will be executed.


Whatever we write in chef,internally executed by the ruby.

All of the chef will be internally executed by the ruby.

That 30 minutes during which it tries to communicate,technically it is called the convergence.

One more term called the configuration drift or called as convergence drift.

One server asked the question to the chef server at 7am and it is configured run at halfhour
so when we  will be the next question 7:30
At 7:15 one of our developer,written script to written  a folder called  /var/temp
And he has uploaded the script  to the chef-server.these all done at 7:15,will the directory be created,so at 7:15 we have a difference between the configuration and the reality.

From 7:15 to 7:30 we have a situation what you want and what you present.this state is called the CONFIGURATION DRIFT or CONVERGENCE DRIFT.
(7:15 to 7:30 your expected to folder be there,but there is no folder).
The reason behind there is no folder on the production machine because the chef-client did not asked the question,if it is asked the question,then only It can able to create a folder.

Note:

Your chef server has to be a linux machine.
(whether it is Ubuntu/centos/fedora).

Chef workstation  and chef-client(nodes/servers) can be anything may be windows/linux/mac/unix


The problem with the script,it cannot be scaled,so we are going for the infrastructure tools.
(using script,we have to make a lot of tooling inorder to make that script work).

Why infrastructure as a code is a forward way?
The reason behind it,whenever you write code,you can test it.(let it be any code).
This testing is called the unit testing,that we cannot do by the shell scripting.
(whenever I write a code,I can test it,whenever I write a script I cannot able to test it (I mean unit testing is not possible).
I mean,I test it by manually executing it.

Basically,we are learning,how to write a infrastructure as a code,using the chef.



So,if it is chef,how do we write it.

Intially,we used to have a lot physical servers.


Do I need to know about the shell scripting?

I certain organsations,your  job as a devops engineer,will be,these are the existing shell scripts,we have to be in a position to read that and automate it.

Converting the bash script to the equivalent chef code.(equivalent configuration management tool).

Important concept of configuration management rule:

Denoting an element of a set which is unchanged in value when multiplied or otherwise operated on by itself.


The great comparsion,with configuration management I can give idempotent,we cannot give samething with the shell.

(if I run script for one time or for 1000 times,I will always get the same output).

Hosted chef,upto five nodes it was free.if you go beyond we have to purchase the licenses.


Create a organsation on your name.


the other components are knife/chefdk components and the chef-client component.

Bookshelf,Manage and the chef-client will speak with the help of API.

And chef server have multiple components in it.


(bookshelf,cookbooks,searchindex and Datastore and we will speak about the different components).


DK and knife are same
Agent and client are also same.

This workflow is very very important.

Chef has architecturally three components:
Local workstation,chef server and chef nodes.

Chef server will only be one 
Where as chef nodes and chef clients are multiple.

On the local workstation,we have a components to develop the scripts .


Chef-client   is the agent software.
(what does agent-software does is,for every 30 mins it gives updates about the chef-nodes).
(if there are new policies it will apply,so this is called as convergence).

There is another concept called the configuration drift,it is also called the,the gap or the difference between the ideal situation and the current situation.

AWS plugins have the opswork and it can support any components.

But if you want a managed service,chef is an answer.

Chef work is very simple:

It has to transfer a file
It has to store the reports.(report comes back,it has to store it).

They are architectural components ,they are message queues over there.
(there is no chance of message to be locked).

They don’t use API calls,they use the message queues internally (so when the load is more,it might be slow,but does not break).

For example: (Message queues)

You went to atm and you swiped money.you did not get the money,but the balance was cutted from the account and at night 12pm you got your money back.

Reason:for example,whenever you sent a message,http:google.com/ that is called as unreliable messaging because once you type that,if google server is up,the message will reach to it,other wise it may not reach.

Reliable messaging is the message queue.
Before sending the message,the message will send in to a queue.

There will be queue of messages.

And then you would have a server,once it reaches the server,your server will send the acknowledgement.till it gets the acknowledgement,it will not delete the message from the queue.so it is a guaranteed delivery.

Chef uses the message queues.

So,everything you asked is guarantee delivery.

This happens in chef and puppet,this both uses the message queues.

Puppet problem:
We have to remember the directory structures.
(interms of puppet,we need to know the conf def,hierarchies and the directory structure and related environment paths).

Chef solution:
And the only way to eliminate that is:
The developers machine,rather than the server.
You just develop in your machine and just upload to the chef server using simple knife commands.

Can we use chef-client less?

If you have the access to the chef-server,develop scripts directly.(that is what,we don’t do in the chef).