If we write multiple resources, we’d have to send that action to every one of them. Exiting pry will work, but then we are, of course, no longer in the pry session. This is not ideal, but hey, it’s not like we’re in chef-shell.

The chef-apply program runs in “solo mode.”

12

2.1.6 (#<Chef::Recipe>):0 > Chef::Config.solo
=> true

However, it may be useful to debug things through the Chef Server API. We will want to do two things. First, load a config file like .chef/knife.rb. We can verify the Chef Server we want is configured by checking Chef::Config[:chef_server_url].

I’m currently updating my vagrant cookbook, and adding ChefSpec coverage. Each of the different platform recipes results in slightly different resources to download the package file and install it. To support this, I have helper methods that calculate the download URI, the package name, and the SHA256 checksum based on the version of Vagrant (node['vagrant']['version']), and the platform (node['os'], node['platform_family']).

The outcomes I want to test are that for a given platform: the correct recipe is included, the correct file is downloaded, and the correct package resource installs the downloaded file. Those tests look like this (using Ubuntu/Debian example first):

123456789101112131415

it'includes the debian platform family recipe'doexpect(chef_run).toinclude_recipe('vagrant::debian')endit'downloads the package from the calculated URI'doexpect(chef_run).tocreate_remote_file('/var/tmp/vagrant.deb').with(source:'https://dl.bintray.com/mitchellh/vagrant/vagrant_1.88.88_x86_64.deb')endit'installs the downloaded package'doexpect(chef_run).toinstall_dpkg_package('vagrant').with(source:'/var/tmp/vagrant.deb')end

I’ve set the version attribute in the chef_run block for the ChefSpec run to 1.88.88 to ensure that it doesn’t use the value set in the attributes file, and then I can test this specifically in the source for the calculated URI, even if the attribute changes – hopefully Vagrant doesn’t have a 1.88.88 version some day ;).

The exception is happening when Chef loads the attributes file, and because the version is not valid. The solution here is to stub out the return value from vagrant_sha256sum. This can be anything at all really, because that specific attribute is to make sure we don’t have to re-download the package to compare its checksum on later Chef runs. In this cookbook, the helper methods are not namespaced under a module, they’re bare methods in libraries.helpers.rb. This poses somechallengeswhen tryingto stubthem in ChefSpec. I won’t rehash all the ways I attempted to get this to work, and instead focus on the final solution that got the tests passing:

When Chef loads cookbook attributes files, it is evaluating them in the context of a Chef::Node, so those library helper methods are sent to the Chef::Node object. Similarly, if this were inside a recipe, I would use Chef::Recipe, and if it were inside a resource (e.g., package), Chef::Resource.

I put this before block at the describe 'vagrant::default' level, not within any context blocks, so it will be done for each of the various per-platform tests. The results in my debian context are now:

As I indicated on Twitter earlier tonight, I’m working with the new Policyfile feature of ChefDK. While converting my personal systems’ repository to use Policyfile instead of roles, I found myself writing this Policyfile:

No big deal, but I found the repetition… redundant. Several of these cookbooks are fine floating on the latest version from Supermarket – everything but packages and users. So I thought, “wouldn’t it be great if entries in the run list were automatically added as dependencies?”

Then, I added chef-client-runit to the run list, but I didn’t add it as a cookbook entry, performed the chef update, and reran my chef provision command, and wound up with chef-client-runit being converged.

To illustrate this with a really simple example, I confirmed with zsh:

Earlier today, ChefDK 0.6.0 was released. In this post, I will illustrate a fairly simple walkthrough using Amazon EC2, based on information in the document. This example will include Policyfile use, too. Let’s get started.

I’m going to use Hosted Chef as my Chef Server. I already have my user API key and configuration in ~/.chef, and I’m going to rely on the automatic configuration detection in the chef command for that.

Generate a new repository using the chef generate command. Further commands run from this directory.

chef generate repo chefdk-provision-demo
cd chefdk-provision-demo

Generate a provision cookbook. This is the required name, and it must be in the current directory.

To break this down, first we get the ChefDK provisioning context that will pass in options to chef-provisioning. Then we tell chef-provisioning to use the AWS driver, and in the us-west-2 region. The options hash is used to setup the instance. We’re using Debian 8, which uses the admin user to log in, an SSH key that exists in the AWS region, the actual AMI, and finally the instance type. Then, we’re going to set the convergence options automatically from ChefDK. This is the important part that will ensure the node has the right run list.

The next step is to install the Policyfile. This generates the Policyfile.lock.json, and downloads the cookbooks to the cache, ~/.chefdk/cache/cookbooks. If this isn’t run, chef will complain, with a reminder to run it.

I’ve started working with the audit mode feature introduced in Chef version 12.1.0. Audit mode allows users to write custom rules (controls) in Chef recipes using new DSL helpers. In his ChefConf 2015 talk, “Compliance At Velocity,” James Casey goes into more of the background and reasoning for this. For now, I wanted to share a few tips with users who may be experimenting with this feature on their own, too.

This is the generated .kitchen.yml with client_rb added to the provisioner config. Note that we must use the Ruby symbol syntax for the config value, :audit_only. The other valid values for audit_mode are :enabled and :disabled. This will be translated to an actual Ruby symbol in the generated config file (/tmp/kitchen/client.rb):

1

audit_mode:audit_only

Next, let’s write a control rule to test. Since we’re using the default .kitchen.yml, which includes Ubuntu 12.04 and uses SSH to connect, we can assume that SSH is running, so port 22 is listening. The following control asserts this is true.

Cool! So we have asserted that the node complies with this control by default. But what does a failing control look like? Let’s write one. Since we’re working with SSH already, let’s use the SSHd configuration. By default in the Vagrant base box we’re using, root login is permitted, so this value is present:

1

PermitRootLoginyes

However, our security policy mandates that we set this to no, and we want to audit that.

When we have a failure, we’ll have contextual information about the failure, including the line number in the recipe where itwas found, and a stack trace (cut from the output here), in case more information is required for debugging. To fix the test, we can simply edit the config file to have the desired setting, or we can manage the file with Chef to set the value accordingly. Either way, after updating the file, the validation will pass, and all will be well.

We can put as many control_group and control blocks with the it validation rules as required to audit our policy. If we have many validations, it can be difficult to follow with all the output if there are failures. Chef’s audit mode is based on Serverspec, which is based on RSpec. We can use the filter_tag configuration feature of RSpec to only run the control blocks or it statements that we’re interested in debugging. To do this, we need an RSpec.configuration block within the control_group – due to the way that audit mode is implemented, we can’t do it outside of control_group.

This example is simple enough that this isn’t necessary, but if we were implementing audit mode checks for our entire security policy, that could be dozens or even hundreds of controls.

As of this writing, audit mode is still under development, and is considered an experimental feature. There will be further information, guides, and documentation about it coming to the Chef blog and docs site, and I’ll have a post coming soon with something I’m working on, so stay tuned!

One of my home projects while I’m on vacation this week is rebuilding my server with Fedora 21 (Server). In order to do this, I needed to add Fedora support to the runit cookbook, since I use runit for a number of services on my system. That’s really neither here nor there, as the topic of this blog post isn’t specific to Fedora, nor runit.

The topic is actually about an issue with transitive dependencies and how Chef dependency resolution works.

Here’s the scenario:

I run chef on my node

The runit cookbook is synchronized

An older version of the runit cookbook is downloaded

The new changes I expected were not made

WTFs ensue

So what happened?

The runit cookbook itself is updated to use Ian Meyer’s Package Cloud repository – at least, the version I want to use is, which is on GitHub. When I submitted the PR for adding this repository for RHEL platforms, Ian had not yet added Fedora packages. That’s okay because Fedora is not listed as supported in the cookbook. However, I wanted to use it, and figured folks in the community using Fedora Server might benefit too.

I digress. Ian pushed a Fedora package earlier today, so I added “fedora” to the various platform family conditionals, in the cookbook and opened the PR linked earlier. All was well in test kitchen. So I change my local repository’s Berksfile:

Then a quick berks update runit and berks upload runit, and I was in business.

Or so I thought. Enter scenario listed above. The problem is, that when I did the berks upload, it only uploaded runit. However in the latest runit cookbook from that branch, it also adds a dependency on Computology’s packagecloud cookbook, since it uses that to add the repository. When the runit cookbook is specified on the berks upload command, it doesn’t upload the transitive dependencies when the location is a git URI. This appears to be by design.

What happens in Chef is that the server solves the graph, seeing that the node needs the runit cookbook. But the latest version of the runit cookbook depends on packagecloud, which hasn’t yet been uploaded. So the dependency solver looks for the latest version of the runit cookbook that meets the constraint (none), and doesn’t have the packagecloud cookbook. Thus, I end up with runit version 1.5.18 on my node, but it fails to converge because it doesn’t have the changes required for Fedora, which are in 1.5.20.

The simple solution here is to upload the packagecloud cookbook. This can be done with berks upload packagecloud, as it does exist in the Berksfile.lock and has been cached in the berkshelf. Alternatively, berks upload will also upload the cookbook, as that operates on all cookbooks in the Berksfile.lock.

I hope this helps anyone who’s faced this issue with transitive dependencies when working on a cookbook “in development.”

As you may be aware, Chef 12.1.0 introduces a change to the chef_gem resource that prints out warning messages like this:

WARN: chef_gem[chef-vault] chef_gem compile_time installation is deprecated
WARN: chef_gem[chef-vault] Please set `compile_time false` on the resource to use the new behavior.
WARN: chef_gem[chef-vault] or set `compile_time true` on the resource if compile_time behavior is required.

These messages are just warnings, but if you’re installing a lot of gems in your recipes, you may be annoyed by the output. As the warning indicates, you can set compile_time true property. This doesn’t work on versions of Chef before 12.1, though:

This appears to get around the problem for most cases. However, if you’re using chef-sugar, you’ll note that until version 3.0.0, chef-sugar includes a compile_time DSL method that gets injected into Chef::Resource (and Chef::Recipe). This has been modified to at_compile_time in chef-sugar version 3.0.0 to work around Chef’s introduction of a compile_time method in the chef_gem resource. The simple thing to do is make sure that your chef-sugar gem/cookbook are updated to v3.0.1. However if that isn’t an option for some reason, you can use this conditional check:

Returns an array containing the names of the public and protected instance methods in the receiver. For a module, these are the public and protected methods; for a class, they are the instance (not singleton) methods. If the optional parameter is false, the methods of any ancestors are not included.

I am working on my presentation for ChefConf. I plan to have quite a lot of code samples. I’ve found the options for getting code samples with nice syntax highlight a lackluster endeavour, with various GUI editors like TextMate, Sublime, and Atom having “Copy as RTF” plugins, but none of them being easily customizable.

So I did a quick Google search and happened on a gist I hadn’t seen before. It describes the following steps:

Install Homebrew (done, I have that covered with Chef ;)).

Install “highlight” with brew install highlight.

Use highlight to transform the source code file to RTF and copy it to the clipboard.

Paste the clipboard into Keynote.app.

This isn’t much different than the other solutions, except one super cool thing I learned about highlight.

It has styles.

123

highlight -w
<OMG LIST OF EIGHTY TWO DIFFERENT STYLES!!!>

That’s right, at least at the time of this writing highlight has 82 different styles available. Including my favorite(s) solarized – both light and dark. Note that the --help output says that this option is deprecated in the version I’ve installed (3.18_1), but the styles are in /usr/local/Cellar/highlight/VERSION/share/themes.

Highlight knows the syntax highlighting for a lot of languages, these are in /usr/local/Cellar/highlight/VERSION/share/langDefs. For example I can get my Ruby recipe highlighted with this:

1

highlight -s solarized-light -O rtf recipes/client.rb | pbcopy

This will use Courier New as the font, and depending on the theme/style used, some of the highlighting may be bold or italic. This is easy enough to change in Keynote though.

For up to date documentation and information about highlight, visit the author’s page.

This quick tip is brought to you by my preparation for my ChefConf talk about using Chef Provisioning to build a Chef Server Cluster, which is based on my blog post about the same. In the blog post I used chef-zero as my Chef Server, but for the talk I’m using Hosted Chef.

In order for the Chef Provisioning recipe to work the provisioning node – the node that runs chef-client – needs to have the appropriate permissions to manage objects on the Chef Server. This is easy with chef-zero – there are no ACLs at all. However in Hosted Chef, like any regular Chef Server, the ACLs don’t allow nodes’ API clients to modify other nodes, or API clients.

Fortunately we can do all the work necessary using knife, with the knife-acl plugin. In this quick tip, I’ll create a group for provisioning nodes, and give that group the proper permissions for the Chef Provisioning recipe to create the machines’ nodes and clients.

First of all, I’m using ChefDK, and it’s my Ruby environment too, so install the gem:

1

chef gem install knife-acl

Next, use the knife group subcommand to create the new group. Groups are a number of users and/or API clients. By default, an organization on Hosted Chef will have admins, billing-admins, clients, and users. Let’s create provisioners now.

1

knife group create provisioners

The Role-based access control (RBAC) system in the Chef Server allows us to assign read, create, update, grant, and delete permissions to various objects in the organization. Containers are a special holder of other types of objects, in this case we need to add permissions for the clients and nodes containers. This is what allows the Chef Provisioning recipe’s machine resources to have their Chef objects created.

Next, we need the API client that will be used by the Chef Provisioning node to authenticate with the Chef Server, and the node needs to be created as well. By default the client will automatically have permissions for the node object that has the same name.

Finally, we need to put the new API client into the provisioners group that was created earlier. First we need to get a mapping of the actors in the organization. Then we can add the client to the group.

This maps users to their USAG and stores a list of clients. More information about this is in the knife-acl README

At this point, we have a node, with the private key in ~/.chef that can be used with the Chef Server to use Chef Provisioning’s machine resource. We can also perform additional tasks that require having a node object, such as create secrets as Chef Vault items:

Why does this happen?

The reason for this is because use_inline_resources tells Chef that in this provider, we’re using inline resources that will be added to their own run context, with their own resource collection. We don’t have access to the resource collection from the recipe. Even though the file[notified] resource exists from the recipe, it doesn’t actually get inherited in the provider’s run context, raising the error we saw before.

We can turn off use_inline_resources by removing it, and the custom resource will be configured:

Notice that the file[notified] resource wasn’t updated at the start of the run, when it was encountered in the recipe, but it was when notified by the log resource in the provider action, changing the content.

Use inline compile mode!

The use_inline_resources method in the lightweight provider DSL is strongly recommended. It makes it easier to send notifications from the custom resource itself to other resources in the recipe’s resource collection. Read more about the inline compile mode in the Chef docs.

Also, define the resources that you need to notify when you’re doing this in your provider’s actions. A common example is within a provider that writes configuration for a service, and needs to tell that service to restart.