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
A Deep Dive into Building Enterprise grade Generative AI Solutions
A Deep Dive into Building Enterprise grade Generative AI Solutions
Suvoraj Biswas
LocalXpose: The Most Useful Tool for Developers to Share Localhost Online
LocalXpose: The Most Useful Tool for Developers to Share Localhost Online
SitePoint Sponsors
8 AI Tips for Web Developers (and Their Careers)
8 AI Tips for Web Developers (and Their Careers)
Jens Oliver Meiert
How to Make a Simple JavaScript Quiz
How to Make a Simple JavaScript Quiz
Yaphi BerhanuJames Hibbard
Best React UI Component Libraries
Best React UI Component Libraries
Kaarle Varkki
Windows Subsystem for Linux 2 (WSL2): The Complete Tutorial for Windows 10 & 11
Windows Subsystem for Linux 2 (WSL2): The Complete Tutorial for Windows 10 & 11
Craig Buckler
Automating Vultr Cloud Infrastructure with Terraform
Automating Vultr Cloud Infrastructure with Terraform
Vultr
Advanced Web Deployment With Plesk on Vultr
Advanced Web Deployment With Plesk on Vultr
Vultr
Building A 300 Channel Video Encoding Server
Building A 300 Channel Video Encoding Server
John O’Neill
Five Ways to Lazy Load Images for Better Website Performance
Five Ways to Lazy Load Images for Better Website Performance
Maria Antonietta Perna
Building a Telemedicine Platform with AI-Powered Diagnostics Using Vultr
Building a Telemedicine Platform with AI-Powered Diagnostics Using Vultr
Vultr
Create a Toggle Switch in React as a Reusable Component
Create a Toggle Switch in React as a Reusable Component
Praveen KumarMichael Wanyoike
Comparing Docker and Podman: A Guide to Container Management Tools
Comparing Docker and Podman: A Guide to Container Management Tools
Vultr
How to Deploy Flask Applications on Vultr
How to Deploy Flask Applications on Vultr
Vultr
A Comprehensive Guide to Understanding TypeScript Record Type
A Comprehensive Guide to Understanding TypeScript Record Type
Emmanuel Onyeyaforo
Top 7 High-Paying Affiliate Programs for Developers and Content Creators
Top 7 High-Paying Affiliate Programs for Developers and Content Creators
SitePoint Sponsors
How to integrate artificial intelligence into office software: the ONLYOFFICE Docs case study
How to integrate artificial intelligence into office software: the ONLYOFFICE Docs case study
SitePoint Sponsors
Momento Migrates Object Cache as a Service to Ampere Altra
Momento Migrates Object Cache as a Service to Ampere Altra
Dave Neary
Dev Hackathon: Reusable Creativity on Wix Studio
Dev Hackathon: Reusable Creativity on Wix Studio
SitePoint Sponsors
10 Amazing Web Developer Resume Examples for Different Web Dev Specializations
10 Amazing Web Developer Resume Examples for Different Web Dev Specializations
SitePoint Sponsors
How to Build Lightning Fast Surveys with Next.js and SurveyJS
How to Build Lightning Fast Surveys with Next.js and SurveyJS
Gavin Henderson
45 Visual Studio Code Shortcuts for Boosting Your Productivity
45 Visual Studio Code Shortcuts for Boosting Your Productivity
Shahed Nasser
Google Cloud Is the New Way to the Cloud
Google Cloud Is the New Way to the Cloud
SitePoint Sponsors
Understanding Vultr Content Delivery Networks (CDNs)
Understanding Vultr Content Delivery Networks (CDNs)
Vultr
Effortless Content Publishing: A Developer’s Guide to Adobe Experience Manager
Effortless Content Publishing: A Developer’s Guide to Adobe Experience Manager
SitePoint Sponsors
From Idea to Prototype in Minutes: Claude Sonnet 3.5
From Idea to Prototype in Minutes: Claude Sonnet 3.5
Zain Zaidi
Essential Plugins for WordPress Developers: Top Picks for 2024
Essential Plugins for WordPress Developers: Top Picks for 2024
SitePoint Sponsors
WebAssembly vs JavaScript: A Comparison
WebAssembly vs JavaScript: A Comparison
Kaan Güner
The Functional Depth of Docker and Docker Compose
The Functional Depth of Docker and Docker Compose
Vultr
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
Get the freshest news and resources for developers, designers and digital creators in your inbox each week