introduction to chef · windows server 2012r2 the system has chefdk (0.3.5), git, and sublime text,...
TRANSCRIPT
Introduction to Chef Managing Windows
Ramya Kailas Solutions Engineer
Galen Emery Automation Engineer
Franklin Webber
DEVICE=C:\Windows\HIMEM.SYS DOS=HIGH,UMB DEVICE=C:\Windows\EMM386.EXE NOEMS
Trainer
Introduce Yourselves Name
Current Job or Role
Previous Job or Role
5
Introduce Yourselves Name
Experience with Windows
Experience with Configuration Management
6
Introduce Yourselves Name
What You are Getting Out of this Conference?
7
Agenda
Our Expectations You will leave this workshop with a basic understanding Chef's core components, prepare you mentally for ChefConf, and ensure you have a workstation with all necessary tools installed.
A Taste of Chef Chef is a large set of tools that are able to be used on multiple platforms and in numerous configurations. We will have time to only explore some of its most fundamental pieces.
The Big Picture To ensure you are going to have an amazing learning experience during the conference we will need to move away from a hands-on approach to ensure we talk about tools and workflows that simply cannot fit inside this brief workshop.
Ask Me Anything (AMA) All of us are coming here with unique experiences and from unique teams that are using Chef in unique ways. It is important that we answer your questions and set you on the path to find more.
InstallFest Near the close of the workshop we will assist those needing assistance with the installation of the Chef tools on workstations.
Introductions Getting a Workstation Using Resources Building Cookbooks
Ask Me Anything (AMA) Including Node Attributes Templates The Big Picture InstallFest
Morning Afternoon
Getting a Workstation
Using a Cloud Workstation To ensure the "smoothest" setup experience we will be using a virtual machine with all the necessary tools installed.
What About My Workstation? At the end of the workshop we will have an InstallFest! During that time we will install all the necessary tools on your workstation and troubleshoot any installation issues you may experience.
OBJECTIVE:
Getting Your Workstation
q Visit http://bit.ly/chefworkstation q Enter an email address q Enter the class passphrase "learn chef with me" q Click on View VM or setup Remote Desktop Client
"Let's all hope the WiFi holds up to the onslaught." – Conference Attendee
Windows Server 2012R2 The system has ChefDK (0.3.5), Git, and Sublime Text, Putty, and other tools installed. We will be writing Chef code on this system and applying it directly to the system.*
Resources Chef's Fundamental Building Blocks
Welcome! A file is an example of a resource. A resource describes some piece of infrastructure, such as a file, a template, or a package.
What is chef-apply? An executable program that allows you to work with resources and recipe files.
LOCAL
Usage: chef-apply [RECIPE_FILE] [-e RECIPE_TEXT] [-s]
--[no-]color Use colored output, defaults to enabled
-e, --execute RECIPE_TEXT Execute resources supplied in a string
-l, --log_level LEVEL Set the log level (debug, info, warn, error, fatal)
-s, --stdin Execute resources read from STDIN
-v, --version Show chef version
-W, --why-run Enable whyrun mode
-h, --help Show this message
What can chef-apply do? PS > chef-apply --help
What is a recipe file? A recipe file is a ruby file that is mostly a collection of resources. It is a fundamental configuration element within Chef.
Resources A resource is a statement of configuration policy. It describes the desired state of an element of your infrastructure, along with the steps needed to bring that item to the desired state. Each resource statement includes the resource type (such as …
http://docs.chef.io/chef/resources.html
Example: File file 'C:\autoexec.bat' do
content 'DOS=HIGH,UMB'
action :create
end
The file name 'C:\autoexec.bat' is created with content 'DOS=HIGH,UMB'
http://docs.chef.io/chef/resources.html#file
Example: File file 'C:\config.sys.bak' do
action :delete
end
The file name 'c:\config.sys.bak' is deleted.
http://docs.chef.io/chef/resources.html#file
Example: Directory directory 'C:\games' do
action :create
end
The directory name 'C:\games' is created.
http://docs.chef.io/chef/resources.html#directory
Example: Batch batch 'echo system vars' do
code 'echo %TEMP% %SYSTEMDRIVE% %PATH% %WINDIR%'
action :run
end
The batch name 'echo system vars' is run with the code 'echo %TEMP% %SYSTEMDRIVE% %PATH% %WINDIR%'.
http://docs.chef.io/chef/resources.html#batch
Example: Powershell-Script powershell_script 'Install IIS' do
code 'Add-WindowsFeature Web-Server'
action :run
end
The powershell_script name 'Install IIS' is run with the code 'Add-WindowsFeature Web-Server'.
http://docs.chef.io/chef/resources.html#powershell-script
Resources A resource is a statement of configuration policy. It describes the desired state of an element of your infrastructure, along with the steps needed to bring that item to the desired state. Each resource statement includes the resource type (such as …
http://docs.chef.io/chef/resources.html
OBJECTIVE:
Managing an INI file
1. Create a directory to do work 2. Create a recipe file 3. Add a file resource 4. Use chef-apply to execute the recipe file
Let's create a recipe file, add a resource, and then apply it to our system.
LOCAL
Set up your working directory PS > mkdir ~\chef-repo
LOCAL
Change into your working directory PS > cd ~\chef-repo
Creating a recipe file named 'hello.rb'
file 'C:\Users\Administrator\chef-repo\settings.ini' do
content 'greeting=hello world'
action :create
end
~\chef-repo\hello.rb
LOCAL
Usage: chef-apply [RECIPE_FILE] [-e RECIPE_TEXT] [-s]
--[no-]color Use colored output, defaults to enabled
-e, --execute RECIPE_TEXT Execute resources supplied in a string
-l, --log_level LEVEL Set the log level (debug, info, warn, error, fatal)
-s, --stdin Execute resources read from STDIN
-v, --version Show chef version
-W, --why-run Enable whyrun mode
-h, --help Show this message
What does chef-apply do again? PS > chef-apply --help
LOCAL
Applying the hello recipe file PS > chef-apply hello.rb
OBJECTIVE:
Creating an INI file
ü Create a directory to do work ü Create a recipe file ü Add a file resource ü Use chef-apply to execute the recipe file
Let's create a recipe file, add a resource, and then apply it to our system.
Applying a recipe? What happened when we applied the recipe?
Test and Repair What happens when I run the command again?
Test and Repair What would happen if you (or someone else) removed that file?
Test and Repair What would happen if you (or someone else) modified that file?
Test and Repair chef-apply takes action only when it needs to. Think of it as test and repair. Chef looks at the current state of each resource and takes action only when that resource is out of policy.
Yes No Is Resource in desired state?
(test)
Do Nothing Bring resource to desired state (repair)
No Is Resource in desired state?
(test)
Do Nothing Bring resource to desired state (repair)
Yes
Resource Definition file "hello.txt" do source "Hello, world!" action :create end
The TYPE named NAME should be ACTION'd with ATTRIBUTES
Resource Definition file "hello.txt" do source "Hello, world!" action :create end
The TYPE named NAME should be ACTION'd with ATTRIBUTES
Resource Definition file "hello.txt" do source "Hello, world!" action :create end
The TYPE named NAME should be ACTION'd with ATTRIBUTES
Resource Definition file "hello.txt" do source "Hello, world!" action :create end
The TYPE named NAME should be ACTION'd with ATTRIBUTES
Resource Definition file "hello.txt" do source "Hello, world!" action :create end
The TYPE named NAME should be ACTION'd with ATTRIBUTES
What is our Definition?
file 'C:\Users\Administrator\chef-repo\settings.ini' do content 'greeting=hello world' action :create end
The TYPE named NAME should be ACTION'd with ATTRIBUTES
What is our Resource Definition? file 'C:\Users\Administrator\chef-repo\settings.ini' do
content 'greeting=hello world'
action :create
end
The TYPE named NAME should be ACTION'd with ATTRIBUTES
What is our Resource Definition? file 'C:\Users\Administrator\chef-repo\settings.ini' do
content 'greeting=hello world'
action :create
end
The file named 'C:\Users\Administrator\chef-repo\settings.ini' should be created with content 'greeting=hello world'.
Deleting an INI file q Create a recipe file named 'goodbye.rb' q Add a file resource: The file named 'C:\Users\Administrator\chef-repo\settings.ini' is deleted.
q Use chef-apply to execute the recipe file
file 'C:\Users\Administrator\chef-repo\settings.ini' do
action :delete
end
~/chef-repo/goodbye.rb
LOCAL
Applying the goodbye recipe file PS > chef-apply goodbye.rb
LOCAL
False
Did we remove the settings.ini? PS > Test-Path settings.ini
Applying a recipe? What happened when we applied the recipe?
Test and Repair What happens when I run the command again?
Test and Repair What would happen if you (or someone else) creates that file?
Test and Repair How might we manage the permissions on a file?
OBJECTIVE:
What about a file's rights? How can we manage who has the rights to read, write, and modify a file?
Resources What are some examples of resources?
Resources What are the four major components of a resource definition?
Resources What is a resource?
Resources What do you think it mean for a resource to be a statement of configuration policy?
Discussion What questions can we answer for you?
• chef-apply • Resources • Resource - default actions and default attributes • Test and Repair
Break 10 minutes
Cookbooks Organizing our recipes
OBJECTIVE:
Versioning?
q Use chef to generate a cookbook to store our example recipe files q Copy our two recipes files into our new cookbook
How are we going to manage this file when I start to use it on more workstations?
What is chef? An executable program that allows you generate cookbooks and cookbook components.
LOCAL
Usage:
chef -h/--help
chef -v/--version
chef command [arguments...] [options...]
Available Commands:
exec Runs the command in context of the embedded ruby
gem Runs the `gem` command in context of the embedded ruby
generate Generate a new app, cookbook, or component
shell-init Initialize your shell to use ChefDK as your primary ruby
install Install cookbooks from a Policyfile and generate a locked cookbook set
update Updates a Policyfile.lock.json with latest run_list and cookbooks
What can chef do? PS > chef --help
Cookbooks A cookbook is the fundamental unit of configuration and policy distribution. Each cookbook defines a scenario, such as everything needed to install and configure MySQL, and then it contains all of the components that are required to support that scenario . . .
http://docs.chef.io/cookbooks.html
LOCAL
Usage: chef generate GENERATOR [options]
Available generators:
app Generate an application repo
cookbook Generate a single cookbook
recipe Generate a new recipe
attribute Generate an attributes file
template Generate a file template
file Generate a cookbook file
lwrp Generate a lightweight resource/provider
repo Generate a Chef policy repository
policyfile Generate a Policyfile for use with the install/push commands (experimental)
What can chef generate do? PS > chef generate --help
LOCAL
Usage: chef generate cookbook NAME [options]
-C, --copyright COPYRIGHT Name of the copyright holder - defaults to 'The Authors'
-m, --email EMAIL Email address of the author - defaults to 'you@exa...
-a, --generator-arg KEY=VALUE Use to set arbitrary attribute KEY to VALUE in the...
-I, --license LICENSE all_rights, apache2, mit, gplv2, gplv3 - defaults ...
-g GENERATOR_COOKBOOK_PATH, Use GENERATOR_COOKBOOK_PATH for the code_generator...
--generator-cookbook
What can chef generate cookbook do? PS > chef generate cookbook --help
LOCAL
Compiling Cookbooks...
Recipe: code_generator::cookbook
* directory[C:/Users/Administrator/example] action create
- create new directory C:/Users/Administrator/example
* template[C:/Users/Administrator/example/metadata.rb] action create_if_missing
- create new file C:/Users/Administrator/example/metadata.rb
- update content in file C:/Users/Administrator/example/metadata.rb from none to 283e7e
(diff output suppressed by config)
* template[C:/Users/Administrator/example/README.md] action create_if_missing
- create new file C:/Users/Administrator/example/README.md
- update content in file C:/Users/Administrator/example/README.md from none to 3659e2
(diff output suppressed by config)
* cookbook_file[C:/Users/Administrator/example/chefignore] action create
Lets create a cookbook! PS > chef generate cookbook example
LOCAL
Folder PATH listing
Volume serial number is 40EF-41B0
C:\USERS\ADMINISTRATOR\EXAMPLE
│ .gitignore
│ .kitchen.yml
│ Berksfile
│ chefignore
│ metadata.rb
│ README.md
│
└───recipes
default.rb
The cookbook has a README PS > tree example /F
README.md The description of the cookbook's features written in Markdown.
http://daringfireball.net/projects/markdown/syntax
LOCAL
Folder PATH listing
Volume serial number is 40EF-41B0
C:\USERS\ADMINISTRATOR\EXAMPLE
│ .gitignore
│ .kitchen.yml
│ Berksfile
│ chefignore
│ metadata.rb
│ README.md
│
└───recipes
default.rb
The cookbook has some metadata PS > tree example /F
metadata.rb Every cookbook requires a small amount of metadata. Metadata is stored in a file called metadata.rb that lives at the top of each cookbook’s directory.
http://docs.chef.io/config_rb_metadata.html
LOCAL
name 'example'
maintainer 'The Authors'
maintainer_email '[email protected]'
license 'all_rights'
description 'Installs/Configures example'
long_description 'Installs/Configures example'
version '0.1.0'
Lets take a look at the metadata PS > cat example\metadata.rb
LOCAL
Folder PATH listing
Volume serial number is 40EF-41B0
C:\USERS\ADMINISTRATOR\EXAMPLE
│ .gitignore
│ .kitchen.yml
│ Berksfile
│ chefignore
│ metadata.rb
│ README.md
│
└───recipes
default.rb
The cookbook has a folder for recipes PS > tree example /F
LOCAL
# Cookbook Name:: setup
# Recipe:: default
#
# Copyright (c) 2015 The Authors, All Rights Reserved.
The cookbook has a default recipe PS > cat example\recipes\default.rb
LOCAL
Copy the recipe into the cookbook PS > cp hello.rb example\recipes\hello.rb
LOCAL
Copy the recipe into the cookbook PS > cp goodbye.rb example\recipes\goodbye.rb
OBJECTIVE:
Versioning?
ü Use chef to generate a cookbook to store our example recipe files ü Copy our two recipes files into our new cookbook
How are we going to manage this file when I start to use it on more workstations?
OBJECTIVE:
Version Control Git is as good as any version control. Really anything is better than .bak!
q Add the example cookbook to version control
LOCAL
Move into the cookbook directory PS > cd example
LOCAL
Reinitialized existing Git repository in C:/Users/Administrator/example/.git/
Initialize it as a git repository PS > git init
LOCAL
Use git add to stage files to be committed. PS > git add .
LOCAL
On branch master
Initial commit
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: .gitignore
new file: .kitchen.yml
new file: Berksfile
new file: README.md
new file: chefignore
new file: metadata.rb
Use git status to view the staged files PS > git status
LOCAL
*** Please tell me who you are.
Run
git config --global user.email "[email protected]"
git config --global user.name "Your Name"
to set your account's default identity.
Omit --global to set the identity only in this repository.
fatal: unable to auto-detect email address (got 'Administrator@C3863237858.(none)')
Use git commit to save the staged changes PS > git commit -m "Initial example cookbook"
Git Not Know Who We Are! Git uses a file in the user's directory, named .gitconfig, that contains information about the author, git aliases, etc.
Create a .gitconfig q Create a recipe file named 'git.rb' q Add a file resource: The file named 'C:\Users\Administrator\.gitconfig' is created with the content: [user] email = [email protected] name = Your Name
q Use chef-apply to execute the recipe file
The git recipe file in the example cookbook
file 'C:\Users\Administrator\.gitconfig' do
content '
[user]
email = [email protected]
name = Your Name
'
action :create
end
~\example\recipes\git.rb
LOCAL
Applying the git recipe PS > chef-apply recipes\git.rb
LOCAL
9 files changed, 147 insertions(+)
create mode 100644 .gitignore
create mode 100644 .kitchen.yml
create mode 100644 Berksfile
create mode 100644 README.md
create mode 100644 chefignore
create mode 100644 metadata.rb
create mode 100644 recipes/default.rb
create mode 100644 recipes/goodbye.rb
create mode 100644 recipes/hello.rb
Use git commit to save the staged changes PS > git commit -m "Initial example cookbook"
OBJECTIVE:
Version Control Git is as good as any version control. Really anything is better than .bak!
ü Add the example cookbook to version control
LOCAL
Return to C:\Users\Administrator PS > cd ~
Setting up a Web Server q Write a recipe named 'iis.rb' with the policy:
The powershell_script named 'Install IIS' is run with the code
'Add-WindowsFeature Web-Server'.
The file named 'C:\inetpub\wwwroot\Default.htm' is created with
the content '<html><body><h1>Hello World!</h1></body></html>'
The service named 'w3svc' is started.
The service named 'w3svc' is enabled.
q Use chef-apply to apply the recipe q Visit http://localhost in Internet Explorer or Chrome
The recipe named iis that installs IIS
powershell_script 'Install IIS' do code 'Add-WindowsFeature Web-Server' end file 'c:\inetpub\wwwroot\Default.htm' do content '<html> <body> <h1>hello world</h1> </body> </html>' end service 'w3svc' do action [ :start, :enable ] end
~\iis.rb
LOCAL
Recipe: (chef-apply cookbook)::(chef-apply recipe)
* powershell_script[Install IIS] action run
- execute "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -File
"C:/Users/ADMINI~1/AppData/Local/Temp/2/chef-script20150329-2868-ojeldu.ps1"
* service[w3svc] action enable (up to date)
* service[w3svc] action start (up to date)
* file[c:\inetpub\wwwroot\Default.htm] action create
- create new file c:\inetpub\wwwroot\Default.htm
- update content in file c:\inetpub\wwwroot\Default.htm from none to 2914aa
--- c:\inetpub\wwwroot\Default.htm 2015-03-29 16:52:36.000000000 -0700
+++ C:/Users/ADMINI~1/AppData/Local/Temp/2/Default.htm20150329-2868-1uqbsdw 2015-03-29 16:52:36.000000000 -0700
@@ -1 +1,6 @@
Applying the iis recipe PS > chef-apply iis.rb
Recipes Belong in a Cookbook q Use chef generate to create a cookbook named 'web'. q Copy the recipe file named 'iis.rb' into the 'web' cookbook q Place the 'web' cookbook under version control
LOCAL
Compiling Cookbooks...
Recipe: code_generator::cookbook
* directory[C:/Users/Administrator/web] action create
- create new directory C:/Users/Administrator/web
* template[C:/Users/Administrator/web/metadata.rb] action create_if_missing
- create new file C:/Users/Administrator/web/metadata.rb
- update content in file C:/Users/Administrator/web/metadata.rb from none to a41ac6
(diff output suppressed by config)
* template[C:/Users/Administrator/web/README.md] action create_if_missing
- create new file C:/Users/Administrator/web/README.md
- update content in file C:/Users/Administrator/web/README.md from none to 05e1d0
(diff output suppressed by config)
* cookbook_file[C:/Users/Administrator/web/chefignore] action create
Lets create a cookbook! PS > chef generate cookbook web
LOCAL
Compiling Cookbooks...
Recipe: code_generator::cookbook
* directory[C:/Users/Administrator/web] action create
- create new directory C:/Users/Administrator/web
* template[C:/Users/Administrator/web/metadata.rb] action create_if_missing
- create new file C:/Users/Administrator/web/metadata.rb
- update content in file C:/Users/Administrator/web/metadata.rb from none to a41ac6
(diff output suppressed by config)
* template[C:/Users/Administrator/web/README.md] action create_if_missing
- create new file C:/Users/Administrator/web/README.md
- update content in file C:/Users/Administrator/web/README.md from none to 05e1d0
(diff output suppressed by config)
* cookbook_file[C:/Users/Administrator/web/chefignore] action create
Copy the iis recipe to the web cookbook PS > cp iis.rb web\recipes\iis.rb
LOCAL
Change into the web directory PS > cd web
LOCAL
Stage the files to be committed PS > git add .
LOCAL
[master (root-commit) e6a8147] Initial web cookbook
8 files changed, 164 insertions(+)
create mode 100644 .gitignore
create mode 100644 .kitchen.yml
create mode 100644 Berksfile
create mode 100644 README.md
create mode 100644 chefignore
create mode 100644 metadata.rb
create mode 100644 recipes/default.rb
create mode 100644 recipes/iis.rb
Commit the files with a message PS > git commit -m "Initial web cookbook"
Creating a Web Cookbook What questions can we answer for you?
Cookbooks How did we create a cookbook?
Cookbooks What are some of the components of a cookbook?
Cookbooks Why did we create a cookbook?
Cookbooks Why did we add our cookbooks to source control?
Discussion What questions can we answer for you?
• cookbooks • version control
Break 10 minutes
chef-client Applying recipes from cookbooks
chef-apply chef-apply is a great tool for applying resources (-e) and for individual recipes but it does not know how to apply a cookbook. This is why we need to specify the path to the recipe file. A better tool for applying cookbooks is called chef-client.
chef-client A chef-client is an agent that runs locally on every node that is under management by Chef. When a chef-client is run, it will perform all of the steps that are required to bring the node into the expected state, including…
https://docs.chef.io/chef_client.html
Using chef-client to locally apply recipes PS > chef-client --local-mode -r "recipe[example::hello]"
Apply the following recipes locally: • The 'hello' recipe from the 'example' cookbook
Using chef-client to locally apply recipes PS > chef-client --local-mode -r "recipe[web::iis]"
Apply the following recipes locally: • The 'iis' recipe from the 'web' cookbook
Using chef-client to locally apply recipes PS > chef-client --local-mode -r "recipe[example::hello],recipe[example::goodbye]"
Apply the following recipes locally:
• The 'hello' recipe from the 'example' cookbook • The 'goodbye' recipe from the 'example' cookbook
Using chef-client to locally apply recipes PS > chef-client --local-mode -r "recipe[example::hello],recipe[example::goodbye],recipe[web::iis]"
Apply the following recipes locally: • The 'hello' recipe from the 'example' cookbook • The 'goodbye' recipe from the 'example' cookbook • The 'iis' recipe from the 'web' cookbook
--local-mode chef-client's default mode attempts to contact a Chef Server and ask it for the recipes to run for the given node. We are overriding that behavior to have work in a local mode.
-r "recipe[COOKBOOK::RECIPE]"
In local mode we need to provide a list of recipes to apply to the system. This is called a run list. A run list is an ordered collection of recipes to execute. Each recipe in the run list must be addressed with the format recipe[COOKBOOK::RECIPE].
LOCAL
[2015-03-29T21:38:56-07:00] WARN: No config file found or specified on command line, using command line options.
[2015-03-29T21:38:56-07:00] WARN: No cookbooks directory found at or above current directory. Assuming C:/Users/Administrator.
Starting Chef Client, version 11.16.4
resolving cookbooks for run list: ["web::iis"]
================================================================================
Error Resolving Cookbooks for Run List:
================================================================================
Missing Cookbooks:
Applying the web::iis recipe locally PS > chef-client --local-mode -r "recipe[web::iis]"
LOCAL
Create a cookbooks directory PS > mkdir cookbooks
LOCAL
Move the example cookbook PS > mv example cookbooks
LOCAL
Move the web cookbook PS > mv web cookbooks
LOCAL
PS C:\Users\Administrator\temp> chef-client --local-mode -r "recipe[web::iis]"
[2015-03-29T21:38:08-07:00] WARN: No config file found or specified on command line, using command line options.
Starting Chef Client, version 11.16.4
resolving cookbooks for run list: ["web::iis"]
Synchronizing Cookbooks:
- web
Compiling Cookbooks...
Converging 3 resources
Recipe: web::iis
* powershell_script[Install IIS] action run
- execute "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -File
Applying the web::iis recipe locally PS > chef-client --local-mode -r "recipe[web::iis]"
chef-client What questions can we answer for you?
Details About the System Finding and display information about our system
OBJECTIVE:
Details about the Node
q Update the file contents, in the 'web' cookbook, to include system details q Use chef-client to apply the 'web::iis' recipe to the system q Update the 'web' cookbook's version q Commit our changes to source control
Displaying system details in our simple web page sounds useful.
Some Useful System Data • IP Address • Hostname • Memory • CPU - MHz
LOCAL
Windows IP Configuration
Ethernet adapter Ethernet:
Connection-specific DNS Suffix . :
IPv4 Address. . . . . . . . . . . : 10.160.23.210
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : 10.160.0.1
Tunnel adapter isatap.{0853D88A-9D54-4752-AF7B-0FF8C309CA39}:
Media State . . . . . . . . . . . : Media disconnected
Discover the ipaddress PS > ipconfig
Adding the ipaddress
file 'c:\inetpub\wwwroot\Default.htm' do
content '<html>
<body>
<h1>hello world</h1>
<h2>IPADDRESS: 10.160.23.210</h2>
</body>
</html>'
end
~\cookbooks\web\recipes\iis.rb
LOCAL
banana-stand
Discover the hostname PS > hostname
Adding the hostname
file 'c:\inetpub\wwwroot\Default.htm' do
content '<html>
<body>
<h1>hello world</h1>
<h2>IPADDRESS: 10.160.23.210</h2>
<h2>HOSTNAME: banana-stand</h2>
</body>
</html>'
end
~\cookbooks\web\recipes\iis.rb
LOCAL
TotalPhysicalMemory
4294430720
Discover the memory PS > wmic ComputerSystem get TotalPhysicalMemory
Adding the memory
file 'c:\inetpub\wwwroot\Default.htm' do
content '<html>
<body>
<h1>hello world</h1>
<h2>IPADDRESS: 10.160.23.210</h2>
<h2>HOSTNAME: banana-stand</h2>
<h2>MEMORY: 4294430720</h2>
</body>
</html>'
end
~\cookbooks\web\recipes\iis.rb
LOCAL
Name
Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz
Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz
Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz
Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz
Discover the cpu PS > wmic cpu get name
Adding the CPU
file 'c:\inetpub\wwwroot\Default.htm' do
content '<html>
<body>
<h1>hello world</h1>
<h2>IPADDRESS: 10.160.23.210</h2>
<h2>HOSTNAME: banana-stand</h2>
<h2>MEMORY: 4294430720</h2>
<h2>CPU: Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz</h2>
</body>
</html>'
end
~\cookbooks\web\recipes\iis.rb
Capturing System Data What are the limitations of the way we captured this data?
Capturing System Data How accurate will our MOTD be when we deploy it on other systems?
Capturing System Data Are these values we would want to capture in our tests?
Ohai! Ohai is a tool that is used to detect attributes on a node, and then provide these attributes to the chef-client at the start of every chef-client run.
http://docs.chef.io/ohai.html
LOCAL
...
"ohai_time": 1427682829.986746,
"etc": {
"passwd": {
},
"group": {
}
},
"current_user": "Administrator",
"root_group": "Administrators"
}
Ohai! PS > ohai
All About The System Ohai queries the operating system with a number of commands, similar to the ones demonstrated. The data is presented in JSON (JavaScript Object Notation).
http://docs.chef.io/ohai.html
ohai + chef-client = <3 chef-client and chef-apply automatically executes ohai and stores the data about the node in an object we can use within the recipes named node.
http://docs.chef.io/ohai.html
The node An attribute is a specific detail about a node, such as an IP address, a host name, a list of loaded kernel modules, the version(s) of available programming languages that are available, and so on.
http://docs.chef.io/nodes.html#attributes
node
ipaddress hostname memory
total
cpu
0
mhz
...
puts "IPADDRESS: #{node["ipaddress"]}"
IPADDRESS: 104.236.192.102
node
ipaddress hostname memory
total
cpu
0
mhz
...
puts "HOSTNAME: #{node["hostname"]}"
HOSTNAME: banana-stand
puts "Memory: #{node["memory"]["total"]} kB"
node
ipaddress hostname memory
total
cpu
0
mhz
...
MEMORY: 502272 kB
node
ipaddress hostname memory
total
cpu
0
mhz
...
https://github.com/chef/ohai/issues/515
puts "CPU: #{node["cpu"]["0"]["mhz"]} MHz"
node
ipaddress hostname memory
total
cpu
0
mhz
...
CPU: 2399.998 MHz
String Interpolation
apple_count = 4 puts "I have #{apple_count} apples"
I have 4 apples
http://en.wikipedia.org/wiki/String_interpolation#Ruby
String Interpolation
apple_count = 4 puts "I have #{apple_count} apples"
I have 4 apples
http://en.wikipedia.org/wiki/String_interpolation#Ruby
Your STRING MUST be DOUBLE QUOTED!
Double Quotes
file 'c:\inetpub\wwwroot\Default.htm' do
content "<html>
<body>
<h1>hello world</h1>
<h2>IPADDRESS: 10.160.23.210</h2>
<h2>HOSTNAME: banana-stand</h2>
<h2>MEMORY: 4294430720</h2>
<h2>CPU: Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz</h2>
</body>
</html>"
end
~\cookbooks\web\recipes\iis.rb
Using the node's ipaddress
file 'c:\inetpub\wwwroot\Default.htm' do
content "<html>
<body>
<h1>hello world</h1>
<h2>IPADDRESS: #{node['ipaddress']}</h2>
<h2>HOSTNAME: banana-stand</h2>
<h2>MEMORY: 4294430720</h2>
<h2>CPU: Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz</h2>
</body>
</html>"
end
~\cookbooks\web\recipes\iis.rb
Using the node's hostname
file 'c:\inetpub\wwwroot\Default.htm' do
content "<html>
<body>
<h1>hello world</h1>
<h2>IPADDRESS: #{node['ipaddress']}</h2>
<h2>HOSTNAME: #{node['hostname']}</h2>
<h2>MEMORY: 4294430720</h2>
<h2>CPU: Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz</h2>
</body>
</html>"
end
~\cookbooks\web\recipes\iis.rb
Let's not worry about the memory
file 'c:\inetpub\wwwroot\Default.htm' do
content "<html>
<body>
<h1>hello world</h1>
<h2>IPADDRESS: #{node['ipaddress']}</h2>
<h2>HOSTNAME: #{node['hostname']}</h2>
<h2>MEMORY: 4294430720</h2>
<h2>CPU: Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz</h2>
</body>
</html>"
end
~\cookbooks\web\recipes\iis.rb
Using the node's cpu
file 'c:\inetpub\wwwroot\Default.htm' do
content "<html>
<body>
<h1>hello world</h1>
<h2>IPADDRESS: #{node['ipaddress']}</h2>
<h2>HOSTNAME: #{node['hostname']}</h2>
<h2>CPU: #{node['cpu']['0']['mhz']}</h2>
</body>
</html>"
end
~\cookbooks\web\recipes\iis.rb
OBJECTIVE:
Details about the Node
ü Update the file contents, in the 'web' cookbook, to include system details q Use chef-client to apply the 'web::iis' recipe to the system q Update the 'web' cookbook's version q Commit our changes to source control
Displaying system details in our simple web page sounds useful.
LOCAL
[2015-03-29T20:26:54-07:00] WARN: No config file found or specified on command line, using command line options.
Starting Chef Client, version 11.16.4
resolving cookbooks for run list: ["web::iis"]
Synchronizing Cookbooks:
- web
Compiling Cookbooks...
Converging 3 resources
Recipe: web::iis
* powershell_script[Install IIS] action run
- execute "powershell.exe" -NoLogo -NonInteractive -NoProfile -ExecutionPolicy RemoteSigned -InputFormat None -Fil
"C:/Users/ADMINI~1/AppData/Local/Temp/2/chef-script20150329-804-1ybmv2u.ps1"
Applying the web::iis recipe PS > chef-client --local-mode -r "recipe[web::iis]"
Cookbook Versions A cookbook version represents a set of functionality that is different from the cookbook on which it is based. A version may exist for many reasons, such as ensuring the correct use of a third-party component, updating a bug fix, or adding an improvement.
https://docs.chef.io/cookbook_versions.html
Semantic Versions Given a version number MAJOR.MINOR.PATCH, increment the: • MAJOR version when you make incompatible API changes, • MINOR version when you add functionality in a backwards-
compatible manner, and • PATCH version when you make backwards-compatible bug fixes.
http://semver.org
Update the Cookbook Version
name 'web'
maintainer 'The Authors'
maintainer_email '[email protected]'
license 'all_rights'
description 'Installs/Configures web'
long_description 'Installs/Configures web'
version '0.2.0'
~\cookbooks\web\metadata.rb
Commit Your Work PS > cd web PS > git add . PS > git commit -m "Version 0.2.0 - Added Node Details to index page"
Node Attributes What questions can we answer for you?
String Interpolation What is the difference between single-quoted strings and double-quoted strings?
String Interpolation What is the sequence to escape out to execute ruby code in a double-quoted string?
String Interpolation What application collects all the data about the system?
Questions What questions can we answer for you? • Ohai • Node Object • Node Attributes
Policy and Data Separating the content from the policy for clarity
The current state of our web::iis recipe
powershell_script 'Install IIS' do code 'Add-WindowsFeature Web-Server' end
file 'c:\inetpub\wwwroot\Default.htm' do
content "<html> <body> <h1>hello world</h1>
<h2>IPADDRESS: #{node['ipaddress']}</h2> <h2>HOSTNAME: #{node['hostname']}</h2> <h2>CPU: #{node['cpu']['0']['mhz']}</h2>
</body> </html>"
end service 'w3svc' do
action [ :start, :enable ] end
~\cookbooks\web\recipes\iis.rb
OBJECTIVE:
Cleaner Recipes
q Decide which resource will help us address this issue
Adding the node attributes to the default page did make it harder to read the recipe.
Let's Check the Docs… Use the file resource to manage files directly on a node. Use the cookbook_file resource to copy a file from a cookbook’s /files directory. Use the template resource to create a file based on a template in a cookbook’s /templates directory. And use the remote_file resource to transfer a file to a node from a remote location.
https://docs.chef.io/resource_file.html
cookbook_file Use the cookbook_file resource to transfer files from a sub-directory of COOKBOOK_NAME/files/ to a specified path located on a host that is running the chef-client.
https://docs.chef.io/resource_cookbook_file.html
template A cookbook template is an Embedded Ruby (ERB) template that is used to generate files … Templates may contain Ruby expressions and statements and are a great way to... Use the template resource to add cookbook templates to recipes; place the corresponding Embedded Ruby (ERB) template in a cookbook’s /templates directory.
https://docs.chef.io/resource_template.html
remote_file Use the remote_file resource to transfer a file from a remote location using file specificity. This resource is similar to the file resource.
https://docs.chef.io/resource_remote_file.html
template To use a template, two things must happen: 1. A template resource must be added to a recipe 2. An Embedded Ruby (ERB) template must be added to a
cookbook
https://docs.chef.io/resource_template.html#using-templates
Choosing the Template Resource What questions can we answer for you?
OBJECTIVE:
Cleaner Recipes
q Create a template with chef generate q Define the contents of the ERB template q Change the file resource to the template resource in the 'web' cookbook
Adding the node attributes to the default page did make it harder to read the recipe.
What is chef? An executable program that allows you generate cookbooks and cookbook components.
LOCAL
Usage:
chef -h/--help
chef -v/--version
chef command [arguments...] [options...]
Available Commands:
exec Runs the command in context of the embedded ruby
gem Runs the `gem` command in context of the embedded ruby
generate Generate a new app, cookbook, or component
shell-init Initialize your shell to use ChefDK as your primary ruby
install Install cookbooks from a Policyfile and generate a locked cookbook set
update Updates a Policyfile.lock.json with latest run_list and cookbooks
What can chef do? PS > chef --help
LOCAL
Usage: chef generate GENERATOR [options]
Available generators:
app Generate an application repo
cookbook Generate a single cookbook
recipe Generate a new recipe
attribute Generate an attributes file
template Generate a file template
file Generate a cookbook file
lwrp Generate a lightweight resource/provider
repo Generate a Chef policy repository
policyfile Generate a Policyfile for use with the install/push commands (experimental)
What can chef generate do? PS > chef generate --help
LOCAL
Usage: chef generate template [path/to/cookbook] NAME [options]
-C, --copyright COPYRIGHT Name of the copyright holder - defaults to 'The Authors'
-m, --email EMAIL Email address of the author - defaults to ...
-a, --generator-arg KEY=VALUE Use to set arbitrary attribute KEY to VALUE in the
-I, --license LICENSE all_rights, apache2, mit, gplv2, gplv3 - defaults to
-s, --source SOURCE_FILE Copy content from SOURCE_FILE
-g GENERATOR_COOKBOOK_PATH, Use GENERATOR_COOKBOOK_PATH for the code_generator
--generator-cookbook
What can chef generate template do? PS > chef generate template --help
LOCAL
Compiling Cookbooks...
Recipe: code_generator::template
* directory[cookbooks/web/templates/default] action create
- create new directory cookbooks/web/templates/default
* template[cookbooks/web/templates/default/Default.htm.erb] action create
- create new file cookbooks/web/templates/default/Default.htm.erb
- update content in file cookbooks/web/templates/default/Default.htm.erb from none to e3b0c4
Use chef to generate a template PS > chef generate template cookbooks\web Default.htm.erb
OBJECTIVE:
Cleaner Recipes
ü Create a template with chef generate q Define the contents of the ERB template q Change the file resource to the template resource in the 'web' cookbook
Adding the node attributes to the default page did make it harder to read the recipe.
ERB An Embedded Ruby (ERB) template allows Ruby code to be embedded inside a text file within specially formatted tags. Ruby code can be embedded using expressions and statements.
https://docs.chef.io/templates.html#variables
Text within an ERB template <% if (50 + 50) == 100 %>
50 + 50 = <%= 50 + 50 %>
<% else %>
At some point all of MATH I learned in school changed.
<% end %>
Each ERB tag has a beginning tag and a matched ending tag.
Text within an ERB template <% if (50 + 50) == 100 %>
50 + 50 = <%= 50 + 50 %>
<% else %>
At some point all of MATH I learned in school changed.
<% end %>
Each ERB tag has a beginning tag and a matched ending tag.
Text within an ERB template <% if (50 + 50) == 100 %>
50 + 50 = <%= 50 + 50 %>
<% else %>
At some point all of MATH I learned in school changed.
<% end %>
Each ERB tag has a beginning tag and a matched ending tag.
Text within an ERB template <% if (50 + 50) == 100 %>
50 + 50 = <%= 50 + 50 %>
<% else %>
At some point all of MATH I learned in school changed.
<% end %>
Executes the ruby code within the brackets and do not display the result.
Text within an ERB template <% if (50 + 50) == 100 %>
50 + 50 = <%= 50 + 50 %>
<% else %>
At some point all of MATH I learned in school changed.
<% end %>
Executes the ruby code within the brackets and display the results.
The Angry Squid
<%=
Move our source to the template
<html>
<body>
<h1>hello world</h1>
<h2>IPADDRESS: #{node['ipaddress']}</h2>
<h2>HOSTNAME: #{node['hostname']}</h2>
<h2>CPU: #{node['cpu']['0']['mhz']}</h2>
</body>
</html>
~\cookbooks\web\templates\default\Default.htm.erb
Change String Interpolation to Angry Squid
<html>
<body>
<h1>hello world</h1>
<h2>IPADDRESS: <%= node['ipaddress'] %></h2>
<h2>HOSTNAME: <%= node['hostname'] %></h2>
<h2>CPU: <%= node['cpu']['0']['mhz'] %></h2>
</body>
</html>
~\cookbooks\web\templates\default\Default.htm.erb
OBJECTIVE:
Cleaner Recipes
ü Create a template with chef generate ü Define the contents of the ERB template q Change the file resource to the template resource in the 'web' cookbook
Adding the node attributes to the default page did make it harder to read the recipe.
Remove the existing content attribute
file 'c:\inetpub\wwwroot\Default.htm' do content "<html> <body> <h1>hello world</h1> <h2>IPADDRESS: #{node['ipaddress']}</h2> <h2>HOSTNAME: #{node['hostname']}</h2> <h2>CPU: #{node['cpu']['0']['mhz']}</h2> </body> </html>" action :create end
~\cookbooks\web\recipes\iis.rb
Change the file resource to a template
template 'c:\inetpub\wwwroot\Default.htm' do
action :create
end
~\cookbooks\web\recipes\iis.rb
Add a source attribute to the template
template 'c:\inetpub\wwwroot\Default.htm' do
source 'Default.htm.erb'
action :create
end
~\cookbooks\web\recipes\iis.rb
Templates What questions can we answer for you?
chef-client The setup with a chef-client and a chef-server
More From Cookbooks Unit-testing with ChefSpec Integration-testing with Test Kitchen Code-linting with FoodCritic and Rubocop
https://docs.chef.io/chefspec.html
Berkshelf
Community Cookbooks
Ohai Plugins
Ask Me Anything
Introduce Yourselves Name What are some things you've wanted to know about Chef?
208
Ask Us Anything What questions can we answer for you?
Workstation Installation
OBJECTIVE:
Install the ChefDK
q Install the ChefDK q Open a PowerShell Prompt q Execute a series of commands to ensure everything is installed q Install git (optional) q Install a text editor (optional)
Now it's time to install the tools on your system
ChefDK The omnibus installer is used to set up the Chef development kit on a workstation, including the chef-client itself, an embedded version of Ruby, RubyGems, OpenSSL, key-value stores, parsers, libraries, command line utilities, and community tools such as Kitchen, Berkshelf, and ChefSpec.
https://downloads.chef.io/chef-dk/
Run All These Commands PS > chef --version PS > chef-client --version PS > knife --version PS > ohai --version PS > berks --version PS > kitchen --version PS > foodcritic --version PS > rubocop --version
git Git is a distributed revision control system with an emphasis on speed, data integrity, and support for distributed, non-linear workflows. Git was initially designed and developed by Linus Torvalds for Linux kernel development in 2005, and has since become the most widely adopted version control system for software development.
http://git-scm.com/downloads
Sublime Text Sublime Text is a sophisticated text editor for code, markup and prose. You'll love the slick user interface, extraordinary features and amazing performance.
http://www.sublimetext.com
ATOM Editor At GitHub, we're building the text editor we've always wanted. A tool you can customize to do anything, but also use productively on the first day without ever touching a config file. Atom is modern, approachable, and hackable to the core. We can't wait to see what you build with it.
https://atom.io
Further Resources
http://bit.ly/chefconf2015 The slides from this workshop and all the workshops from ChefConf 2015
http://bit.ly/cheftraining The training material for Chef Fundamentals and Extending Chef classes.
http://learnchef.com
http://docs.chef.io
youtube.com/user/getchef
youtube.com/user/getchef
irc.freenode.net#chef Meetings every two weeks
Learning Chef A Guide to Configuration Management and Automation
Customizing Chef Getting the Most Out of Your Infrastructure Automation