Slide 1

Slide 1 text

Cookbook Refactoring A

Slide 2

Slide 2 text

Cookbook Refactoring ... and extracting logic into Rubygems A

Slide 3

Slide 3 text

sethvargo@opscode.com E b yz

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

We're Hiring!

Slide 6

Slide 6 text

We're Hiring! Colorado

Slide 7

Slide 7 text

New Branding We're Hiring!

Slide 8

Slide 8 text

U DO YOU SOMETIMES FEEL LIKE THIS

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

template '/etc/hosts' do owner 'root' group 'root' source 'etc/hosts' end recipes/default.rb

Slide 12

Slide 12 text

# This file is managed by Chef for "<%= node['fqdn'] %>" # Do NOT modify this file by hand. <%= node['ipaddress'] %> <%= node['fqdn'] %> 127.0.0.1! localhost <%= node['fqdn'] %> 255.255.255.255!broadcasthost ::1 localhost fe80::1%lo0! localhost templates/default/etc/hosts.erb

Slide 13

Slide 13 text

No content

Slide 14

Slide 14 text

default['etc']['hosts'] = [] unless node['etc']['hosts'] attributes/default.rb

Slide 15

Slide 15 text

# This file is managed by Chef for "<%= node['fqdn'] %>" # Do NOT modify this file by hand. <%= node['ipaddress'] %> <%= node['fqdn'] %> 127.0.0.1! localhost <%= node['fqdn'] %> 255.255.255.255!broadcasthost ::1 localhost fe80::1%lo0! localhost # Custom Entries <% node['etc']['hosts'].each do |h| -%> <%= h['ip'] %> <%= h['host'] %> <% end -%> templates/default/etc/hosts.erb

Slide 16

Slide 16 text

include_attribute 'hostsfile' default['etc']['hosts'] << { 'ip' => '1.2.3.4', 'host' => 'www.example.com' } other_cookbook/attributes/default.rb

Slide 17

Slide 17 text

node.default['etc']['hosts'] << { 'ip' => '1.2.3.4', 'host' => 'www.example.com' } other_cookbook/recipes/default.rb

Slide 18

Slide 18 text

default_attributes({ 'etc' => { 'hosts' => [ {'ip' => '1.2.3.4', 'host' => 'www.example.com'}, {'ip' => '4.5.6.7', 'host' => 'foo.example.com'} ] } }) roles/my_role.rb

Slide 19

Slide 19 text

{ "default_attributes": { "etc": { "hosts": [ {"ip": "1.2.3.4", "host": "www.example.com"}, {"ip": "4.5.6.7", "host": "foo.example.com"} ] } } } environments/production.json

Slide 20

Slide 20 text

No content

Slide 21

Slide 21 text

node.set['etc']['hosts'] = { ip: '7.8.9.0', host: 'bar.example.com' }) recipes/default.rb

Slide 22

Slide 22 text

No content

Slide 23

Slide 23 text

arr = [1,2,3] arr << 4 => [1,2,3,4] arr = 4 => 4

Slide 24

Slide 24 text

arr = [1,2,3] arr << 4 => [1,2,3,4] arr = 4 => 4 Not an Array

Slide 25

Slide 25 text

TODO: Add infographics # This file is managed by Chef for "www.myapp.com" # Do NOT modify this file by hand. 1.2.3.4 www.myapp.com 127.0.0.1! localhost www.myapp.com 255.255.255.255!broadcasthost ::1 localhost fe80::1%lo0! localhost # Custom Entries 1.2.3.4 www.example.com 4.5.6.7 foo.example.com 7.8.9.0 bar.example.com /etc/hosts

Slide 26

Slide 26 text

TODO: Add infographics # This file is managed by Chef for "www.myapp.com" # Do NOT modify this file by hand. 1.2.3.4 www.myapp.com 127.0.0.1! localhost www.myapp.com 255.255.255.255!broadcasthost ::1 localhost fe80::1%lo0! localhost # Custom Entries 7.8.9.0 bar.example.com /etc/hosts

Slide 27

Slide 27 text

Post Mortem

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

No content

Slide 30

Slide 30 text

<< =

Slide 31

Slide 31 text

<< = !=

Slide 32

Slide 32 text

Post Mortem Action Items 7

Slide 33

Slide 33 text

Monkey patch Chef to raise an exception when redefining that particular node attribute.

Slide 34

Slide 34 text

Monkey patch Chef to raise an exception when redefining that particular node attribute. t

Slide 35

Slide 35 text

Create a special cookbook that uses a threshold value and raises an exception if the size of the array doesn't "make sense".

Slide 36

Slide 36 text

Create a special cookbook that uses a threshold value and raises an exception if the size of the array doesn't "make sense". t

Slide 37

Slide 37 text

Move all entries to a data bag

Slide 38

Slide 38 text

Move all entries to a data bag u

Slide 39

Slide 39 text

Move all entries to a data bag 6 6 Add tests

Slide 40

Slide 40 text

Data Bags

Slide 41

Slide 41 text

[ "1.2.3.4 example.com www.example.com", "4.5.6.7 foo.example.com", "7.8.9.0 bar.example.com" ] data_bags/etc_hosts.json

Slide 42

Slide 42 text

hosts = data_bag('etc_hosts') template '/etc/hosts' do owner 'root' group 'root' source 'etc/hosts' variables( hosts: hosts ) end recipes/default.rb

Slide 43

Slide 43 text

# This file is managed by Chef for "<%= node['fqdn'] %>" # Do NOT modify this file by hand. <%= node['ipaddress'] %> <%= node['fqdn'] %> 127.0.0.1! localhost <%= node['fqdn'] %> 255.255.255.255!broadcasthost ::1 localhost fe80::1%lo0! localhost # Custom Entries <%= @hosts.join("\n") %> templates/default/etc/hosts.erb

Slide 44

Slide 44 text

Move all entries to a data bag 5 6 Add tests

Slide 45

Slide 45 text

require 'chefspec' spec/default_spec.rb

Slide 46

Slide 46 text

require 'chefspec' describe 'hostsfile::default' do end spec/default_spec.rb

Slide 47

Slide 47 text

require 'chefspec' describe 'hostsfile::default' do let(:hosts) { ['1.2.3.4 example.com', '4.5.6.7 bar.com'] } before do Chef::Recipe.any_instance.stub(:data_bag).with('etc_hosts').and_return(hosts) end end spec/default_spec.rb

Slide 48

Slide 48 text

require 'chefspec' describe 'hostsfile::default' do let(:hosts) { ['1.2.3.4 example.com', '4.5.6.7 bar.com'] } before do Chef::Recipe.any_instance.stub(:data_bag).with('etc_hosts').and_return(hosts) end let(:runner) { ChefSpec::ChefRunner.new.converge('hostsfile::default') } end spec/default_spec.rb

Slide 49

Slide 49 text

require 'chefspec' describe 'hostsfile::default' do let(:hosts) { ['1.2.3.4 example.com', '4.5.6.7 bar.com'] } before do Chef::Recipe.any_instance.stub(:data_bag).with('etc_hosts').and_return(hosts) end let(:runner) { ChefSpec::ChefRunner.new.converge('hostsfile::default') } it 'loads the data bag' do Chef::Recipe.any_instance.should_receive(:data_bag).with('etc_hosts') end end spec/default_spec.rb

Slide 50

Slide 50 text

require 'chefspec' describe 'hostsfile::default' do let(:hosts) { ['1.2.3.4 example.com', '4.5.6.7 bar.com'] } before do Chef::Recipe.any_instance.stub(:data_bag).with('etc_hosts').and_return(hosts) end let(:runner) { ChefSpec::ChefRunner.new.converge('hostsfile::default') } it 'loads the data bag' do Chef::Recipe.any_instance.should_receive(:data_bag).with('etc_hosts') end it 'creates the /etc/hosts template' do expect(runner).to create_template('/etc/hosts').with_content(hosts.join("\n")) end end spec/default_spec.rb

Slide 51

Slide 51 text

$ rspec cookbooks/hostsfile Running all specs

Slide 52

Slide 52 text

$ rspec cookbooks/hostsfile Running all specs ** Finished in 0.0003 seconds 2 examples, 0 failures

Slide 53

Slide 53 text

$ rspec cookbooks/hostsfile Running all specs ** Finished in 0.0003 seconds 2 examples, 0 failures Really Fucking Fast™

Slide 54

Slide 54 text

#winning

Slide 55

Slide 55 text

10,000 tests

Slide 56

Slide 56 text

28 seconds

Slide 57

Slide 57 text

#winning

Slide 58

Slide 58 text

⏳ ⏳

Slide 59

Slide 59 text

No content

Slide 60

Slide 60 text

No content

Slide 61

Slide 61 text

hosts = data_bag('etc_hosts') hosts << search(:node, 'role:mongo_master').first.tap do |n| "#{n['ip_address']} #{n['fqdn']}" end template '/etc/hosts' do owner 'root' group 'root' source 'etc/hosts' variables( hosts: hosts ) end recipes/default.rb

Slide 62

Slide 62 text

hosts = data_bag('etc_hosts') hosts << search(:node, 'role:mongo_master').first.tap do |n| "#{n['ip_address']} #{n['fqdn']}" end hosts << search(:node, 'role:mysql_master').first.tap do |n| "#{n['ip_address']} #{n['fqdn']}" end hosts << search(:node, 'role:redis_master').first.tap do |n| "#{n['ip_address']} #{n['fqdn']}" end template '/etc/hosts' do owner 'root' group 'root' recipes/default.rb

Slide 63

Slide 63 text

LWRPs

Slide 64

Slide 64 text

# List of all actions supported by the provider actions :create, :create_if_missing, :update, :remove # Make create the default action default_action :create # Required attributes attribute :ip_address, kind_of: String, name_attribute: true, required: true attribute :hostname, kind_of: String # Optional attributes attribute :aliases, kind_of: Array attribute :comment, kind_of: String resources/entry.rb

Slide 65

Slide 65 text

action :create do ::Chef::Util::FileEdit.search_file_delete_line(entry) ::Chef::Util::FileEdit.insert_line_after_match(/\n/, entry) end protected def entry [new_resource.ip_address, new_resource.hostname, new_resource.aliases.join(' ')].compact.join(' ').squeeze(' ') end providers/entry.rb

Slide 66

Slide 66 text

hostsfile_entry '1.2.3.4' do hostname 'example.com' end providers/entry.rb

Slide 67

Slide 67 text

Chef::Util::FileEdit is slow

Slide 68

Slide 68 text

Re-writing the file on each run

Slide 69

Slide 69 text

Provider kept growning

Slide 70

Slide 70 text

Untested

Slide 71

Slide 71 text

Refactor A

Slide 72

Slide 72 text

Move to pure Ruby classes

Slide 73

Slide 73 text

Ditch Chef::Util::FileEdit and manage the entire file

Slide 74

Slide 74 text

Only implement Ruby classes in the Provider (logic-less Provider)

Slide 75

Slide 75 text

Test the Ruby code

Slide 76

Slide 76 text

Test that the Provider implements the proper Ruby classes

Slide 77

Slide 77 text

TODO: Add infographics class Entry attr_accessor :ip_address, :hostname, :aliases, :comment def initialize(options = {}) if options[:ip_address].nil? || options[:hostname].nil? raise ':ip_address and :hostname are both required options' end @ip_address = options[:ip_address] @hostname = options[:hostname] @aliases = [options[:aliases]].flatten @comment = options[:comment] end # ... end libraries/entry.rb

Slide 78

Slide 78 text

TODO: Add infographics class Manipulator def initialize contents = ::File.readlines(hostsfile_path) @entries = contents.collect do |line| Entry.parse(line) unless line.strip.nil? || line.strip.empty? end.compact end def add(options = {}) @entries << Entry.new( ip_address: options[:ip_address], hostname: options[:hostname], aliases: options[:aliases], comment: options[:comment] ) end end libraries/manipulator.rb

Slide 79

Slide 79 text

# Creates a new hosts file entry. If an entry already exists, it # will be overwritten by this one. action :create do hostsfile.add( ip_address: new_resource.ip_address, hostname: new_resource.hostname, aliases: new_resource.aliases, comment: new_resource.comment ) new_resource.updated_by_last_action(true) if hostsfile.save end providers/entry.rb

Slide 80

Slide 80 text

No content

Slide 81

Slide 81 text

No content

Slide 82

Slide 82 text

RSpec

Slide 83

Slide 83 text

TODO: Add infographics describe Entry do describe '.initialize' do subject { Entry.new(ip_address: '2.3.4.5', hostname: 'www.example.com', aliases: ['foo', 'bar'], comment: 'This is a comment!', priority: 100) } it 'raises an exception if :ip_address is missing' do expect { Entry.new(hostname: 'www.example.com') }.to raise_error(ArgumentError) end it 'sets the ip_address' do expect(subject.ip_address).to eq('2.3.4.5') end end spec/entry_spec.rb

Slide 84

Slide 84 text

No content

Slide 85

Slide 85 text

Chef Spec

Slide 86

Slide 86 text

Chef Spec

Slide 87

Slide 87 text

TODO: Add infographics describe 'hostsfile lwrp' do let(:manipulator) { double('manipulator') } before do Manipulator.stub(:new).and_return(manipulator) Manipulator.should_receive(:new).with(kind_of(Chef::Node)) .and_return(manipulator) manipulator.should_receive(:save!) end let(:chef_run) { ChefSpec::ChefRunner.new( cookbook_path: $cookbook_paths, step_into: ['hostsfile_entry'] ) } spec/default_spec.rb

Slide 88

Slide 88 text

TODO: Add infographics context 'actions' do describe ':create' do it 'adds the entry' do manipulator.should_receive(:add).with({ ip_address: '2.3.4.5', hostname: 'www.example.com', aliases: nil, comment: nil, priority: nil }) chef_run.converge('fake::create') end end end end

Slide 89

Slide 89 text

Open It

Slide 90

Slide 90 text

No content

Slide 91

Slide 91 text

No content

Slide 92

Slide 92 text

No content

Slide 93

Slide 93 text

No content

Slide 94

Slide 94 text

No content

Slide 95

Slide 95 text

Gem It

Slide 96

Slide 96 text

$ bundle gem hostsfile

Slide 97

Slide 97 text

$ bundle gem hostsfile create hostsfile/Gemfile create hostsfile/Rakefile create hostsfile/LICENSE.txt create hostsfile/README.md create hostsfile/.gitignore create hostsfile/hostsfile.gemspec create hostsfile/lib/hostsfile.rb create hostsfile/lib/hostsfile/version.rb Initializating git repo in ~Development/hostsfile

Slide 98

Slide 98 text

entry.rb manipulator.rb 9 9

Slide 99

Slide 99 text

9

Slide 100

Slide 100 text

9 ?

Slide 101

Slide 101 text

chef_gem 'hostsfile' recipes/default.rb

Slide 102

Slide 102 text

require 'hostsfile' providers/entry.rb

Slide 103

Slide 103 text

In another cookbook...

Slide 104

Slide 104 text

# ... depends 'hostsfile' other_cookbook/metadata.rb

Slide 105

Slide 105 text

{ "run_list": [ "recipe[hostsfile]" ] } www.myapp.com (Chef Node)

Slide 106

Slide 106 text

No content

Slide 107

Slide 107 text

No content

Slide 108

Slide 108 text

No content

Slide 109

Slide 109 text

Thank You z