Cooking with Chef Solo

Share this article

Chef is billed as “A systems integration framework, built to bring the benefits of configuration management to your entire infrastructure”. It doesn’t matter how many times I read that, I still hear a ‘whoosh’ over my head. Put simply, we can manage server configurations through good old familiar Ruby.

The gist of Chef is we create cookbooks, these cookbooks use the Chef DSL to install and configure packages we require for our servers. How many times have you looked up the same tutorial for installing and configuring something like MySQL? With Chef we have a cookbook, under source control that we can maintain and use to spin up new environments in no time. If you have ever had to create your own staging and production environments, and maintain consistency as your application evolves this should already be sounding like good news.

Chef comes in a couple of flavors. Today we will focus on Chef Solo, unlike Chef Server, Chef Solo works with everything “on disk”. The cookbooks, and anything else we require (which we will get into in a minute) have to be on the server we are configuring.

The Basics of Chef Solo

Before going any further it’s probably best we establish the components available to us when creating Chef scripts, previously we called this “anything else we require.”

Recipes for Resources

Quite simply the resource is what we are trying to configure on the server. Taking the example of MySQL, we write a recipe for the that resource. The Recipe is written in Ruby and establishes how we want the resource configured using block style syntax.

package "mysql-client" do
  package_name value_for_platform("default" => "mysql-client")
  action :install
end

The source above is a truncated example of the Opscode recipe for MySQL. Although it pretty much makes sense to read as is, you may wonder about the value_for_platform method. It simply selects the correct package name of the resource you are trying to configure based on the platform. I have condensed this for Debian based systems, but we can pass a plain old Ruby Hash to make Chef use the correct package. If you hadn’t clicked ahead to the original source yet:

package_name value_for_platform(
    [ "centos", "redhat", "suse", "fedora", "scientific", "amazon"] => { "default" => "mysql" },
    "default" => "mysql-client"
  )

How does Chef know what platform we are running on? The answer to that question leads nicely into Nodes.

Nodes

A Node is our server. Our Cookbook of Recipes are applied to a Node. We could end it here, but I recently found it handy to peel back the curtain on Nodes.

To find out everything it needs to know about our Node/Server, Chef uses a gem named Ohai. You can check out how Chef does this yourself.

require 'ohai'
o = Ohai::System.new
o.all_plugins
puts o[:platform] # => "linuxmint"

Just Like Mama Used to Make it

That is quite enough theory, now it’s time to get our hands dirty. Grab your favorite server distro (I’m going to use Ubuntu on VirtualBox). I find VirtualBox great for its snapshot capabilities, allowing us to test out a Chef run and roll it back if something goes wrong.

The directory structure of the project is pretty simple. We will have a cookbook, recipes and support files.

mkdir cookbooks cookbooks/main cookbooks/main/recipes
touch solo.rb cookbooks/main/recipes/default.rb node.json

The next step is to open our solo.rb file and add the following:

cookbook_path File.join(File.dirname(File.expand_path(__FILE__)), "cookbooks")
json_attribs File.join(File.dirname(File.expand_path(__FILE__)), "node.json")

As you probably guessed, all we are doing in the first line is telling Chef where to find our Cookbooks. We then pass the location of node.json to json_attribs. Our file node.json is where we will set specific attributes for our Chef run.

I showed earlier that Chef will set up a lot of information about our environment. Some of these attributes can be overwritten by our recipes. There is a precedence for these attributes. In this example, anything passed to json_attribs will take highest precedence.

It is time to look at our node.json file now. One thing I like to use is a common temp directory, it’s a handy place for downloading packages, files etc. Chef does not give us this so we can start by adding that. While we are doing that, we better setup our main recipe. This will simply include other recipes for our server, and makes a nice drop off point if we need to add/remove any recipes.

{
  "temp_dir":"/tmp",
  "run_list":["recipe[main]"]
}

Now that we have some basic setup in place, let’s look at what we want our Chef run to do. For this example, we will keep it pretty short and sweet. There are a host of cookbooks already available for you to get a good starting point. Instead, we will look at installing a package using available cookbooks (Apache) and we will install RVM.

The first task for apache is simply a case of copying the existing cookbook into our cookbooks directory.

RVM on the other hand we will have to do a bit more work. First of all we create a rvm directory along with our other cookbooks and a recipes folder.

mkdir cookbooks/rvm cookbooks/rvm/recipes
touch cookbooks/rvm/default.rb

If we look at RVMs release notes we see there are a number of dependencies. Job number 1 for our RVM recipe is to meet these.

%w(build-essential openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion).each do |pkg|
  package pkg
end

I know some of these may already be in place on our system, but I like to treat each recipe in isolation. If the package is already there, what the hey? Using the package method we can ensure our dependencies are in place.

The next step is to install RVM itself. I’m guessing you will have already done this before and know about the great bin installer. Well, Chef supports these kind of installs using its bash provider. This essentially evaluates the block as a bash command.

bash "install RVM" do
  user node[:user]
  code "sudo bash < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer )"
end

The Chef DSL is just great to follow, I setup a bash script to be run as the current user on the system and execute the RVM install script. Don’t get caught in the trap of executing this as user "root", as I did. Following the RVM documentation , there is a difference.

Garnish and Season

Now that we have a couple of recipes in place, it’s time to sort out the run order and how we get the Chef script onto the box/node. The first one is simple: In cookbooks/main/recipes/default.rb add your cookbooks.

include_recipe "apache2"
include_recipe "rvm"

It’s just Ruby so we can add new cookbooks, comment out lines, or whatever you are used to doing in your ruby files. Now we have to look at getting the code onto the box we are interested in. The best way I have seen is to use a bash script. This was originally pointed out to me by my esteemed college Colin Gemmell, who done most of the grunt work for this bash script. Me? I just tweaked it a little.

#!/bin/bash

sudo apt-get update
sudo apt-get install git-core -y -q
sudo apt-get install build-essential -y -q
sudo apt-get install ruby -y -q
sudo apt-get install ruby-dev -y -q
sudo apt-get install libopenssl-ruby -y -q
sudo apt-get install rubygems -y -q
sudo apt-get install irb -y -q
sudo apt-get install rake -y -q
sudo apt-get install curl -y -q
sudo gem install chef --no-ri --no-rdoc

git clone git://github.com/bangline/demo_cookbooks.git /tmp/chef_run

cd /tmp/chef_run

sudo /var/lib/gems/1.8/bin/chef-solo -c /tmp/chef_run/solo.rb -j /tmp/chef_run/node.json

It’s pretty straight forward. All the dependencies I need are setup first (silenced so I an not asked “Is this OK? [Y/N]” for every package) before cloning the project and running chef-solo on it. The Chef script is passed in the configuration of solo.rb and the JSON attributes from node.json.

After the Chef script completes, testing it is easy. For Apache, just wget http://127.0.0.1 to download the “It works!” page. For RVM, you will have to logout and log back in again, after which rvm notes will produce the RVM documentation. The next step would to modify this recipe to install a default Ruby version of course.

Wrapping up

Chef is a huge topic and the documentation for it is improving over time. Hopefully this introduction will give you enough of an incentive to start using Chef in some way when thinking of starting some manual system ops. There is still so much to cover, setting up users, vhosts or even setting a default Ruby to use with RVM and install Passenger or something alongside so we have a complete hosting solution for our applications. If you go ahead and test out the demo (source can be found in the usual place), you will find a couple of annoying warnings when restarting Apache. This one is not a big deal, we should really have tinkered with the NameVirtualHost configuration. Nonetheless, considering this was just a quick copy/paste job, we do get a working Apache2 setup.

The greatest resource for me has been examining the existing cookbooks from Opscode and 37Signals. A lot of work has been done for a lot of common packages. These days I struggle to find a resource that does not have a cookbook available in some form to use “as is” or minimal customizations.

So, next time you are setting up an environment for your applications invest some time building it on a local virtual host using VirtualBox. Like most things it will take extra time, it will frustrate you, but what you end up with pays of ten fold. Now who else is hungry?

Dave KennedyDave Kennedy
View Author

Dave is a web application developer residing in sunny Glasgow, Scotland. He works daily with Ruby but has been known to wear PHP and C++ hats. In his spare time he snowboards on plastic slopes, only reads geek books and listens to music that is certainly not suitable for his age.

chefdevops
Share this article
Read Next
How Top HR Agencies Build Trust Through Logo Designs
How Top HR Agencies Build Trust Through Logo Designs
Evan Brown
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
Leveraging Progressive Web Apps (PWAs) for Enhanced Mobile User Engagement
SitePoint Sponsors
10 Artificial Intelligence APIs for Developers
10 Artificial Intelligence APIs for Developers
SitePoint Sponsors
The Ultimate Guide to Navigating SQL Server With SQLCMD
The Ultimate Guide to Navigating SQL Server With SQLCMD
Nisarg Upadhyay
Retrieval-augmented Generation: Revolution or Overpromise?
Retrieval-augmented Generation: Revolution or Overpromise?
Kateryna ReshetiloOlexandr Moklyak
How to Deploy Apache Airflow on Vultr Using Anaconda
How to Deploy Apache Airflow on Vultr Using Anaconda
Vultr
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Cloud Native: How Ampere Is Improving Nightly Arm64 Builds
Dave NearyAaron Williams
How to Create Content in WordPress with AI
How to Create Content in WordPress with AI
Çağdaş Dağ
A Beginner’s Guide to Setting Up a Project in Laravel
A Beginner’s Guide to Setting Up a Project in Laravel
Claudio Ribeiro
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Enhancing DevSecOps Workflows with Generative AI: A Comprehensive Guide
Gitlab
Creating Fluid Typography with the CSS clamp() Function
Creating Fluid Typography with the CSS clamp() Function
Daine Mawer
Comparing Full Stack and Headless CMS Platforms
Comparing Full Stack and Headless CMS Platforms
Vultr
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
A Beginner’s Guide to SvelteKit
A Beginner’s Guide to SvelteKit
Erik KückelheimSimon Holthausen
Brighten Up Your Astro Site with KwesForms and Rive
Brighten Up Your Astro Site with KwesForms and Rive
Paul Scanlon
Which Programming Language Should I Learn First in 2024?
Which Programming Language Should I Learn First in 2024?
Joel Falconer
Managing PHP Versions with Laravel Herd
Managing PHP Versions with Laravel Herd
Dianne Pena
Accelerating the Cloud: The Final Steps
Accelerating the Cloud: The Final Steps
Dave Neary
An Alphebetized List of MIME Types
An Alphebetized List of MIME Types
Dianne Pena
The Best PHP Frameworks for 2024
The Best PHP Frameworks for 2024
Claudio Ribeiro
11 Best WordPress Themes for Developers & Designers in 2024
11 Best WordPress Themes for Developers & Designers in 2024
SitePoint Sponsors
Top 10 Best WordPress AI Plugins of 2024
Top 10 Best WordPress AI Plugins of 2024
Dianne Pena
20+ Tools for Node.js Development in 2024
20+ Tools for Node.js Development in 2024
Dianne Pena
The Best Figma Plugins to Enhance Your Design Workflow in 2024
The Best Figma Plugins to Enhance Your Design Workflow in 2024
Dianne Pena
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Christopher Collins
Build Your Own AI Tools in Python Using the OpenAI API
Build Your Own AI Tools in Python Using the OpenAI API
Zain Zaidi
The Best React Chart Libraries for Data Visualization in 2024
The Best React Chart Libraries for Data Visualization in 2024
Dianne Pena
7 Free AI Logo Generators to Get Started
7 Free AI Logo Generators to Get Started
Zain Zaidi
Turn Your Vue App into an Offline-ready Progressive Web App
Turn Your Vue App into an Offline-ready Progressive Web App
Imran Alam
Clean Architecture: Theming with Tailwind and CSS Variables
Clean Architecture: Theming with Tailwind and CSS Variables
Emmanuel Onyeyaforo
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form