Making changes at speed while feeling confident you didn’t just break
the world
§ Understand how your cookbook development workflow should follow
mature software development practices
§ Learn how to inject data and attributes
§ Use code correctness tools to
− enforce a consistent style
− avoid common pitfalls, enforce operational standards
§ Write unit tests to prove correctness of cookbooks
§ Write functional tests to prove overall purpose of cookbook
Code Correctness
Rubocop - http://batsov.com/rubocop/ Foodcritic - http://acrmp.github.io/foodcritic/
Rubocop example
$ cd cookbooks/gapMetrics/!
$ rubocop!
warning: parser/current is loading parser/ruby21, which recognizes!
warning: 2.1.7-compliant syntax, but you are running 2.1.5.!
Inspecting 20 files!
CCCCCCWWCCCCCCW.WCCC!
!
Offenses:!
!
Berksfile:1:1: C: Missing space after #.!
#site :opscode!
^^^^^^^^^^^^^^!
...!
recipes/xpolog.rb:11:3: C: Inconsistent indentation detected.!
authorized_keys_for 'xpolog'!
^^^^^^^^^^^^^^^^^^^^^^^^^^^^!
recipes/xpolog.rb:11:31: C: Final newline missing.!
authorized_keys_for 'xpolog'!
!!
20 files inspected, 384 offenses detected
Rubocop resources
§ Marks your code against the style guide
− https://github.com/bbatsov/ruby-style-guide
§ Can automatically fix some errors
§ You can choose rules to ignore, create new ones
or override defaults in .rubocop.yml
https://docs.chef.io/rubocop.html
Lab: Rubocop your repos cookbook
§ Let’s use rubocop to fix up the repos cookbook
§ Remember, rubocop works from the cookbook of
the current directory
Lab – rubocop - style advice on repos
cookbook
$ cd cookbooks/repos!
$ rubocop!
$ rubocop!
Inspecting 7 files!
..C....!
!
Offenses:!
!
recipes/default.rb:6:9: C: Prefer single-quoted strings when
you don't need string interpolation or special symbols.!
execute "yum_clean" do!
^^^^^^^^^^^!
recipes/default.rb:7:11: C: Prefer single-quoted strings
when you don't need string interpolation or special symbols.!
command "/usr/bin/yum clean all && /usr/bin/yum makecache"!
Lab – rubocop – fix an issue
default.rb
#cookbook Name:: repos
#Recipe:: default
#
#Copyright (c) 2015 The Authors
execute 'yum_clean' do
command "/usr/bin/yum clean all &&
action :nothing
end
Lab - rubocop – rerun
rubocop
Inspecting 7 files
..C....
Offenses:
recipes/default.rb:7:11: C: Prefer single-quoted strings
when you don't need string interpolation or special symbols.
command "/usr/bin/yum clean all && /usr/bin/yum makecache"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
recipes/default.rb:19:7: C: Use the new Ruby 1.9 hash
syntax.
:id => repo['id'],
^^^^^^
Foodcritic example
$ foodcritic .!
FC001: Use strings in preference to symbols to access node attributes: ./attributes/
graphite.rb:28!
FC002: Avoid string interpolation where not required: ./recipes/relay.rb:78!
FC007: Ensure recipe dependencies are reflected in cookbook metadata: ./recipes/
_pre_setup.rb:34!
$ !
$ foodcritic -h!
foodcritic [cookbook_paths]!
-t, --tags TAGS Check against (or exclude ~) rules with the specified
tags.!
-f, --epic-fail TAGS Fail the build based on tags. Use 'any' to fail on
all warnings.!
-c, --chef-version VERSION Only check against rules valid for this version of
Chef.!
-B, --cookbook-path PATH Cookbook path(s) to check.!
-C, --[no-]context Show lines matched against rather than the default
summary.!
-E, --environment-path PATH Environment path(s) to check.!
-I, --include PATH Additional rule file path(s) to load.!
-G, --search-gems Search rubygems for rule files with the path
foodcritic/rules/**/*.rb!
-R, --role-path PATH Role path(s) to check.!
-S, --search-grammar PATH Specify grammar to use when validating search syntax.!
-V, --version Display the foodcritic version.!
-X, --exclude PATH Exclude path(s) from being linted.!
Foodcritic resources
http://acrmp.github.io/foodcritic/
Also, look for great production-related catches from Etsy:
https://github.com/etsy/foodcritic-rules
§ Catch packages with an :upgrade action and no specific version
§ Notice dev resources being called from prod
§ Find execute resources with no metaparameters or action :ignore
Lab – Foodcritic
§ Let’s use Foodcritic to check our cookbook
§ Boring standard rules are OK (for now)
Lab – Foodcritic – check the repos
cookbook
$ foodcritic .
FC003: Check whether you are running with chef server before
using server-specific features: ./recipes/default.rb:11
Lab – Foodcritic – rerun, ignoring that rule
$ foodcritic . –tags ~FC003
$ echo $?
0
Lab – Foodcritic - Success
§ We used foodcritic to statically check for code
problems.
§ We determined that the rule was not applicable
for our situation at The Gap
§ We re-ran foodcritic, telling it to ignore that class
of warnings and our cookbook passes.
Unit tests – ChefSpec (an extension of rspec)
ChefSpec simulates the convergence of resources on a node
§ It’s fast(er)! Runs in memory, does not actually create the node or
run chef-client
§ Can show you what percent of your code is “covered” by tests
§ chef cookbook generate command automatically generated the basic
tests:
spec/unit/recipes/default_spec.rb/spec_helper.rb
Unit Tests - ChefSpec – default files
The most basic test is autogenerated for you
default_spec.rb
#Cookbook Name:: repos
# Spec:: default
#
# Copyright (c) 2015 The Authors, All Rights Reserved
require 'spec_helper'
describe 'repos::default' do
context 'When all attributes are default, on an unspecified platform' do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new
runner.converge(described_recipe)
end
it 'converges successfully' do
chef_run # This should not raise an error
end
end
end
Unit Tests – ChefSpec – initial run
Does the repos cookbook pass ChefSpec?
$ rspec --format doc
repos::default
When all attributes are default, on an unspecified platform
=============================================================================
===
Recipe Compile Error in
...
Net::HTTPServerException
404 "Not Found “
...
10:
11>> repos = search('repos', '*:*')
12: repos.each do |repo|
13: template "/etc/yum.repos.d/#{repo['id']}.repo" do
Unit Tests – ChefSpec – why did that fail?
§ ChefSpec runs without a server.
§ Our repos cookbook requires databags to search
§ We didn’t provide any data for that search
− search bombed out with a 404
Unit Tests – ChefSpec – mysite cookbook
# Copyright (c) 2015 The authors, All Rights Reserved.
require 'spec helper'
at_exit { ChefSpec::Coverage.report! }
describe 'my site::default' do
context 'when all attributes are default, on an unspecified platform' do
let(:chef_run) do
runner = ChefSpec::ServerRunner.new
runner.converge(described_recipe)
end
it 'converges successfully' do
chef_run #This should not raise an error
end
it 'installs httpd' do
expect(chef_run).to install_package('httpd')
end
Unit Tests – ChefSpec – success!
rspec --format doc
mysite::default!
When all attributes are default, on an unspecified platform!
converges successfully!
installs httpd!
!
Finished in 0.53351 seconds (files took 17.3 seconds to load)!
2 examples, 0 failures!
!!
ChefSpec Coverage report generated...!
!
Total Resources: 3!
Touched Resources: 1!
Touch Coverage: 33.33%!
!
Untouched Resources:!
!
service[httpd] mysite/recipes/default.rb:9!
cookbook_file[/var/www/html/index.html] mysite/recipes/default.rb:14!
Unit tests – ChefSpec (an extension of rspec)
rspec in general can mock objects or stub apis
# sadly, webmock wasn't able to intercept whatever chef users for http calls
# gotta stub the manage_objectOperation on L54 in getValue.rb
fakeUtil = Class.new
stub_const("knifeManage::Utils", fakeUtil)
allow(fakeUtil).to receive(:manage_objectOperation) do | delete_objs,update_objs,file
expect(delete_objs).
to eq(%w[data_bags/nagios_networkdevices/s03894rtr1.json
data_bags/nagios_networkdevices/s03694rtr1.json
data_bags/ nagios_networkdevices/s03794rtr1.json
expect(update_objs).
to eq(%w[ data_bags/nagios_networkdevices/s07224rtr1.json
data_bags/nagios_networkdevices/s07224rtr1.json
data_bags/nagios_networkdevices/s07224rtr1.json
data_bags/nagios_networkdevices/s07224rtr1.json ])
expect(file).to eq ('data/dullknife.rb')
end
data_bags/nagios_networkdevices/s07224rtr1.json
data_bags/nagios_networkdevices/s07224rtr1.json ])
expect(file).to eq ('data/dullknife.rb')
end
ChefSpec and rspec resources
§ https://docs.chef.io/chefspec.html
§ http://betterspecs.org/
Functional testing
§ Identify the function or purpose of the cookbook
§ Create input data
§ Expect output
§ Create and execute tests
§ Verify output
Functional Tests – ServerSpec - Intro
§ ServerSpec is way, way more powerful
§ ServerSpec is way, way slower
§ Actually creates the instance and runs tests against the running
machine.
− Check that ports are listening
− Check that apps actually start up
− Check that network services return actual values
− Check contents of files
Functional Tests – ServerSpec - Locations
test/integration/default/serverspec/default_spec.rb/helper/serverspec/spec_helper.rb
Functional Tests – ServerSpec - Defaults
default_spec.rb
require 'spec_helper'
describe 'repos::default' do
# Serverspec examples can be found at
# http://serverspec.org/resource_types.html
it 'does something' do
skip 'Replace this with meaningful tests'
end
end
Functional Tests – ServerSpec – replace
tests
require 'spec_helper'
describe 'gap site' do
it 'responds on port 80' do
expect(port 80).to be_listening 'tcp'
end
end
describe 'old navy site' do
it 'responds on port 81' do
expect(port 81). to be_listening 'tcp'
end
Functional Tests – ServerSpec – run tests
kitchen verify
gap site
responds on port 80
old navy site
responds on port 81 (FAILED - 1)
Functional Tests – adding attributes
§ You can force – inject test attributes into ServerSpec via test kitchen.
§ Look at the bottom of our .kitchen.yml
suites :
- name: default
run_list:
- recipe[mysite::default]
attributes:
Review
§ What tool would we use to ensure consistent cookbook and ruby style?
§ What tool would we use to find common errors in cookbooks?
§ What are two ways to insert attributes and test data into our test
runs?
§ What are the differences between ChefSpec and ServerSpec
well written.Keep sharing
ReplyDeleteDevops Online Course