How to Create a Recipe in Shell Script and Upload to Chef Server

Introduction


Chef is a configuration management system designed to allow y'all to automate and control vast numbers of computers in an automated, reliable, and scalable fashion.

In previous tutorials, nosotros have looked at some common Chef terminology and discussed how to install a Chef server, workstation, and nodes (with Chef 12 or Chef 11). In this guide, we will use these guides equally a jumping off signal to begin talking virtually how to automate your environment.

In this article, nosotros will discuss the basics of creating a Chef cookbook. Cookbooks are the configuration units that permit u.s.a. to configure and perform specific tasks within Chef on our remote nodes. Nosotros build cookbooks and then tell Chef which nodes we desire to run the steps outlined in the cookbook.

In this guide, we will assume that you are starting with the three machines that we concluded the final lesson with. You should accept a server, a workstation, and at least ane node to push configuration changes to.

Basic Cookbook Concepts


Cookbooks serve every bit the fundamental unit of configuration and policy details that Chef uses to bring a node into a specific land. This simply means that Chef uses cookbooks to perform work and make sure things are every bit they should be on the node.

Cookbooks are unremarkably used to handle 1 specific service, application, or functionality. For instance, a cookbook can be created to use NTP to set and sync the node'south fourth dimension with a specific server. Information technology may install and configure a database application. Cookbooks are basically packages for infrastructure choices.

Cookbooks are created on the workstation and so uploaded to a Chef server. From there, recipes and policies described within the cookbook can be assigned to nodes as part of the node'south "run-listing". A run-list is a sequential listing of recipes and roles that are run on a node by chef-customer in order to bring the node into compliance with the policy you lot gear up for it.

In this way, the configuration details that you write in your cookbook are applied to the nodes you want to adhere to the scenario described in the cookbook.

Cookbooks are organized in a directory construction that is completely self-independent. There are many unlike directories and files that are used for different purposes. Let's go over some of the more than of import ones now.

Recipes


A recipe is the main workhorse of the cookbook. A cookbook tin contain more than one recipe, or depend on outside recipes. Recipes are used to declare the land of different resource.

Chef resources describe a role of the system and its desired state. For instance, a resource could say "the package x should be installed". Another resources may say "the x service should be running".

A recipe is a listing related resource that tell Chef how the system should await if it implements the recipe. When Chef runs the recipe, it checks each resources for compliance to the declared state. If the system matches, it moves on to the next resource, otherwise, it attempts to move the resource into the given state.

Resource tin can be of many dissimilar types. You tin learn almost the different resource types hither. Some common ones are:

  • bundle: Used to manage packages on a node
  • service: Used to manage services on a node
  • user: Manage users on the node
  • group: Manage groups
  • template: Manage files with embedded ruby templates
  • cookbook_file: Transfer files from the files subdirectory in the cookbook to a location on the node
  • file: Manage contents of a file on node
  • directory: Manage directories on node
  • execute: Execute a control on the node
  • cron: Edit an existing cron file on the node

Attributes


Attributes in Chef are basically settings. Think of them every bit simple key-value pairs for anything yous might want to use in your cookbook.

There are several unlike kinds of attributes that can be practical, each with a dissimilar level of precedence over the final settings that a node operates under. At the cookbook level, we generally ascertain the default attributes of the service or organisation we are configuring. These tin be overridden later by more than specific values for a specific node.

When creating a cookbook, nosotros tin can set attributes for our service in the attributes subdirectory of our cookbook. Nosotros tin then reference these values in other parts of our cookbook.

Files


The files subdirectory within the cookbook contains whatsoever static files that we will exist placing on the nodes that apply the cookbook.

For instance, any simple configuration files that we are not probable to alter can be placed, in their entirety, in the files subdirectory. A recipe can so declare a resource that moves the files from that directory into their final location on the node.

Templates


Templates are like to files, but they are non static. Template files cease with the .erb extension, meaning that they contain embedded Reddish.

These are mainly used to substitute attribute values into the file to create the terminal file version that will exist placed on the node.

For example, if we have an attribute that defines the default port for a service, the template file can telephone call to insert the aspect at the point in the file where the port is declared. Using this technique, you can easily create configuration files, while keeping the bodily variables that you wish to change elsewhere.

Metadata.rb


The metadata.rb file is used, non surprisingly, to manage the metadata about a package. This includes things similar the name of the package, a clarification, etc.

It also includes things similar dependency information, where you can specify which cookbooks this cookbook needs to operate. This will allow the Chef server to build the run-list for the nodes correctly and ensure that all of the pieces are transfered correctly.

Create a Unproblematic Cookbook


To demonstrate some of the piece of work menstruum involved in working with cookbooks, we will create a cookbook of our own. This volition be a very simple cookbook that installs and configures the Nginx web server on our node.

To begin, we need to go to our ~/chef-repo directory on our workstation:

          cd ~/chef-repo                  

Once at that place, we can create a cookbook past using knife. As nosotros mentioned in previous guides, pocketknife is a tool used to configure nigh interactions with the Chef system. We can employ it to perform work on our workstation and as well to connect with the Chef server or individual nodes.

The general syntax for creating a cookbook is:

<pre> knife cookbook create <span course="highlight">cookbook_name</bridge> </pre>

Since our cookbook will deal with installing and configuring Nginx, we will proper name our cookbook appropriately:

          pocketknife cookbook create nginx                  

          ** Creating cookbook nginx ** Creating README for cookbook: nginx ** Creating CHANGELOG for cookbook: nginx ** Creating metadata for cookbook: nginx                  

What knife does here is builds a simple construction within our cookbooks directory for our new cookbook. Nosotros tin run across our cookbook structure by navigating into the cookbooks directory, and into the directory with the cookbook name.

          cd cookbooks/nginx ls                  

          attributes  CHANGELOG.md  definitions  files  libraries  metadata.rb  providers  README.md  recipes  resources	templates                  

Equally you tin see, this has created a folder and file structure that we tin use to build our cookbook. Permit's begin with the biggest clamper of the configuration, the recipe.

Create a Unproblematic Recipe


If we become into the recipes subdirectory, we can see that at that place is already a file called default.rb within:

          cd recipes ls                  

          default.rb                  

This is the recipe that volition be run if y'all reference the "nginx" recipe. This is where we will be adding our code.

Open the file with your text editor:

          nano default.rb                  

          # # Cookbook Name:: nginx # Recipe:: default # # Copyright 2014, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute #                  

The only thing that is in this file currently is a comment header.

We can brainstorm by planning the things that need to happen for our Nginx web server to get up and running the way that we want it to. We do this past configuring "resources". Resources do not describe how to practice something; they simply describe what a office of the arrangement should look like when it is complete.

Commencement of all, we obviously demand to make certain the software is installed. We can do this by creating a "packet" resource beginning.

          package 'nginx' exercise   action :install terminate                  

This picayune piece of lawmaking defines a bundle resource for Nginx. The first line begins with the type of resources (package) and the proper name of the resource ('nginx'). The residual is a group of deportment and parameters that declare what we desire to happen with the resource.

In this resource, we run into action :install. This line tells Chef that the resource nosotros are describing should exist installed. The node that runs this recipe will check that Nginx is installed. If it is, it will check that off the list of things to do. If not, it will install the program using the methods bachelor on the customer system and then check information technology off.

After we install the service, we probably want to adjust its electric current state on the node. By default, Ubuntu does not start Nginx after installation, so nosotros will desire to change that:

          service 'nginx' do   action [ :enable, :start ] end                  

Here, nosotros see a resources of the "service" type. This declares that for the Nginx service component (the part that allows usa to manage the server with init or upstart), nosotros want to commencement the service right at present, and also enable it to starting time automatically when the machine is restarted.

The terminal resource nosotros will exist declaring is the actual file that we volition exist serving. Since this is just a elementary file that we volition not exist modifying, we tin simply declare the location where we want the file and tell information technology where in the cookbook to become the file:

          cookbook_file "/usr/share/nginx/www/alphabetize.html" do   source "alphabetize.html"   mode "0644" terminate                  

We employ the "cookbook_file" resources type to tell Chef that this file is available inside the cookbook itself and tin exist transfered as-is to the location. In our example, nosotros are transferring a file into Nginx's certificate root.

In our instance, nosotros specify the file proper name that nosotros are trying to create in the beginning line. In the "source" line, we tell it the name of the file to look for within the cookbook. Chef looks for this file within the "files/default" subdirectory in the cookbook.

The "style" line sets the permissions on the file we are creating. In this example, we are allowing the root user read and write permissions and everyone else read permissions.

Salve and close this file when you are finished.

Creating the Index file


Equally yous saw above, we defined a "cookbook_file" resource which should move a file called "alphabetize.html" into the document root on the node. We need to create this file.

We should put this file in the "files/default" subdirectory of our cookbook. Go there now by typing:

          cd ~/chef-repo/cookbooks/nginx/files/default                  

Inside this directory, we volition create the file we referenced:

          nano index.html                  

This file volition just exist a really simple HTML document meant to demonstrate that our resources take operated the manner we wanted them to.

Paste this into the file:

          <html>   <caput>     <title>Hullo at that place</title>   </caput>   <torso>     <h1>This is a test</h1>     <p>Please work!</p>   </body> </html>                  

Salvage and close the file when you are finished.

Create a Helper Cookbook


Earlier we become whatsoever farther, let's preemptively solve a small problem. When our node tries to run the cookbook that we've created as it is now, chances are, it volition fail.

That is because it will endeavor to install Nginx from the Ubuntu repositories, and the package database on our node is near likely out-of-date. Usually, we run "sudo apt-go update" prior to running bundle commands.

To address this consequence, we can create a simple cookbook whose but purpose is to ensure that the package database is updated.

We can exercise this using the same knife syntax nosotros used before. Let's call this cookbook "apt":

          knife cookbook create apt                  

This will create the same kind of directory structure that we had when we first started with our Nginx cookbook.

Allow's cutting straight to the hunt and edit the default recipe for our new cookbook.

          nano ~/chef-repo/cookbooks/apt/recipes/default.rb                  

In this file, we will declare an "execute" resources. This is simply a mode of defining a command that we want to run on the node.

Our resource looks like this:

          execute "apt-get update" do   control "apt-go update" end                  

The get-go line gives a name for our resources. In our instance, we are calling the resource this for simplicity'southward sake. If the "command" attribute is defined (as nosotros have done), so this is the actual command that is executed.

Since these are exactly the same, information technology does non affair in the slightest.

Relieve and close the file.

Now that we have our new cookbook, there are a number of ways that we tin brand sure that we execute this earlier our Nginx cookbook. We could add it to the node'south run-list before the Nginx cookbook, simply we can likewise necktie information technology into the Nginx cookbook itself.

This is probably the amend selection because we volition not have to recall to add the "apt" cookbook before the "nginx" cookbook on every node nosotros want to configure for Nginx.

We need to adjust a few things in the Nginx cookbook to make this happen. First, let'due south open the Nginx recipe file over again:

          nano ~/chef-repo/cookbooks/nginx/recipes/default.rb                  

At the pinnacle of this cookbook, earlier the other resources that we have defined, nosotros can read in the "apt" default recipe by typing:

<pre> <span class="highlight">include_recipe "apt"</bridge>

packet 'nginx' do action :install end

service 'nginx' practice activity [ :enable, :start ] terminate

cookbook_file "/usr/share/nginx/www/index.html" exercise source "alphabetize.html" mode "0644" end </pre>

Save and close the file.

The other file that we need to edit is the metadata.rb file. This file is checked when the Chef server sends the run-list to the node, to see which other recipes should exist added to the run-list.

Open up the file now:

          nano ~/chef-repo/cookbooks/nginx/metadata.rb                  

At the bottom of the file, yous can add together this line:

<pre> proper name 'nginx' maintainer 'YOUR_COMPANY_NAME' maintainer_email 'YOUR_EMAIL' license 'All rights reserved' description 'Installs/Configures nginx' long_description IO.read(File.bring together(File.dirname(FILE), 'README.md')) version '0.1.0'

<span class="highlight">depends "apt"</span> </pre>

With that finished, our Nginx cookbook now relies on our apt cookbook to have care of the package database update.

Add together the Cookbook to your Node


Now that our bones cookbooks are complete, nosotros tin can upload them to our chef server.

We can practise that individually by typing:

          knife cookbook upload apt knife cookbook upload nginx                  

Or, we can upload everything by typing:

          knife cookbook upload -a                  

Either way, our recipes volition be uploaded to the Chef server.

At present, we tin can modify the run-listing of our nodes. Nosotros can do this easily past typing:

<pre> knife node edit <bridge class="highlight">name_of_node</span> </pre>

If you need to find the name of your bachelor nodes, yous tin can type:

          pocketknife node list                  

          client1                  

For our purposes, when we type this, nosotros get a file that looks like this:

          knife node edit client1                  

          {   "proper name": "client1",   "chef_environment": "_default",   "normal": {     "tags": [      ]   },   "run_list": [    ] }                  

You may need to fix your EDITOR ecology variable before this works. Yous can do this by typing:

<pre> export EDITOR=<span class="highlight">name_of_editor</span> </pre>

As you can see, this is a simple JSON certificate that describes some aspects of our node. We tin can encounter a "run_list" assortment, which is currently empty.

Nosotros tin add our Nginx cookbook to that assortment using the format:

<pre> "recipe[<bridge class="highlight">name_of_recipe</span>]" </pre>

When we are finished, our file should await similar this:

          {   "name": "client1",   "chef_environment": "_default",   "normal": {     "tags": [      ]   },   "run_list": [     "recipe[nginx]"   ] }                  

Save and close the file to implement the new settings.

At present, we can SSH into our node and run the Chef client software. This will cause the client to check into the Chef server. Once information technology does this, it volition see the new run-listing that has been assigned it.

SSH into your node and then run this:

          sudo chef-client                  

          Starting Chef Client, version 11.8.2 resolving cookbooks for run listing: ["nginx"] Synchronizing Cookbooks:   - apt   - nginx Compiling Cookbooks... Converging 4 resources Recipe: apt::default   * execute[apt-get update] activeness run     - execute apt-become update  Recipe: nginx::default   * package[nginx] action install (up to date)   * service[nginx] activity enable     - enable service service[nginx]    * service[nginx] activeness start (up to engagement)   * cookbook_file[/usr/share/nginx/www/alphabetize.html] action create (upwards to appointment) Chef Client finished, 2 resource updated                  

As yous can see, our apt cookbook was sent over and run likewise, even though it wasn't in the run-list we created. That is because Chef intelligently resolved dependencies and modified the actual run-list before executing it on the node.

Note: In that location are various methods of ensuring that ane cookbook or recipe is run before some other. Calculation a dependency is merely one pick, and other methods may be preferred.

We tin verify that this works by going to our node'due south IP address or domain name:

<pre> http://<span class="highlight">node_domain_or_IP</span> </pre>

You should see something that looks like this:

Chef node Nginx

Congratulations, you have configured your first node using Chef cookbooks!

Decision


Although this was a very simple case that probably didn't salve you much time over configuring your server manually, hopefully you tin begin to run across the possibilities of this method of building infrastructure.

Not only does it permit for rapid deployment and configuration of different kinds of servers, information technology ensures that you know the exact configuration of all of your machines. This lets you validate and examination your infrastructure, and likewise gives you the framework you need to quickly redeploy your infrastructure on a whim.

<div form="author">By Justin Ellingwood</div>

gocherovereful.blogspot.com

Source: https://www.digitalocean.com/community/tutorials/how-to-create-simple-chef-cookbooks-to-manage-infrastructure-on-ubuntu

0 Response to "How to Create a Recipe in Shell Script and Upload to Chef Server"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel