• Stars
    star
    107
  • Rank 323,587 (Top 7 %)
  • Language
    Ruby
  • License
    Apache License 2.0
  • Created almost 11 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

DEPRECATED: A tiny Chef API client with minimal dependencies

ChefAPI Client

Gem Version Build status

ChefAPI is a dependency-minimal Ruby client for interacting with a Chef Server. It adopts many patterns and principles from Rails

DEPRECATED

The chef-api gem is no longer maintained. Please use the supported Chef::ServerAPI library from the Chef gem. Documentation is provided at https://docs.chef.io/server/api_chef_server/.

Quick start

Install via Rubygems:

$ gem install chef-api

or add it to your Gemfile if you are using Bundler:

gem 'chef-api', '~> 0.1'

In your library or project, you will likely want to include the ChefAPI::Resource namespace:

include ChefAPI::Resource

This will give you "Rails-like" access to the top-level Chef resources like:

Client.all
Node.all

If you choose not to include the module, you will need to specify the full module path to access resources:

ChefAPI::Resource::Client.all
ChefAPI::Resource::Node.all

Create a connection

Before you can make a request, you must give the ChefAPI your connection information and credentials.

ChefAPI.configure do |config|
  # The endpoint for the Chef Server. This can be an Open Source Chef Server,
  # Hosted Chef Server, or Enterprise Chef Server.
  config.endpoint = 'https://api.opscode.com/organizations/meats'

  # ChefAPI will try to determine if you are running on an Enterprise Chef
  # Server or Open Source Chef depending on the URL you provide for the
  # +endpoint+ attribute. However, it may be incorrect. If is seems like the
  # generated schema does not match the response from the server, it is
  # possible this value was calculated incorrectly. Thus, you should set it
  # manually. Possible values are +:enterprise+ and +:open_source+.
  config.flavor = :enterprise

  # The client and key must also be specified (unless you are running Chef Zero
  # in no-authentication mode). The +key+ attribute may be the raw private key,
  # the path to the private key on disk, or an +OpenSSLL::PKey+ object.
  config.client = 'bacon'
  config.key    = '~/.chef/bacon.pem'

  # If you are running your own Chef Server with a custom SSL certificate, you
  # will need to specify the path to a pem file with your custom certificates
  # and ChefAPI will wire everything up correctly. (NOTE: it must be a valid
  # PEM file).
  config.ssl_pem_file = '/path/to/my.pem'

  # If you would like to be vulnerable to MITM attacks, you can also turn off
  # SSL verification. Despite what Internet blog posts may suggest, you should
  # exhaust other methods before disabling SSL verification. ChefAPI will emit
  # a warning message for every request issued with SSL verification disabled.
  config.ssl_verify = false

  # If you are behind a proxy, Chef API can run requests through the proxy as
  # well. Just set the following configuration parameters as needed.
  config.proxy_username = 'user'
  config.proxy_password = 'password'
  config.proxy_address  = 'my.proxy.server' # or 10.0.0.50
  config.proxy_port     = '8080'

  # If you want to make queries that return a very large result chef, you might
  # need to adjust the timeout limits for the network request. (NOTE: time is
  # given in seconds).
  config.read_timeout = 120
end

All of these configuration options are available via the top-level ChefAPI object.

ChefAPI.endpoint = '...'

You can also configure everything via environment variables (great solution for Docker-based usage). All the environment variables are of the format CHEF_API_{key}, where key is the uppercase equivalent of the item in the configuration object.

# ChefAPI will use these values
export CHEF_API_ENDPOINT=https://api.opscode.com/organizations/meats
export CHEF_API_CLIENT=bacon
export CHEF_API_KEY=~/.chef/bacon.pem

In addition, you can configure the environment variables in a JSON-formatted config file either placed in ~/.chef-api or placed in a location configured via the environment variable CHEF_API_CONFIG. For example:

{
  "CHEF_API_ENDPOINT": "https://api.opscode.com/organizations/meats",
  "CHEF_API_CLIENT": "bacon",
  "CHEF_API_KEY": "~/.chef/bacon.pem"
}

If you prefer a more object-oriented approach (or if you want to support multiple simultaneous connections), you can create a raw ChefAPI::Connection object. All of the options that are available on the ChefAPI object are also available on a raw connection:

connection = ChefAPI::Connection.new(
  endpoint: 'https://api.opscode.com/organizations/meats',
  client:   'bacon',
  key:      '~/.chef/bacon.pem'
)

connection.clients.fetch('chef-webui')
connection.environments.delete('production')

If you do not want to manage a ChefAPI::Connection object, or if you just prefer an alternative syntax, you can use the block-form:

ChefAPI::Connection.new do |connection|
  connection.endpoint = 'https://api.opscode.com/organizations/meats'
  connection.client   = 'bacon'
  connection.key      = '~/.chef/bacon.pem'

  # The connection object is now setup, so you can use it directly:
  connection.clients.fetch('chef-webui')
  connection.environments.delete('production')
end

Making Requests

The ChefAPI gem attempts to wrap the Chef Server API in an object-oriented and Rubyesque way. All of the methods and API calls are heavily documented inline using YARD. For a full list of every possible option, please see the inline documentation.

Most resources can be listed, retrieved, created, updated, and destroyed. In programming, this is commonly referred to as "CRUD".

Create

There are multiple ways to create a new Chef resource on the remote Chef Server. You can use the native create method. It accepts a list of parameters as a hash:

Client.create(name: 'new-client') #=> #<Resource::Client name: "new-client", admin: false, ...>

Or you can create an instance of the object, setting parameters as you go.

client = Client.new
client.name = 'new-client'
client.save #=> #<Resource::Client name: "new-client", admin: false, ...>

You can also mix-and-match the hash and object initialization:

client = Client.new(name: 'new-client')
client.validator = true
client.admin = true
client.save #=> #<Resource::Client name: "new-client", admin: false, ...>

Read

Most resources have the following "read" functions:

  • .list, .all, and .each for listing Chef resources
  • .fetch for getting a single Chef resource with the given identifier
Listing

You can get a list of all the identifiers for a given type of resource using the .list method. This is especially useful when you only want to list items by their identifier, since it only issues a single API request. For example, to get the names of all of the Client resources:

Client.list #=> ["chef-webui", "validator"]

You can also get the full collection of Chef resources using the .all method:

Client.all #=> [#<Resource::Client name: "chef-webui", admin: false ...>,
                #<Resource::Client name: "validator", admin: false ...>]

However, this is incredibly inefficient. Because of the way the Chef Server serves requests, this will make N+1 queries to the Chef Server. Unless you absolutely need every resource in the collection, you are much better using the lazy enumerable:

Client.each do |client|
  puts client.name
end

Because the resources include Ruby's custom Enumerable, you can treat the top-level resources as if they were native Ruby enumerable objects. Here are just a few examples:

Client.first #=> #<Resource::Client name: "chef-webui" ...>
Client.first(3) #=> [#<Resource::Client name: "chef-webui" ...>, ...]
Client.map(&:public_key) #=> ["-----BEGIN PUBLIC KEY-----\nMIGfMA...", "-----BEGIN PUBLIC KEY-----\nMIIBI..."]
Fetching

You can also fetch a single resource from the Chef Server using the given identifier. Each Chef resource has a unique identifier; internally this is called the "primary key". For most resources, this attribute is "name". You can fetch a resource by it's primary key using the .fetch method:

Client.fetch('chef-webui') #=> #<Resource::Client name: "chef-webui" ...>

If a resource with the given identifier does not exist, it will return nil:

Client.fetch('not-a-real-client') #=> nil

Update

You can update a resource using it's unique identifier and a list of hash attributes:

Client.update('chef-webui', admin: true)

Or you can get an instance of the object and update the attributes manually:

client = Client.fetch('chef-webui')
client.admin = true
client.save

Delete

You can destroy a resource using it's unique identifier:

Client.destroy('chef-webui') #=> true

Or you can get an instance of the object and delete it manually:

client = Client.fetch('chef-webui')
client.destroy #=> true

Validations

Each resource includes its own validations. If these validations fail, they exhibit custom errors messages that are added to the resource. For example, Chef clients must have a name attribute. This is validated on the client side:

client = Client.new
client.save #=> false

Notice that the client.save call returned false? This is an indication that the resource did not commit back to the server because of a failed validation. You can get the error(s) that prevented the object from saving using the .errors method on an instance:

client.errors #=> { :name => ["must be present"] }

Just like Rails, you can also get the human-readable list of these errors by calling #full_messages on the errors hash. This is useful if you are using ChefAPI as a library and want to give developers a semantic error:

client.errors.full_messages #=> ["`name' must be present"]

You can also force ChefAPI to raise an exception if the validations fail, using the "bang" version of save - save!:

client.save! #=> InvalidResource: There were errors saving your resource: `name' must be present

Objects on Disk

ChefAPI also has the ability to read and manipulate objects on disk. This varies from resource-to-resource, but the .from_file method accepts a path to a resource on disk and loads as much information about the object on disk as it can. The attributes are then merged with the remote resource, if one exists. For example, you can read a Client resource from disk:

client = Client.from_file('~/.chef/bacon.pem') #=> #<Resource::Client name: "bacon", admin: false, public_key: nil, private_key: "..." ...>

Searching

ChefAPI employs both search and partial search functionality.

# Using regular search
results = Search.query(:node, '*:*', start: 1)
results.total #=> 5_000
results.rows.each do |result|
  puts result
end

# Using partial search
results = PartialSearch.query(:node, { data: ['fqdn'] }, start: 1)
results.total #=> 2
results.rows.each do |result|
  puts result
end

FAQ

Q: How is this different than Ridley?
A: Ridley is optimized for highly concurrent connections with support for multiple Chef Servers. ChefAPI is designed for the "average user" who does not need the advanced use cases that Ridley provides. For this reason, the ChefAPI is incredibly opinionated about the features it will include. If you need complex features, take a look at Ridley.

Development

  1. Clone the project on GitHub
  2. Create a feature branch
  3. Submit a Pull Request

Important Notes:

  • All new features must include test coverage. At a bare minimum, Unit tests are required. It is preferred if you include acceptance tests as well.
  • The tests must be be idempotent. The HTTP calls made during a test should be able to be run over and over.
  • Tests are order independent. The default RSpec configuration randomizes the test order, so this should not be a problem.

License & Authors

Copyright 2013-2014 Seth Vargo

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

More Repositories

1

cookbooks

DEPRECATED: This repository has been split up into separate repositories by cookbook under the "opscode-cookbooks" organization.
1,495
star
2

chef-repo

DEPRECATED: Use of this repository is deprecated. We recommend using the chef generate repo command that comes with ChefDK.
859
star
3

vagrant-omnibus

A Vagrant plugin that ensures the desired version of Chef is installed via the platform-specific Omnibus packages.
Ruby
551
star
4

devops-kungfu

Chef Style DevOps Kung fu
JavaScript
528
star
5

chef-provisioning

A library for creating machines and infrastructures idempotently in Chef.
Ruby
524
star
6

chef-dk

DEPRECATED: A streamlined development and deployment workflow for Chef Infra platform.
Ruby
384
star
7

windows

Development repository for Chef Cookbook windows
Ruby
252
star
8

chef-fundamentals

DEPRECATED: Chef Fundamentals training materials
CSS
205
star
9

database

DEPRECATED: Development repository for Chef database cookbook
Ruby
186
star
10

chef-client

Development repository for Chef Client cookbook
Ruby
175
star
11

stove

DEPRECATED: A utility for packaging and releasing Chef cookbooks
Ruby
168
star
12

minitest-chef-handler

Run minitest suites after your Chef recipes to check the status of your system.
Ruby
164
star
13

knife-rackspace

Chef knife plug-in for Rackspace
Ruby
153
star
14

chef-rfc

Public RFCs for Chef and related projects
Ruby
148
star
15

chef-provisioning-aws

AWS driver and resources for Chef that uses the AWS SDK
Ruby
142
star
16

sudo

Development repository for sudo cookbook
Ruby
117
star
17

build-essential

Development repository for build-essential Chef Cookbook
Ruby
116
star
18

chef-provisioning-docker

Docker provisioner for chef-provisioning
Ruby
93
star
19

erchef

DEPRECATED: Erlang based Chef Server top-level OTP release project
Erlang
89
star
20

knife-acl

knife plugin for working with ACLs on Chef Server
Ruby
81
star
21

delivery-cli

The command line tool for the workflow capabilities in Chef Automate.
Rust
80
star
22

knife-linode

DEPRECATED: Chef knife plug-in for Linode
Ruby
78
star
23

omnibus-chef

Omnibus packaging for Chef
77
star
24

chef-web-docs-2016

DEPRECATED - All The Documentation
HTML
75
star
25

omnibus_updater

DEPRECATED: Chef cookbook to update the omnibus packaged Chef client
Ruby
74
star
26

openssl

Development repository for openssl cookbook
Ruby
74
star
27

terraform-provisioner-inspec

Terraform InSpec Provisioner Plugin
Go
68
star
28

rails-quick-start

DEPRECATED: Repository used with the Chef Rails Quick Start Guide
HTML
63
star
29

ubuntu

Development repository for Chef Cookbook ubuntu
Ruby
61
star
30

chef-vault

chef-vault cookbook
Ruby
61
star
31

route53

DEPRECATED: Provides resources for adding and removing records from Amazon Route53
Ruby
60
star
32

knife-container

DEPRECATED: Container support for Chef's Knife Command
Ruby
57
star
33

audit

Audit Cookbook for Chef Compliance
Ruby
57
star
34

chef-provisioning-fog

Fog driver for Chef Provisioning
Ruby
54
star
35

chef_nginx

Chef Software support NGINX cookbook
Ruby
53
star
36

quick-reference

quick reference documentation
52
star
37

ohai

Development repository for Chef Cookbook ohai
Ruby
49
star
38

chef_handler

DEPRECATED: Development repository for Chef Cookbook chef_handler
Ruby
49
star
39

dmg

Development repository for dmg Chef cookbook
Ruby
45
star
40

omnibus-chef-server

Deprecated: Omnibus packaging for Opscode Chef Server (OSC 11.x only).
Ruby
44
star
41

inspec-aws-old

[Deprecated] This is integrated in InSpec 2.0 now
Ruby
42
star
42

django-quick-start

DEPRECATED: Django Quick Start Guide Chef Repository
40
star
43

hubot

DEPRECATED: Chef cookbook for deploying and managing an instance of Github's Hubot.
Ruby
40
star
44

httpd

DEPRECATED: Library cookbook with Apache httpd primitives
Ruby
39
star
45

aws_native_chef_server

Cloudformation templates for building a scalable cloud-native Chef Server on AWS
Shell
37
star
46

delivery-truck

DEPRECATED: Delivery build cb for pipelines
Ruby
36
star
47

bluepill

Development repository for bluepill Chef Cookbook
Ruby
35
star
48

unicorn

DEPRECATED: Development repository for Chef Cookbook unicorn
Ruby
34
star
49

chef-server-cluster

DEPRECATED: Chef Cookbook to manage Chef Clusters
Ruby
33
star
50

opscode-packages

Packages of Opscode Software for various platforms
Ruby
33
star
51

openstack-chef-repo

DEPRECATED: Chef Repository for OpenStack
Ruby
32
star
52

cookbook-guide

Chef Technical Alliances guide for writing quality cookbooks
Ruby
31
star
53

tar

Deprecated: Chef cookbook for tar packages
Ruby
31
star
54

audit-cis

DEPRECATED: Recipes to perform chef audit mode check for CIS Benchmarks
Ruby
31
star
55

omnibus

Prepares a machine to be an Omnibus builder. โ”ฌโ”€โ”€โ”ฌโ—ก๏พ‰(ยฐ -ยฐ๏พ‰)
Ruby
28
star
56

libarchive

Deprecated: A library cookbook for manipulating archive files
Ruby
28
star
57

resource

DEPRECATED: Easier, More Powerful Chef Resources
27
star
58

chef-sugar

Ruby
27
star
59

ruby

DEPRECATED: Chef Cookbook for Managing Ruby from Packages
Ruby
27
star
60

locale

Chef cookbook to configure the system locale on Linux systems
Ruby
26
star
61

chef-server-webui

DEPRECATED: Web Interface to Open Source Chef Server 11
JavaScript
24
star
62

private-chef-administration

DEPRECATED: Private Chef Administration Guide
Python
24
star
63

bookshelf

DEPRECATED: Minimal S3 Clone
Erlang
24
star
64

opscode-agent

Opscode Agent, providing RESTful and AMQP access to Chef and Ohai
Ruby
23
star
65

pantry-chef-repo

A Chef Repository For Pantry
Shell
22
star
66

habitat

Chef Cookbook for Habitat
Ruby
22
star
67

chef-provisioning-vagrant

Vagrant provisioner for chef-provisioning
Ruby
22
star
68

microsoft_azure

Windows Azure Cookbook for Chef
Ruby
21
star
69

chef-init

PID1 for your Chef containers
Ruby
21
star
70

knife-opc

Knife plugin for managing Chef Server Organizations
Ruby
21
star
71

zsh

DEPRECATED: Development repository for Chef Cookbook zsh
Ruby
21
star
72

push-jobs-cookbook

Development repository for Chef Cookbook push-jobs
Ruby
21
star
73

chef-provisioning-azure

DEPRECATED: Azure driver for chef-provisioning!
Ruby
21
star
74

delivery-cluster

DEPRECATED: Deployment cookbook for standing up Delivery clusters using chef-provisioning.
Ruby
20
star
75

gunicorn

DEPRECATED: Development repository for Chef Cookbook gunicorn
Ruby
20
star
76

dsc

DEPRECATED: Preview of PowerShell Desired State Configuration (DSC) integration with the Chef DSL
Ruby
19
star
77

cis-el7-l1-hardening

Hardening cookbook for CIS Level 1 for RHEL 7 based operating systems
Ruby
19
star
78

logwatch

Development repository for Chef Cookbook logwatch
Ruby
19
star
79

ec-metal

Chef Provisioning-based tool for creating, managing and testing Enterprise Chef HA clusters
Ruby
19
star
80

inspec-vmware

InSpec VMware Resource Pack (Incubation)
Ruby
19
star
81

whitelist-node-attrs

Look here:
Ruby
18
star
82

java-quick-start

DEPRECATED: Chef Java Quick Start Guide
18
star
83

community-summits

Wikis to capture notes for Community Summits
18
star
84

whitelist-node-attrs-cookbook

DEPRECATED: Development repository for whitelist-node-attrs cookbook
Ruby
18
star
85

activemq

Development repository for activemq Chef Cookbook
Ruby
18
star
86

chef-server-cloudformation-templates

Collection of AWS Cloudformation templates for installing Chef Server 12 on EC2
17
star
87

php-quick-start

DEPRECATED: PHP quickstart guide for Chef
17
star
88

knife-eucalyptus

Chef knife plug-in for Eucalyptus
Ruby
16
star
89

lambda_ebs_snapshot

Terraform config for automatic EBS snapshots
HCL
16
star
90

knife-push

knife commands for Chef Push Jobs
Ruby
16
star
91

opscode-pushy-server

Chef Push Jobs Server
Erlang
16
star
92

chef-provisioning-ssh

Provision Machines Via SSH or WinRM Using Chef Provisioning
Ruby
15
star
93

automeck

Streamlines setting up and using meck-based mocks
Erlang
15
star
94

compat_resource

Cookbook to bring some features from future Chef to earlier versions
Ruby
15
star
95

chef-container

Official build definitions for Chef's Docker images
Ruby
14
star
96

chef_wm

DEPRECATED repository. Now lives in chef-server.
Erlang
14
star
97

opscode-omnibus

Deprecated: Omnibus packaging for Chef Server - Use Chef Server Instead
Ruby
14
star
98

win32-sound

A Ruby library for playing and controlling sounds on MS Windows.
Ruby
13
star
99

chef-pedant

DEPRECATED Integration Test Suite for Chef Sever - replaced with oc-chef-pedant
Ruby
13
star
100

chef-server-solo-install

Bootstrap a Chef Server via Chef Solo
Ruby
13
star