# Chef for Microsoft Windows¶

[edit on GitHub]

Note

Note

New in Chef Client 12.9, Chef client now runs on 64-bit versions of Microsoft Windows.

The chef-client has specific components that are designed to support unique aspects of the Microsoft Windows platform, including Windows PowerShell, Internet Information Services (IIS), and SQL Server.

• The chef-client is installed on a machine running Microsoft Windows by using a Microsoft Installer Package (MSI)

• Six resources dedicated to the Microsoft Windows platform are built into the chef-client: batch, dsc_script, env, powershell_script, registry_key, and windows_package

• Use the dsc_resource to use Powershell DSC resources in Chef!

• Two knife plugins dedicated to the Microsoft Windows platform are available: knife azure is used to manage virtual instances in Microsoft Azure; knife windows is used to interact with and manage physical nodes that are running Microsoft Windows, such as desktops and servers

• Many community cookbooks on Supermarket provide Windows specific support. Chef maintains cookbooks for PowerShell, IIS, SQL Server, and Windows.

• The following Microsoft Windows platform-specific helpers can be used in recipes:

Helper Description
cluster? Use to test for a Cluster SKU (Windows Server 2003 and later).
core? Use to test for a Core SKU (Windows Server 2003 and later).
datacenter? Use to test for a Datacenter SKU.
marketing_name Use to display the marketing name for a Microsoft Windows platform.
windows_7? Use to test for Windows 7.
windows_8? Use to test for Windows 8.
windows_8_1? Use to test for Windows 8.1.
windows_2000? Use to test for Windows 2000.
windows_home_server? Use to test for Windows Home Server.
windows_server_2003? Use to test for Windows Server 2003.
windows_server_2003_r2? Use to test for Windows Server 2003 R2.
windows_server_2008? Use to test for Windows Server 2008.
windows_server_2008_r2? Use to test for Windows Server 2008 R2.
windows_server_2012? Use to test for Windows Server 2012.
windows_server_2012_r2? Use to test for Windows Server 2012 R2.
windows_vista? Use to test for Windows Vista.
windows_xp? Use to test for Windows XP.
• Two community provisioners for Kitchen: kitchen-dsc and kitchen-pester

The most popular core resources in the chef-client—cookbook_file, directory, env, execute, file, group, http_request, link, mount, package, remote_directory, remote_file, ruby_block, service, template, and user—work the same way in Microsoft Windows as they do on any UNIX- or Linux-based platform.

The file-based resources—cookbook_file, file, remote_file, and template—have attributes that support unique requirements within the Microsoft Windows platform, including inherits (for file inheritance), mode (for octal modes), and rights (for access control lists, or ACLs).

Note

The Microsoft Windows platform does not support running as an alternate user unless full credentials (a username and password or equivalent) are specified.

The following sections are pulled in from the larger https://docs.chef.io/ site and represents the documentation that is specific to the Microsoft Windows platform, compiled here into a single-page reference.

## Install the chef-client on Windows¶

The chef-client can be installed on machines running Microsoft Windows in the following ways:

• By using the knife windows plugin to bootstrap the chef-client; this process requires the target node be available via SSH (port 22) or by using the HTTP or HTTPS ports that are required by WinRM
• By downloading the chef-client to the target node, and then running the Microsoft Installer Package (MSI) locally
• By using an existing process already in place for managing Microsoft Windows machines, such as System Center

To run the chef-client at periodic intervals (so that it can check in with the Chef server automatically), configure the chef-client to run as a service or as a scheduled task. (The chef-client can be configured to run as a service during the setup process.)

The chef-client can be used to manage machines that run on the following versions of Microsoft Windows:

Operating System Version Architecture
Windows 2008 R2, 2012, 2012 R2 x86_64

(The recommended amount of RAM available to the chef-client during a chef-client run is 512MB. Each node and workstation must have access to the Chef server via HTTPS. Ruby version 1.9.1 or Ruby version 1.9.2 with SSL bindings is required.)

The Microsoft Installer Package (MSI) for Microsoft Windows is available at http://www.chef.io/chef/install/. From the drop-downs, select the operating system (Windows), then the version, and then the architecture.

After the chef-client is installed, it is located at C:\chef. The main configuration file for the chef-client is located at C:\chef\client.rb.

### Set the System Ruby¶

To set the system Ruby for the Microsoft Windows platform the steps described for all platforms are true, but then require the following manual edits to the chef shell-init bash output for the Microsoft Windows platform:

1. Add quotes around the variable assignment strings.
2. Convert C:/ to /c/.
3. Save those changes.

### Spaces and Directories¶

Directories that are used by Chef on Windows cannot have spaces. For example, C:\Users\Steven Danno will not work, but C:\Users\StevenDanno will. Because of this, the knife cookbook site install subcommand will fail if the directory contains a space.

### Top-level Directory Names¶

Windows will throw errors when path name lengths are too long. For this reason, it’s often helpful to use a very short top-level directory, much like what is done in UNIX and Linux. For example, Chef uses /opt/ to install the Chef development kit on macOS. A similar approach can be done on Microsoft Windows, by creating a top-level directory with a short name. For example: C:\chef.

### Use knife-windows¶

The knife windows subcommand is used to configure and interact with nodes that exist on server and/or desktop machines that are running Microsoft Windows. Nodes are configured using WinRM, which allows native objects—batch scripts, Windows PowerShell scripts, or scripting library variables—to be called by external applications. The knife windows subcommand supports NTLM and Kerberos methods of authentication.

For more information about the knife windows plugin, see windows.

#### Ports¶

WinRM requires that a target node be accessible via the ports configured to support access via HTTP or HTTPS.

#### Msiexec.exe¶

Msiexec.exe is used to install the chef-client on a node as part of a bootstrap operation. The actual command that is run by the default bootstrap script is:



OR

$msiexec /qn /i C:\inst\chef-client-12.4.3-1.windows.msi ADDLOCAL="ChefClientFeature,ChefServiceFeature,ChefPSModuleFeature"  ### Use MSI Installer¶ A Microsoft Installer Package (MSI) is available for installing the chef-client on a Microsoft Windows machine. To install the chef-client on Microsoft Windows, do the following: 1. Click the Chef Client tab. 2. Select Windows, a version, and an architecture. 3. Under Downloads, select the version of the chef-client to download, and then click the link that appears below to download the package. 4. Ensure that the MSI is on the target node. 5. Run the MSI package and use all the default options: then: then: Note The MSI can either configure the chef-client to run as a scheduled task or as a service for it to be able to regularly check in with the Chef server. Using a scheduled task is a recommended approach. Select the Chef Unattended Execution Options option to have the MSI configure the chef-client as a scheduled task or as a service. then: then: then: then: #### Enable as a Scheduled Task¶ To run the chef-client at periodic intervals (so that it can check in with the Chef server automatically), configure the chef-client to run as a scheduled task. This can be done via the MSI, by selecting the Chef Unattended Execution Options –> Chef Client Scheduled Task option on the Custom Setup page or by running the following command after the chef-client is installed: For example: $ SCHTASKS.EXE /CREATE /TN ChefClientSchTask /SC MINUTE /MO 30 /F /RU "System" /RP /RL HIGHEST /TR "cmd /c \"C:\opscode\chef\embedded\bin\ruby.exe C:\opscode\chef\bin\chef-client -L C:\chef\chef-client.log -c C:\chef\client.rb\""


Refer Schedule a Task for more details.

After the chef-client is configured to run as a scheduled task, the default file path is: c:\chef\chef-client.log.

Using a scheduled task is a recommended approach. Refer to Should I run chef-client on Windows as a ‘service’ or a ‘scheduled task’? for additional information on the differences between the two approaches.

#### Enable as a Service¶

To run the chef-client at periodic intervals (so that it can check in with the Chef server automatically), configure the chef-client to run as a service. This can be done via the MSI, by selecting the Chef Unattended Execution Options –> Chef Client Service option on the Custom Setup page or by running the following command after the chef-client is installed:

$chef-service-manager -a install  and then start the chef-client as a service: $ chef-service-manager -a start


After the chef-client is configured to run as a service, the default file path is: c:\chef\chef-client.log.

### Use an Existing Process¶

Many organizations already have processes in place for managing the applications and settings on various Microsoft Windows machines. For example, System Center. The chef-client can be installed using this method.

### PATH System Variable¶

On Microsoft Windows, the chef-client must have two entries added to the PATH environment variable:

• C:\opscode\chef\bin
• C:\opscode\chef\embedded\bin

This is typically done during the installation of the chef-client automatically. If these values (for any reason) are not in the PATH environment variable, the chef-client will not run properly.

This value can be set from a recipe. For example, from the php cookbook:

#  the following code sample comes from the package recipe in the php cookbook: https://github.com/chef-cookbooks/php

if platform?('windows')

include_recipe 'iis::mod_cgi'

install_dir = File.expand_path(node['php']['conf_dir']).gsub('/', '\\')
windows_package node['php']['windows']['msi_name'] do
source node['php']['windows']['msi_source']
installer_type :msi

options %W[
/quiet
INSTALLDIR="#{install_dir}"
].join(' ')
end

...

ENV['PATH'] += ";#{install_dir}"
windows_path install_dir

...


## Proxy Settings¶

To determine the current proxy server on the Microsoft Windows platform:

1. Open Internet Properties.
2. Open Connections.
3. Open LAN settings.
4. View the Proxy server setting. If this setting is blank, then a proxy server may not be available.

To configure proxy settings in Microsoft Windows:

1. Open System Properties.
2. Open Environment Variables.
3. Open System variables.
4. Set http_proxy and https_proxy to the location of your proxy server. This value MUST be lowercase.

## Microsoft Azure portal¶

Microsoft Azure is a cloud hosting platform from Microsoft that provides virtual machines and integrated services for you to use with your cloud and hybrid applications. Through the Azure Marketplace and the Azure portal, virtual machines can be bootstrapped and ready to run Chef Automate, Chef Compliance and Chef client.

Through the Azure portal, you can provision a virtual machine with chef-client running as a background service. Once provisioned, these virtual machines are ready to be managed by a Chef server.

Note

Virtual machines running on Microsoft Azure can also be provisioned from the command-line using the knife azure plugin for knife. This approach is ideal for cases that require automation or for users who are more suited to command-line interfaces.

### chef-client Settings¶

Before virtual machines can be created using the Azure portal, some chef-client-specific settings will need to be identified so they can be provided to the Azure portal during the virtual machine creation workflow. These settings are available from the chef-client configuration settings:

• The chef_server_url and validation_client_name. These are settings in the client.rb file.
• The file for the validator key.

### Set up Virtual Machines¶

Once this information has been identified, launch the Azure portal, start the virtual machine creation workflow, and then bootstrap virtual machines with Chef using the following steps:

2. Choose Virtual Machines in the left pane of the portal.

4. Select either Windows Server or Ubuntu Server in the Recommended category.

Note

The Chef extension on the Azure portal may be used on the following platforms:

• Windows Server 2008 R2 SP1, 2012, 2012 R2, 2016
• Ubuntu 12.04 LTS, 14.04 LTS, 16.04 LTS, 16.10
• CentOS 6.5+
• RHEL 6+
• Debian 7, 8
5. In the next blade, select the sku/version of the OS that you would like to use on your VM and click Create.

6. Fill in the virtual machine configuration information, such as machine name, credentials, VM size, and so on.

Note

It’s best to use a new computer name each time through this workflow. This will help to avoid conflicts with virtual machine names that may have been previously registered on the Chef server.

7. In Step 3 on the portal UI, open the Extensions blade and click Add extension.

8. Depending on the OS you selected earlier, select either Windows Chef Extension or Linux Chef Extension and then Create.

9. Using the chef-repo/.chef/knife.rb file you downloaded during your Chef server setup, enter values for the Chef server URL and the validation client name. You can also use this file to help you find the location of your validation key.

10. Browse on your local machine and find your validation key (chef-repo/.chef/<orgname>-validator.pem).

11. Upload it through the portal in the Validation Key field.

Note

Because the .chef directory is considered a hidden directory, you may have to copy this file out to a non-hidden directory on disk before you can upload it through the open file dialog box.

12. For Client Configuration File, browse to the chef-repo/.chef/knife.rb file and upload it through your web browser.

Note

Same directory issue from previous step applies here as well. Also, the knife.rb file must be correctly configured to communicate to the Chef server. Specifically, it must have valid values for the following two settings: chef_server_url and validation_client_name.

13. Optional. Use a run-list to specify what should be run when the virtual machine is provisioned, such as using the run-list to provision a virtual machine with Internet Information Services (IIS). Use the iis cookbook and the default recipe to build a run-list. For example:

iis


or:

iis::default


or:

recipe['iis']


A run-list can also be built using a role. For example, if a role named backend_server is defined on the Chef server, the run-list would look like:

role['backend_server']


Even without a run-list, the virtual machine will periodically check with the Chef server to see if the configuration requirements change. This means that the run-list can be updated later, by editing the run-list to add the desired run-list items by using the Chef server web user interface or by using the knife command line tool.

Note

A run-list may only refer to roles and/or recipes that have already been uploaded to the Chef server.

14. Click OK to complete the page. Click OK in the Extensions blade and the rest of the setup blades. Provisioning will begin and the portal will the blade for your new VM.

After the process is complete, the virtual machine will be registered with the Chef server and it will have been provisioned with the configuration (applications, services, etc.) from the specified run-list. The Chef server can now be used to perform all ongoing management of the virtual machine node.

### Log Files¶

If the Azure portal displays an error in dashboard, check the log files. The log files are created by the chef-client. The log files can be accessed from within the Azure portal or by running the chef-client on the node itself and then reproducing the issue interactively.

#### From the Azure portal¶

Log files are available from within the Azure portal:

1. Select Virtual Machines in the left pane of the Azure portal.

2. Select the virtual machine that has the error status.

3. Click the Connect button at the bottom of the portal to launch a Windows Remote Desktop session, and then log in to the virtual machine.

4. Start up a Windows PowerShell command shell.

$cd c:\windowsazure\logs ls –r chef*.log  5. This should display the log files, including the chef-client log file. #### From the chef-client¶ The chef-client can be run interactively by using Windows Remote Desktop to connect to the virtual machine, and then running the chef-client: 1. Log into the virtual machine. 2. Start up a Windows PowerShell command shell. 3. Run the following command: $ chef-client -l debug

4. View the logs. On a linux system, the Chef client logs are saved to /var/log/azure/Chef.Bootstrap.WindowsAzure.LinuxChefClient/<extension-version-number>/chef-client.log and can be viewed using the following command:

$tail -f /var/log/azure/Chef.Bootstrap.WindowsAzure.LinuxChefClient/1210.12.102.1000/chef-client.log  #### Troubleshoot Log Files¶ After the log files have been located, open them using a text editor to view the log file. The most common problem are below: • Connectivity errors with the Chef server caused by incorrect settings in the client.rb file. Ensure that the chef_server_url value in the client.rb file is the correct value and that it can be resolved. • An invalid validator key has been specified. This will prevent the chef-client from authenticating to the Chef server. Ensure that the validation_client_name value in the client.rb file is the correct value • The name of the node is the same as an existing node. Node names must be unique. Ensure that the name of the virtual machine in Microsoft Azure has a unique name. • An error in one the run-list. The log file will specify the details about errors related to the run-list. ### For more information …¶ For more information about Microsoft Azure and how to use it with Chef: ## Knife¶ knife is a command-line tool that provides an interface between a local chef-repo and the Chef server. knife helps users to manage: • Nodes • Cookbooks and recipes • Roles, Environments, and Data Bags • Resources within various cloud environments • The installation of the chef-client onto nodes • Searching of indexed data on the Chef server ### Set the Text Editor¶ Some knife commands, such as knife data bag edit, require that information be edited as JSON data using a text editor. For example, the following command: $ knife data bag edit admins admin_name


will open up the text editor with data similar to:

{
}


Changes to that file can then be made:

{
"id": "Justin C."
"description": "I am passing the time by letting time pass over me ..."
}


The type of text editor that is used by knife can be configured by adding an entry to your knife.rb file, or by setting an EDITOR environment variable. For example, to configure knife to open the vim text editor, add the following to your knife.rb file:

knife[:editor] = "/usr/bin/vim"


When a Microsoft Windows file path is enclosed in a double-quoted string (” “), the same backslash character (\) that is used to define the file path separator is also used in Ruby to define an escape character. The knife.rb file is a Ruby file; therefore, file path separators must be escaped. In addition, spaces in the file path must be replaced with ~1 so that the length of each section within the file path is not more than 8 characters. For example, if EditPad Pro is the text editor of choice and is located at the following path:

C:\\Program Files (x86)\EditPad Pro\EditPad.exe


the setting in the knife.rb file would be similar to:

knife[:editor] = "C:\\Progra~1\\EditPa~1\\EditPad.exe"


One approach to working around the double- vs. single-quote issue is to put the single-quotes outside of the double-quotes. For example, for Notepad++:

knife[:editor] = '"C:\Program Files (x86)\Notepad++\notepad++.exe" -nosession -multiInst'


for Sublime Text:

knife[:editor] = '"C:\Program Files\Sublime Text 2\sublime_text.exe" --wait'


knife[:editor] = '"C:\Program Files (x86)\TextPad 7\TextPad.exe"'


and for vim:

knife[:editor] = '"C:\Program Files (x86)\vim\vim74\gvim.exe"'


### Quotes, Windows¶

When running knife in Microsoft Windows, a string may be interpreted as a wildcard pattern when quotes are not present in the command. The number of quotes to use depends on the shell from which the command is being run.

When running knife from the command prompt, a string should be surrounded by single quotes (' '). For example:

$knife node run_list set test-node 'recipe[iptables]'  When running knife from Windows PowerShell, a string should be surrounded by triple single quotes (''' '''). For example: $ knife node run_list set test-node '''recipe[iptables]'''


#### Import-Module chef¶

The chef-client version 12.4 release adds an optional feature to the Microsoft Installer Package (MSI) for Chef. This feature enables the ability to pass quoted strings from the Windows PowerShell command line without the need for triple single quotes (''' '''). This feature installs a Windows PowerShell module (typically in C:\opscode\chef\modules) that is also appended to the PSModulePath environment variable. This feature is not enabled by default. To activate this feature, run the following command from within Windows PowerShell:

$Import-Module chef  or add Import-Module chef to the profile for Windows PowerShell located at: ~\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1  This module exports cmdlets that have the same name as the command-line tools—chef-client, knife, chef-apply—that are built into Chef. For example: $ knife exec -E 'puts ARGV' """&s0meth1ng"""


is now:

$knife exec -E 'puts ARGV' '&s0meth1ng'  and: $ knife node run_list set test-node '''role[ssssssomething]'''


is now:

$knife node run_list set test-node 'role[ssssssomething]'  To remove this feature, run the following command from within Windows PowerShell: $ Remove-Module chef


### Ampersands, Windows¶

When running knife in Microsoft Windows, an ampersand (&) is a special character and must be protected by quotes when it appears in a command. The number of quotes to use depends on the shell from which the command is being run.

When running knife from the command prompt, an ampersand should be surrounded by quotes ("&"). For example:

$knife bootstrap windows winrm -P "&s0meth1ng"  When running knife from Windows PowerShell, an ampersand should be surrounded by triple quotes ("""&"""). For example: $ knife bootstrap windows winrm -P """&s0meth1ng"""


### knife bootstrap¶

A node is any physical, virtual, or cloud machine that is configured to be maintained by a chef-client. In order to bootstrap a node, you will first need a working installation of the Chef software package. A bootstrap is a process that installs the chef-client on a target system so that it can run as a chef-client and communicate with a Chef server. There are two ways to do this:

Use the knife bootstrap subcommand to run a bootstrap operation that installs the chef-client on the target system. The bootstrap operation must specify the IP address or FQDN of the target system.

Note

To bootstrap the chef-client on Microsoft Windows machines, the knife-windows plugins is required, which includes the necessary bootstrap scripts that are used to do the actual installation.

#### Syntax¶

This subcommand has the following syntax:

$knife bootstrap FQDN_or_IP_ADDRESS (options)  #### Options¶ Note Review the list of common options available to this (and all) knife subcommands and plugins. This subcommand has the following options: -A, --forward-agent Enable SSH agent forwarding. --bootstrap-curl-options OPTIONS Arbitrary options to be added to the bootstrap command when using cURL. This option may not be used in the same command with --bootstrap-install-command. --bootstrap-install-command COMMAND Execute a custom installation command sequence for the chef-client. This option may not be used in the same command with --bootstrap-curl-options or --bootstrap-wget-options. --bootstrap-no-proxy NO_PROXY_URL_or_IP A URL or IP address that specifies a location that should not be proxied. Note This option is used internally by Chef to help verify bootstrap operations during testing and should never be used during an actual bootstrap operation. --bootstrap-proxy PROXY_URL The proxy server for the node that is the target of a bootstrap operation. --bootstrap-vault-file VAULT_FILE The path to a JSON file that contains a list of vaults and items to be updated. --bootstrap-vault-item VAULT_ITEM A single vault and item to update as vault:item. --bootstrap-vault-json VAULT_JSON A JSON string that contains a list of vaults and items to be updated. For example: --bootstrap-vault-json '{ "vault1": ["item1", "item2"], "vault2": "item2" }'  --bootstrap-version VERSION The version of the chef-client to install. --bootstrap-wget-options OPTIONS Arbitrary options to be added to the bootstrap command when using GNU Wget. This option may not be used in the same command with --bootstrap-install-command. -E ENVIRONMENT, --environment ENVIRONMENT The name of the environment. When this option is added to a command, the command will run only against the named environment. -G GATEWAY, --ssh-gateway GATEWAY The SSH tunnel or gateway that is used to run a bootstrap action on a machine that is not accessible from the workstation. --hint HINT_NAME[=HINT_FILE] An Ohai hint to be set on the target node. Ohai hints are used to tell Ohai something about the system that it is running on that it would not be able to discover itself. An Ohai hint exists if a JSON file exists in the hint directory with the same name as the hint. For example, calling hint?('antarctica') in an Ohai plugin would return an empty hash if the file antarctica.json existed in the hints directory, and return nil if the file does not exist. If the hint file contains JSON content, it will be returned as a hash from the call to hint?. { "snow": true, "penguins": "many" }  antarctica_hint = hint?('antarctica') if antarctica_hint['snow'] "There are #{antarctica_hint['penguins']} penguins here." else 'There is no snow here, and penguins like snow.' end  Hint files are located in the /etc/chef/ohai/hints/ directory by default. Use the Ohai.config[:hints_path] setting in the client.rb file to customize this location. HINT_FILE is the name of the JSON file. HINT_NAME is the name of a hint in a JSON file. Use multiple --hint options to specify multiple hints. -i IDENTITY_FILE, --ssh-identity-file IDENTITY_FILE The SSH identity file used for authentication. Key-based authentication is recommended. New in Chef Client 12.6. -j JSON_ATTRIBS, --json-attributes JSON_ATTRIBS A JSON string that is added to the first run of a chef-client. --json-attribute-file FILE A JSON file to be added to the first run of chef-client. New in Chef Client 12.6. -N NAME, --node-name NAME The name of the node. Note This option is required for a validatorless bootstrap (Changed in Chef Client 12.4). --[no-]fips Allows OpenSSL to enforce FIPS-validated security during the chef-client run. --[no-]host-key-verify Use --no-host-key-verify to disable host key verification. Default setting: --host-key-verify. --[no-]node-verify-api-cert Verify the SSL certificate on the Chef server. When true, the chef-client always verifies the SSL certificate. When false, the chef-client uses the value of ssl_verify_mode to determine if the SSL certificate requires verification. If this option is not specified, the setting for verify_api_cert in the configuration file is applied. New in Chef Client 12.0. --node-ssl-verify-mode MODE Set the verify mode for HTTPS requests. Options: none or peer. Use none to do no validation of SSL certificates. Use peer to do validation of all SSL certificates, including the Chef server connections, S3 connections, and any HTTPS remote_file resource URLs used in the chef-client run. This is the recommended setting. New in Chef Client 12.0. -p PORT, --ssh-port PORT The SSH port. -P PASSWORD, --ssh-password PASSWORD The SSH password. This can be used to pass the password directly on the command line. If this option is not specified (and a password is required) knife prompts for the password. --prerelease Install pre-release gems. -r RUN_LIST, --run-list RUN_LIST A comma-separated list of roles and/or recipes to be applied. --secret SECRET The encryption key that is used for values contained within a data bag item. --secret-file FILE The path to the file that contains the encryption key. --sudo Execute a bootstrap operation with sudo. --sudo-preserve-home Use to preserve the non-root user’s HOME environment. New in Chef Client 12.6. -t TEMPLATE, --bootstrap-template TEMPLATE The bootstrap template to use. This may be the name of a bootstrap template—chef-full, for example—or it may be the full path to an Embedded Ruby (ERB) template that defines a custom bootstrap. Default value: chef-full, which installs the chef-client using the omnibus installer on all supported platforms. New in Chef Client 12.0. --use-sudo-password Perform a bootstrap operation with sudo; specify the password with the -P (or --ssh-password) option. -V -V Run the initial chef-client run at the debug log-level (e.g. chef-client -l debug). -x USERNAME, --ssh-user USERNAME The SSH user name. Note See knife.rb for more information about how to add certain knife options as settings in the knife.rb file. ### knife azure¶ Microsoft Azure is a cloud hosting platform from Microsoft that provides virtual machines for Linux and Windows Server, cloud and database services, and more. The knife azure subcommand is used to manage API-driven cloud servers that are hosted by Microsoft Azure. Note Review the list of common options available to this (and all) knife subcommands and plugins. #### Install this plugin¶ To install the knife azure plugin using RubyGems, run the following command: $ /opt/chef/embedded/bin/gem install knife-azure


where /opt/chef/embedded/bin/ is the path to the location where the chef-client expects knife plugins to be located. If the chef-client was installed using RubyGems, omit the path in the previous example.

#### Generate Certificates¶

The knife azure subcommand must use a management certificate for secure communication with Microsoft Azure. The management certificate is required for secure communication with the Microsoft Azure platform via the REST APIs. To generate the management certificate (.pem file):

2. Extract the data from the ManagementCertificate field into a separate file named cert.pfx.

3. Decode the certificate file with the following command:

$base64 -d cert.pfx > cert_decoded.pfx  4. Convert the decoded PFX file to a PEM file with the following command: $ openssl pkcs12 -in cert_decoded.pfx -out managementCertificate.pem -nodes


Note

#### ag create¶

Use the ag create argument to create an affinity group.

##### Syntax¶

This argument has the following syntax:


##### Options¶

This argument has the following options:

--azure-publish-settings-file FILE_NAME
The name of the Azure Publish Settings file, including the path. For example: "/path/to/your.publishsettings".
-H HOST_NAME, --azure_host_name HOST_NAME
The host name for the Microsoft Azure environment.
-p FILE_NAME, --azure-mgmt-cert FILE_NAME
The name of the file that contains the SSH public key that is used when authenticating to Microsoft Azure.
-S ID, --azure-subscription-id ID
The subscription identifier for the Microsoft Azure portal.
--verify-ssl-cert
The SSL certificate used to verify communication over HTTPS.

#### image list¶

Use the image list argument to get a list of images that exist in a Microsoft Azure environment. Any image in this list may be used for provisioning.

##### Syntax¶

This argument has the following syntax:


##### Options¶

This argument has the following options:

-a, --azure-affinity-group GROUP
The affinity group to which the virtual machine belongs. Required when not using a service location. Required when not using --azure-service-location.
--auto-update-client
Enable automatic updates for the chef-client in Microsoft Azure. This option may only be used when --bootstrap-protocol is set to cloud-api. Default value: false.
--azure-availability-set NAME
The name of the availability set for the virtual machine.
--azure-dns-name DNS_NAME
Required. The name of the DNS prefix that is used to access the cloud service. This name must be unique within Microsoft Azure. Use with --azure-connect-to-existing-dns to use an existing DNS prefix.
--azure-network-name NETWORK_NAME
The network for the virtual machine.
--azure-publish-settings-file FILE_NAME
The name of the Azure Publish Settings file, including the path. For example: "/path/to/your.publishsettings".
--azure-storage-account STORAGE_ACCOUNT_NAME
The name of the storage account used with the hosted service. A storage account name may be between 3 and 24 characters (lower-case letters and numbers only) and must be unique within Microsoft Azure.
--azure-subnet-name SUBNET_NAME
The subnet for the virtual machine.
--azure-vm-name NAME
The name of the virtual machine. Must be unique within Microsoft Azure. Required for advanced server creation options.
--azure-vm-ready-timeout TIMEOUT
A number (in minutes) to wait for a virtual machine to reach the provisioning state. Default value: 10.
--azure-vm-startup-timeout TIMEOUT
A number (in minutes) to wait for a virtual machine to transition from the provisioning state to the ready state. Default value: 15.
--bootstrap-protocol PROTOCOL

The protocol used to bootstrap on a machine that is running Windows Server: cloud-api, ssh, or winrm. Default value: winrm.

Use the cloud-api option to bootstrap a machine in Microsoft Azure. The bootstrap operation will enable the guest agent to install, configure, and run the chef-client on a node, after which the chef-client is configured to run as a daemon/service. (This is a similar process to using the Azure portal.)

Microsoft Azure maintains images of the chef-client on the guest, so connectivity between the guest and the workstation from which the bootstrap operation was initiated is not required, after a cloud-api bootstrap is started.

During the cloud-api bootstrap operation, knife does not print the output of the chef-client run like it does when the winrm and ssh options are used. knife reports only on the status of the bootstrap process: provisioning, installing, ready, and so on, along with reporting errors.

--bootstrap-version VERSION
The version of the chef-client to install.
-c, --azure-connect-to-existing-dns
Add a new virtual machine to the existing deployment and/or service. Use with --azure-dns-name to ensure the correct DNS is used.
--cert-passphrase PASSWORD
The password for the SSL certificate.
--cert-path PATH
The path to the location of the SSL certificate.
-d DISTRO, --distro DISTRO

The template file to be used during a bootstrap operation. The following distributions are supported:

• chef-full (the default bootstrap)
• centos5-gems
• fedora13-gems
• ubuntu10.04-gems
• ubuntu10.04-apt
• ubuntu12.04-gems
• The name of a custom bootstrap template file.

When this option is used, knife searches for the template file in the following order:

1. The bootstrap/ folder in the current working directory
2. The bootstrap/ folder in the chef-repo
3. The bootstrap/ folder in the ~/.chef/ directory
4. A default bootstrap file.

Do not use the --template-file option when --distro is specified.

Deprecated in Chef Client 12.0,

-H HOST_NAME, --azure_host_name HOST_NAME
The host name for the virtual machine.
--hint HINT_NAME[=HINT_FILE]

An Ohai hint to be set on the target node.

Ohai hints are used to tell Ohai something about the system that it is running on that it would not be able to discover itself. An Ohai hint exists if a JSON file exists in the hint directory with the same name as the hint. For example, calling hint?('antarctica') in an Ohai plugin would return an empty hash if the file antarctica.json existed in the hints directory, and return nil if the file does not exist.

If the hint file contains JSON content, it will be returned as a hash from the call to hint?.

{
"snow": true,
"penguins": "many"
}

antarctica_hint = hint?('antarctica')
if antarctica_hint['snow']
"There are #{antarctica_hint['penguins']} penguins here."
else
'There is no snow here, and penguins like snow.'
end


Hint files are located in the /etc/chef/ohai/hints/ directory by default. Use the Ohai.config[:hints_path] setting in the client.rb file to customize this location.

HINT_FILE is the name of the JSON file. HINT_NAME is the name of a hint in a JSON file. Use multiple --hint options to specify multiple hints.

--host-name HOST_NAME
The host name for the Microsoft Azure environment.
-I IMAGE, --azure-source-image IMAGE
The name of the disk image to be used to create the virtual machine.
--identity-file IDENTITY_FILE
The SSH identity file used for authentication. Key-based authentication is recommended.
--identity-file_passphrase PASSWORD
The passphrase for the SSH key. Use only with --identity-file.
-j JSON_ATTRIBS, --json-attributes JSON_ATTRIBS
A JSON string that is added to the first run of a chef-client.
-m LOCATION, --azure-service-location LOCATION
The geographic location for a virtual machine and its services. Required when not using --azure-affinity-group.
-N NAME, --node-name NAME
The name of the node. Node names, when used with Microsoft Azure, must be 91 characters or shorter.
--[no-]host-key-verify
Use --no-host-key-verify to disable host key verification. Default setting: --host-key-verify.
-o DISK_NAME, --azure-os-disk-name DISK_NAME
The operating system type of the Microsoft Azure OS image: Linux or Windows.
-p FILE_NAME, --azure-mgmt-cert FILE_NAME
The name of the file that contains the SSH public key that is used when authenticating to Microsoft Azure.
-P PASSWORD, --ssh-password PASSWORD
The SSH password. This can be used to pass the password directly on the command line. If this option is not specified (and a password is required) knife prompts for the password.
--prerelease
Install pre-release gems.
-r RUN_LIST, --run-list RUN_LIST
A comma-separated list of roles and/or recipes to be applied.
-R ROLE_NAME, --role-name ROLE_NAME
The name of the virtual machine.
--ssh-port PORT
The SSH port. Default value: 22.
-t PORT_LIST, --tcp-endpoints PORT_LIST
A comma-separated list of local and public TCP ports that are to be opened. For example: 80:80,433:5000.
--template-file TEMPLATE

The path to a template file to be used during a bootstrap operation.

Deprecated in Chef Client 12.0.

--thumbprint THUMBPRINT
The thumbprint of the SSL certificate.
-u PORT_LIST, ---udp-endpoints PORT_LIST
A comma-separated list of local and public UDP ports that are to be opened. For example: 80:80,433:5000.
--verify-ssl-cert
The SSL certificate used to verify communication over HTTPS.
--windows-auth-timeout MINUTES
The amount of time (in minutes) to wait for authentication to succeed. Default value: 25.
-x USER_NAME, --ssh-user USER_NAME
The SSH user name.
-z SIZE, --azure-vm-size SIZE
The size of the virtual machine: ExtraSmall, Small, Medium, Large, or ExtraLarge. Default value: Small.
##### Examples¶

Provision an instance using new hosted service and storage accounts

To provision a medium-sized CentOS machine configured as a web server in the West US data center, while reusing existing hosted service and storage accounts, enter something like:

$knife azure server create -r "role[webserver]" --service-location "West US" --hosted-service-name webservers --storage-account webservers-storage --ssh-user foo --ssh--password password --role-name web-apache-0001 --host-name web-apache --tcp-endpoints 80:80,8080:8080 --source-image name_of_source_image --role-size Medium  Provision an instance using new hosted service and storage accounts To provision a medium-sized CentOS machine configured as a web server in the West US data center, while also creating new hosted service and storage accounts, enter something like: $ knife azure server create -r "role[webserver]" --service-location "West US" --ssh-user foo
--tcp-endpoints 80:80,8080:8080 --source-image name_of_source_image --role-size Medium


#### server delete¶

Use the server delete argument to delete one or more instances that are running in the Microsoft Azure cloud. To find a specific cloud instance, use knife azure server list. Use the --purge option to delete all associated node and client objects from the Chef server or use the knife node delete and knife client delete subcommands to delete specific node and client objects.

##### Syntax¶

This argument has the following syntax:



#### server describe¶

Use the server describe argument to view a detailed description of one (or more) roles that exist in a Microsoft Azure cloud instance. For each specified role name, information such as status, size, hosted service name, deployment name, ports (open, local, public) and IP are displayed.

##### Syntax¶

This argument has the following syntax:



#### server list¶

Use the server list argument to find instances that are associated with a Microsoft Azure account. The results may show instances that are not currently managed by the Chef server.

##### Syntax¶

This argument has the following syntax:


##### Options¶

This argument has the following options:

--azure-publish-settings-file FILE_NAME
The name of the Azure Publish Settings file, including the path. For example: "/path/to/your.publishsettings".
-H HOST_NAME, --azure_host_name HOST_NAME
The host name for the Microsoft Azure environment.
-p FILE_NAME, --azure-mgmt-cert FILE_NAME
The name of the file that contains the SSH public key that is used when authenticating to Microsoft Azure.
-S ID, --azure-subscription-id ID
The subscription identifier for the Microsoft Azure portal.
--verify-ssl-cert
The SSL certificate used to verify communication over HTTPS.

#### vnet create¶

Use the vnet create argument to create a virtual network.

##### Syntax¶

This argument has the following syntax:


##### Options¶

This argument has the following options:

--azure-publish-settings-file FILE_NAME
The name of the Azure Publish Settings file, including the path. For example: "/path/to/your.publishsettings".
-H HOST_NAME, --azure_host_name HOST_NAME
The host name for the Microsoft Azure environment.
-p FILE_NAME, --azure-mgmt-cert FILE_NAME
The name of the file that contains the SSH public key that is used when authenticating to Microsoft Azure.
-S ID, --azure-subscription-id ID
The subscription identifier for the Microsoft Azure portal.
--verify-ssl-cert
The SSL certificate used to verify communication over HTTPS.

### knife windows¶

The knife windows subcommand is used to configure and interact with nodes that exist on server and/or desktop machines that are running Microsoft Windows. Nodes are configured using WinRM, which allows native objects—batch scripts, Windows PowerShell scripts, or scripting library variables—to be called by external applications. The knife windows subcommand supports NTLM and Kerberos methods of authentication.

Note

Review the list of common options available to this (and all) knife subcommands and plugins.

#### Install this plugin¶

To install the knife windows plugin using RubyGems, run the following command:

$/opt/chef/embedded/bin/gem install knife-windows  where /opt/chef/embedded/bin/ is the path to the location where the chef-client expects knife plugins to be located. If the chef-client was installed using RubyGems, omit the path in the previous example. #### Requirements¶ This subcommand requires WinRM to be installed, and then configured correctly, including ensuring the correct ports are open. For more information, see: http://msdn.microsoft.com/en-us/library/aa384372(v=vs.85).aspx and/or http://support.microsoft.com/kb/968930. Use the quick configuration option in WinRM to allow outside connections and the entire network path from knife (and the workstation): $ winrm quickconfig -q


The following WinRM configuration settings should be updated:

Setting Description
MaxMemoryPerShellMB The chef-client and Ohai typically require more memory than the default setting allows. Increase this value to 300MB. Only required on Windows Server 2008 R2 Standard and older. The default in Windows Server 2012 was increased to 1024MB.
MaxTimeoutms A bootstrap command can take longer than allowed by the default setting. Increase this value to 1800000 (30 minutes).

To update these settings, run the following commands:

$winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="300"}'  and then: $ winrm set winrm/config '@{MaxTimeoutms="1800000"}'


Ensure that the Windows Firewall is configured to allow WinRM connections between the workstation and the Chef server. For example:



and:

$knife bootstrap windows winrm db1.cloudapp.net -r 'server::db' -x '.\localadmin' -P 'password'  #### Domain Authentication¶ The knife windows plugin supports Microsoft Windows domain authentication. This requires: To create the listener over HTTPS, run the following command: $ winrm create winrm/config/Listener?Address=IP:<ip_address>+Transport=HTTPS @{Hostname="<fqdn>";CertificateThumbprint="<hexidecimal_thumbprint_value>"}


where the CertificateThumbprint is the thumbprint hex value copied from the certificate details. (The hex value may require that spaces be removed before passing them to the node using the knife windows plugin.) WinRM 2.0 uses port 5985 for HTTP and port 5986 for HTTPS traffic, by default.

To bootstrap the target node using the knife bootstrap subcommand, first use the winrm argument in the knife windows plugin to verify communication with the node:

$knife winrm 'node1.domain.com' 'dir' -m -x domain\\administrator -P 'super_secret_password' –p 5986  and then run a command similar to the following: $ knife bootstrap windows winrm 'node1.domain.com' -r 'role[webserver]' -x domain\\administrator -P 'password' -p 5986


#### bootstrap windows ssh¶

Use the bootstrap windows ssh argument to bootstrap chef-client installations in a Microsoft Windows environment, using a command shell that is native to Microsoft Windows.

##### Syntax¶

This argument has the following syntax:


##### Options¶

This argument has the following options:

-a ATTR, --attribute ATTR
The attribute used when opening an SSH connection. The default attribute is the FQDN of the host. Other possible values include a public IP address, a private IP address, or a hostname.
-f CA_TRUST_FILE, --ca-trust-file CA_TRUST_FILE
Optional. The certificate authority (CA) trust file used for SSL transport.
-C NUM, --concurrency NUM
Changed in knife-windows 1.9.0. The number of allowed concurrent connections. Defaults to 1.
-i IDENTITY_FILE, --identity-file IDENTITY_FILE
The keytab file that contains the encryption key required by Kerberos-based authentication.
--keytab-file KEYTAB_FILE
The keytab file that contains the encryption key required by Kerberos-based authentication.
-m, --manual-list
Define a search query as a space-separated list of servers.
-p PORT, --winrm-port PORT
The WinRM port. The TCP port on the remote system to which knife windows commands that are made using WinRM are sent. Default: 5986 when --winrm-transport is set to ssl, otherwise 5985.
-P PASSWORD, --winrm-password PASSWORD
-R KERBEROS_REALM, --kerberos-realm KERBEROS_REALM
Optional. The administrative domain to which a user belongs.
--returns CODES
A comma-delimited list of return codes that indicate the success or failure of the command that was run remotely.
-S KERBEROS_SERVICE, --kerberos-service KERBEROS_SERVICE
Optional. The service principal used during Kerberos-based authentication.
SEARCH_QUERY
The search query used to return a list of servers to be accessed using SSH and the specified SSH_COMMAND. This option uses the same syntax as the search subcommand.
SSH_COMMAND
The command to be run against the results of a search query.
--session-timeout MINUTES
The amount of time (in minutes) for the maximum length of a WinRM session.
-t TRANSPORT, --winrm-transport TRANSPORT
The WinRM transport type. Possible values: ssl or plaintext.
--winrm-authentication-protocol PROTOCOL
The authentication protocol to be used during WinRM communication. Possible values: basic, kerberos or negotiate. Default value: negotiate.
--winrm-shell SHELL
The WinRM shell type. Valid choices are cmd, powershell or elevated. Default value: cmd. The elevated shell is similar to the powershell option, but runs the powershell command from a scheduled task.
--winrm-ssl-verify-mode MODE
The peer verification mode that is used during WinRM communication. Possible values: verify_none or verify_peer. Default value: verify_peer.
-x USERNAME, --winrm-user USERNAME
The WinRM user name.

#### Examples¶

Find Uptime for Web Servers

To find the uptime of all web servers, enter:

$knife winrm "role:web" "net stats srv" -x Administrator -P password  Force a chef-client run To force a chef-client run: knife winrm 'ec2-50-xx-xx-124.amazonaws.com' 'chef-client -c c:/chef/client.rb' -m -x admin -P 'password' ec2-50-xx-xx-124.amazonaws.com [date] INFO: Starting Chef Run (Version 0.9.12) ec2-50-xx-xx-124.amazonaws.com [date] WARN: Node ip-0A502FFB has an empty run list. ec2-50-xx-xx-124.amazonaws.com [date] INFO: Chef Run complete in 4.383966 seconds ec2-50-xx-xx-124.amazonaws.com [date] INFO: cleaning the checksum cache ec2-50-xx-xx-124.amazonaws.com [date] INFO: Running report handlers ec2-50-xx-xx-124.amazonaws.com [date] INFO: Report handlers complete  Where in the examples above, [date] represents the date and time the long entry was created. For example: [Fri, 04 Mar 2011 22:00:53 +0000]. Bootstrap a Windows machine using SSH To bootstrap a Microsoft Windows machine using SSH: $ knife bootstrap windows ssh ec2-50-xx-xx-124.compute-1.amazonaws.com -r 'role[webserver],role[production]' -x Administrator -i ~/.ssh/id_rsa


Bootstrap a Windows machine using Windows Remote Management

To bootstrap a Microsoft Windows machine using WinRM:

$knife bootstrap windows winrm ec2-50-xx-xx-124.compute-1.amazonaws.com -r 'role[webserver],role[production]' -x Administrator -P 'super_secret_password'  ## Resources¶ A resource is a statement of configuration policy that: • Describes the desired state for a configuration item • Declares the steps needed to bring that item to the desired state • Specifies a resource type—such as package, template, or service • Lists additional details (also known as resource properties), as necessary • Are grouped into recipes, which describe working configurations ### Common Functionality¶ The following sections describe Microsoft Windows-specific functionality that applies generally to all resources: #### Relative Paths¶ The following relative paths can be used with any resource: #{ENV['HOME']} Use to return the ~ path in Linux and macOS or the %HOMEPATH% in Microsoft Windows. ##### Examples¶ template "#{ENV['HOME']}/chef-getting-started.txt" do source 'chef-getting-started.txt.erb' mode '0755' end  #### Windows File Security¶ To support Microsoft Windows security, the template, file, remote_file, cookbook_file, directory, and remote_directory resources support the use of inheritance and access control lists (ACLs) within recipes. Note Windows File Security applies to the cookbook_file, directory, file, remote_directory, remote_file, and template resources. ##### ACLs¶ The rights property can be used in a recipe to manage access control lists (ACLs), which allow permissions to be given to multiple users and groups. Use the rights property can be used as many times as necessary; the chef-client will apply them to the file or directory as required. The syntax for the rights property is as follows: rights permission, principal, option_type => value  where permission Use to specify which rights are granted to the principal. The possible values are: :read, :write, read_execute, :modify, and :full_control. These permissions are cumulative. If :write is specified, then it includes :read. If :full_control is specified, then it includes both :write and :read. (For those who know the Microsoft Windows API: :read corresponds to GENERIC_READ; :write corresponds to GENERIC_WRITE; :read_execute corresponds to GENERIC_READ and GENERIC_EXECUTE; :modify corresponds to GENERIC_WRITE, GENERIC_READ, GENERIC_EXECUTE, and DELETE; :full_control corresponds to GENERIC_ALL, which allows a user to change the owner and other metadata about a file.) principal Use to specify a group or user name. This is identical to what is entered in the login box for Microsoft Windows, such as user_name, domain\user_name, or user_name@fully_qualified_domain_name. The chef-client does not need to know if a principal is a user or a group. option_type A hash that contains advanced rights options. For example, the rights to a directory that only applies to the first level of children might look something like: rights :write, 'domain\group_name', :one_level_deep => true. Possible option types: Option Type Description :applies_to_children Specify how permissions are applied to children. Possible values: true to inherit both child directories and files; false to not inherit any child directories or files; :containers_only to inherit only child directories (and not files); :objects_only to recursively inherit files (and not child directories). :applies_to_self Indicates whether a permission is applied to the parent directory. Possible values: true to apply to the parent directory or file and its children; false to not apply only to child directories and files. :one_level_deep Indicates the depth to which permissions will be applied. Possible values: true to apply only to the first level of children; false to apply to all children. For example: resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', :applies_to_children => true end  or: rights :read, ['Administrators','Everyone'] rights :full_control, 'Users', :applies_to_children => true rights :write, 'Sally', :applies_to_children => :containers_only, :applies_to_self => false, :one_level_deep => true  Some other important things to know when using the rights attribute: • Only inherited rights remain. All existing explicit rights on the object are removed and replaced. • If rights are not specified, nothing will be changed. The chef-client does not clear out the rights on a file or directory if rights are not specified. • Changing inherited rights can be expensive. Microsoft Windows will propagate rights to all children recursively due to inheritance. This is a normal aspect of Microsoft Windows, so consider the frequency with which this type of action is necessary and take steps to control this type of action if performance is the primary consideration. Use the deny_rights property to deny specific rights to specific users. The ordering is independent of using the rights property. For example, it doesn’t matter if rights are granted to everyone is placed before or after deny_rights :read, ['Julian', 'Lewis'], both Julian and Lewis will be unable to read the document. For example: resource 'x.txt' do rights :read, 'Everyone' rights :write, 'domain\group' rights :full_control, 'group_name_or_user_name' rights :full_control, 'user_name', :applies_to_children => true deny_rights :read, ['Julian', 'Lewis'] end  or: deny_rights :full_control, ['Sally']  ##### Inheritance¶ By default, a file or directory inherits rights from its parent directory. Most of the time this is the preferred behavior, but sometimes it may be necessary to take steps to more specifically control rights. The inherits property can be used to specifically tell the chef-client to apply (or not apply) inherited rights from its parent directory. For example, the following example specifies the rights for a directory: directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' end  and then the following example specifies how to use inheritance to deny access to the child directory: directory 'C:\mordor\mount_doom' do rights :full_control, 'MORDOR\Sauron' inherits false # Sauron is the only person who should have any sort of access end  If the deny_rights permission were to be used instead, something could slip through unless all users and groups were denied. Another example also shows how to specify rights for a directory: directory 'C:\mordor' do rights :read, 'MORDOR\Minions' rights :full_control, 'MORDOR\Sauron' rights :write, 'SHIRE\Frodo' # Who put that there I didn't put that there end  but then not use the inherits property to deny those rights on a child directory: directory 'C:\mordor\mount_doom' do deny_rights :read, 'MORDOR\Minions' # Oops, not specific enough end  Because the inherits property is not specified, the chef-client will default it to true, which will ensure that security settings for existing files remain unchanged. #### Attributes for File-based Resources¶ This resource has the following attributes: Attribute Description group A string or ID that identifies the group owner by group name, including fully qualified group names such as domain\group or group@domain. If this value is not specified, existing groups remain unchanged and new group assignments use the default POSIX group (if available). inherits Microsoft Windows only. Whether a file inherits rights from its parent directory. Default value: true. mode If mode is not specified and if the file already exists, the existing mode on the file is used. If mode is not specified, the file does not exist, and the :create action is specified, the chef-client assumes a mask value of '0777' and then applies the umask for the system on which the file is to be created to the mask value. For example, if the umask on a system is '022', the chef-client uses the default value of '0755'. Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: '755', '0755', or 00755. Values up to '0777' are allowed (no sticky bits) and mean the same in Microsoft Windows as they do in UNIX, where 4 equals GENERIC_READ, 2 equals GENERIC_WRITE, and 1 equals GENERIC_EXECUTE. This property cannot be used to set :full_control. This property has no effect if not specified, but when it and rights are both specified, the effects are cumulative. owner A string or ID that identifies the group owner by user name, including fully qualified user names such as domain\user or user@domain. If this value is not specified, existing owners remain unchanged and new owner assignments use the current user (when necessary). path The full path to the file, including the file name and its extension. Microsoft Windows: A path that begins with a forward slash (/) will point to the root of the current working directory of the chef-client process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (/) is not recommended. rights Microsoft Windows only. The permissions for users and groups in a Microsoft Windows environment. For example: rights <permissions>, <principal>, <options> where <permissions> specifies the rights granted to the principal, <principal> is the group or user name, and <options> is a Hash with one (or more) advanced rights options. Note Use the owner and right attributes and avoid the group and mode attributes whenever possible. The group and mode attributes are not true Microsoft Windows concepts and are provided more for backward compatibility than for best practice. #### Atomic File Updates¶ Atomic updates are used with file-based resources to help ensure that file updates can be made when updating a binary or if disk space runs out. Atomic updates are enabled by default. They can be managed globally using the file_atomic_update setting in the client.rb file. They can be managed on a per-resource basis using the atomic_update property that is available with the cookbook_file, file, remote_file, and template resources. Note On certain platforms, and after a file has been moved into place, the chef-client may modify file permissions to support features specific to those platforms. On platforms with SELinux enabled, the chef-client will fix up the security contexts after a file has been moved into the correct location by running the restorecon command. On the Microsoft Windows platform, the chef-client will create files so that ACL inheritance works as expected. Note Atomic File Updates applies to the template resource. ### batch¶ Use the batch resource to execute a batch script using the cmd.exe interpreter on Windows. The batch resource creates and executes a temporary file (similar to how the script resource behaves), rather than running the command inline. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence. #### Syntax¶ A batch resource block executes a batch script using the cmd.exe interpreter: batch 'echo some env vars' do code <<-EOH echo %TEMP% echo %SYSTEMDRIVE% echo %PATH% echo %WINDIR% EOH end  The full syntax for all of the properties that are available to the batch resource is: batch 'name' do architecture Symbol code String command String, Array creates String cwd String flags String group String, Integer guard_interpreter Symbol interpreter String notifies # see description provider Chef::Provider::Batch returns Integer, Array subscribes # see description timeout Integer, Float user String password String domain String action Symbol # defaults to :run if not specified end  where • batch is the resource • name is the name of the resource block • command is the command to be run and cwd is the location from which the command is run • action identifies the steps the chef-client will take to bring the node into the desired state • architecture, code, command, creates, cwd, flags, group, guard_interpreter, interpreter, provider, returns, timeout, user, password and domain are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. #### Actions¶ This resource has the following actions: :nothing Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the Chef Client run. :run Run a batch file. #### Attributes¶ This resource has the following properties: architecture Ruby Type: Symbol The architecture of the process under which a script is executed. If a value is not provided, the chef-client defaults to the correct value for the architecture, as determined by Ohai. An exception is raised when anything other than :i386 is specified for a 32-bit process. Possible values: :i386 (for 32-bit processes) and :x86_64 (for 64-bit processes). code Ruby Type: String A quoted (” “) string of code to be executed. command Ruby Types: String, Array The name of the command to be executed. creates Ruby Type: String Prevent a command from creating a file when that file already exists. cwd Ruby Type: String The current working directory from which a command is run. flags Ruby Type: String One or more command line flags that are passed to the interpreter when a command is invoked. group Ruby Types: String, Integer The group name or group ID that must be changed before running a command. guard_interpreter Ruby Type: Symbol Default value: :batch. When this property is set to :batch, the 64-bit version of the cmd.exe shell will be used to evaluate strings values for the not_if and only_if properties. Set this value to :default to use the 32-bit version of the cmd.exe shell. Changed in Chef Client 12.0 to default to the specified property. ignore_failure Ruby Types: TrueClass, FalseClass Continue running a recipe if a resource fails for any reason. Default value: false. interpreter Ruby Type: String The script interpreter to use during code execution. Changing the default value of this property is not supported. notifies Ruby Type: Symbol, ‘Chef::Resource[String]’ A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified. A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available: :before Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. :delayed Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run. :immediate, :immediately Specifies that a notification should be run immediately, per resource notified. The syntax for notifies is: notifies :action, 'resource[name]', :timer  provider Ruby Type: Chef Class Optional. Explicitly specifies a provider. retries Ruby Type: Integer The number of times to catch exceptions and retry the resource. Default value: 0. retry_delay Ruby Type: Integer The retry delay (in seconds). Default value: 2. returns Ruby Types: Integer, Array The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. Default value: 0. subscribes Ruby Type: Symbol, ‘Chef::Resource[String]’ A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action. Note that subscribes does not apply the specified action to the resource that it listens to - for example: file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end  In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected. A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available: :before Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. :delayed Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run. :immediate, :immediately Specifies that a notification should be run immediately, per resource notified. The syntax for subscribes is: subscribes :action, 'resource[name]', :timer  timeout Ruby Types: Integer, Float The amount of time (in seconds) a command is to wait before timing out. Default value: 3600. user Ruby Types: String The user name of the user identity with which to launch the new process. Default value: nil. The user name may optionally be specifed with a domain, i.e. domainuser or user@my.dns.domain.com via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain attribute. On Windows only, if this property is specified, the password property must be specified. password Ruby Types: String Windows only: The password of the user specified by the user property. Default value: nil. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified. domain Ruby Types: String Windows only: The domain of the user user specified by the user property. Default value: nil. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running Chef client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property. Note See http://technet.microsoft.com/en-us/library/bb490880.aspx for more information about the cmd.exe interpreter. #### Examples¶ The following examples demonstrate various approaches for using resources in recipes. If you want to see examples of how Chef uses resources in recipes, take a closer look at the cookbooks that Chef authors and maintains: https://github.com/chef-cookbooks. Unzip a file, and then move it To run a batch file that unzips and then moves Ruby, do something like: batch 'unzip_and_move_ruby' do code <<-EOH 7z.exe x #{Chef::Config[:file_cache_path]}/ruby-1.8.7-p352-i386-mingw32.7z -oC:\\source -r -y xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y EOH end batch 'echo some env vars' do code <<-EOH echo %TEMP% echo %SYSTEMDRIVE% echo %PATH% echo %WINDIR% EOH end  or: batch 'unzip_and_move_ruby' do code <<-EOH 7z.exe x #{Chef::Config[:file_cache_path]}/ruby-1.8.7-p352-i386-mingw32.7z -oC:\\source -r -y xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y EOH end batch 'echo some env vars' do code 'echo %TEMP%\\necho %SYSTEMDRIVE%\\necho %PATH%\\necho %WINDIR%' end  ### dsc_resource¶ A resource defines the desired state for a single configuration item present on a node that is under management by Chef. A resource collection—one (or more) individual resources—defines the desired state for the entire node. During a chef-client run, the current state of each resource is tested, after which the chef-client will take any steps that are necessary to repair the node and bring it back into the desired state. Desired State Configuration (DSC) is a feature of Windows PowerShell that provides a set of language extensions, cmdlets, and resources that can be used to declaratively configure software. DSC is similar to Chef, in that both tools are idempotent, take similar approaches to the concept of resources, describe the configuration of a system, and then take the steps required to do that configuration. The most important difference between Chef and DSC is that Chef uses Ruby and DSC is exposed as configuration data from within Windows PowerShell. The dsc_resource resource allows any DSC resource to be used in a Chef recipe, as well as any custom resources that have been added to your Windows PowerShell environment. Microsoft frequently adds new resources to the DSC resource collection. Warning Using the dsc_resource has the following requirements: • Windows Management Framework (WMF) 5.0 February Preview (or higher), which includes Windows PowerShell 5.0.10018.0 (or higher). • The RefreshMode configuration setting in the Local Configuration Manager must be set to Disabled. NOTE: Starting with the chef-client 12.6 release, this requirement applies only for versions of Windows PowerShell earlier than 5.0.10586.0. The latest version of Windows Management Framework (WMF) 5 has relaxed the limitation that prevented the chef-client from running in non-disabled refresh mode. • The dsc_script resource may not be used in the same run-list with the dsc_resource. This is because the dsc_script resource requires that RefreshMode in the Local Configuration Manager be set to Push, whereas the dsc_resource resource requires it to be set to Disabled. NOTE: Starting with the chef-client 12.6 release, this requirement applies only for versions of Windows PowerShell earlier than 5.0.10586.0. The latest version of Windows Management Framework (WMF) 5 has relaxed the limitation that prevented the chef-client from running in non-disabled refresh mode, which allows the Local Configuration Manager to be set to Push. • The dsc_resource resource can only use binary- or script-based resources. Composite DSC resources may not be used. This is because composite resources aren’t “real” resources from the perspective of the the Local Configuration Manager (LCM). Composite resources are used by the “configuration” keyword from the PSDesiredStateConfiguration module, and then evaluated in that context. When using DSC to create the configuration document (the Managed Object Framework (MOF) file) from the configuration command, the composite resource is evaluated. Any individual resources from that composite resource are written into the Managed Object Framework (MOF) document. As far as the Local Configuration Manager (LCM) is concerned, there is no such thing as a composite resource. Unless that changes, the dsc_resource resource and/or Invoke-DscResource command cannot directly use them. #### Syntax¶ A dsc_resource resource block allows DSC resources to be used in a Chef recipe. For example, the DSC Archive resource: Archive ExampleArchive { Ensure = "Present" Path = "C:\Users\Public\Documents\example.zip" Destination = "C:\Users\Public\Documents\ExtractionPath" }  and then the same dsc_resource with Chef: dsc_resource 'example' do resource :archive property :ensure, 'Present' property :path, "C:\Users\Public\Documents\example.zip" property :destination, "C:\Users\Public\Documents\ExtractionPath" end  The full syntax for all of the properties that are available to the dsc_resource resource is: dsc_resource 'name' do module_name String module_version String notifies # see description property Symbol resource String subscribes # see description end  where • dsc_resource is the resource • name is the name of the resource block • property is zero (or more) properties in the DSC resource, where each property is entered on a separate line, :dsc_property_name is the case-insensitive name of that property, and "property_value" is a Ruby value to be applied by the chef-client • module_name, module_version, property, and resource are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. #### Attributes¶ This resource has the following properties: ignore_failure Ruby Types: TrueClass, FalseClass Continue running a recipe if a resource fails for any reason. Default value: false. module_name Ruby Type: String The name of the module from which a DSC resource originates. If this property is not specified, it will be inferred. module_version Ruby Type: String The version number of the module to use. Powershell 5.0.10018.0 (or higher) supports having multiple versions of a module installed. This should be specified along with the module_name. New in Chef Client 12.19. notifies Ruby Type: Symbol, ‘Chef::Resource[String]’ A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified. A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available: :before Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. :delayed Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run. :immediate, :immediately Specifies that a notification should be run immediately, per resource notified. The syntax for notifies is: notifies :action, 'resource[name]', :timer  property Ruby Type: Symbol A property from a Desired State Configuration (DSC) resource. Use this property multiple times, one for each property in the Desired State Configuration (DSC) resource. The format for this property must follow property :dsc_property_name, "property_value" for each DSC property added to the resource block. The :dsc_property_name must be a symbol. Use the following Ruby types to define property_value: Ruby Windows PowerShell Array Object[] Chef::Util::Powershell:PSCredential PSCredential FalseClass bool($false)
Fixnum Integer
Float Double
Hash Hashtable
TrueClass bool($true) These are converted into the corresponding Windows PowerShell type during the chef-client run. resource Ruby Type: String The name of the DSC resource. This value is case-insensitive and must be a symbol that matches the name of the DSC resource. For built-in DSC resources, use the following values: Value Description :archive Use to to unpack archive (.zip) files. :environment Use to to manage system environment variables. :file Use to to manage files and directories. :group Use to to manage local groups. :log Use to to log configuration messages. :package Use to to install and manage packages. :registry Use to to manage registry keys and registry key values. :script Use to to run Powershell script blocks. :service Use to to manage services. :user Use to to manage local user accounts. :windowsfeature Use to to add or remove Windows features and roles. :windowsoptionalfeature Use to configure Microsoft Windows optional features. :windowsprocess Use to to configure Windows processes. Any DSC resource may be used in a Chef recipe. For example, the DSC Resource Kit contains resources for configuring Active Directory components, such as xADDomain, xADDomainController, and xADUser. Assuming that these resources are available to the chef-client, the corresponding values for the resource attribute would be: :xADDomain, :xADDomainController, and xADUser. retries Ruby Type: Integer The number of times to catch exceptions and retry the resource. Default value: 0. retry_delay Ruby Type: Integer The retry delay (in seconds). Default value: 2. subscribes Ruby Type: Symbol, ‘Chef::Resource[String]’ A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action. Note that subscribes does not apply the specified action to the resource that it listens to - for example: file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end  In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected. A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available: :before Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. :delayed Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run. :immediate, :immediately Specifies that a notification should be run immediately, per resource notified. The syntax for subscribes is: subscribes :action, 'resource[name]', :timer  #### Examples¶ Open a Zip file dsc_resource 'example' do resource :archive property :ensure, 'Present' property :path, 'C:\Users\Public\Documents\example.zip' property :destination, 'C:\Users\Public\Documents\ExtractionPath' end  Manage users and groups dsc_resource 'demogroupadd' do resource :group property :groupname, 'demo1' property :ensure, 'present' end dsc_resource 'useradd' do resource :user property :username, 'Foobar1' property :fullname, 'Foobar1' property :password, ps_credential('P@assword!') property :ensure, 'present' end dsc_resource 'AddFoobar1ToUsers' do resource :Group property :GroupName, 'demo1' property :MembersToInclude, ['Foobar1'] end  Create a test message queue The following example creates a file on a node (based on one that is located in a cookbook), unpacks the MessageQueue.zip Windows PowerShell module, and then uses the dsc_resource to ensure that Message Queuing (MSMQ) sub-features are installed, a test queue is created, and that permissions are set on the test queue: cookbook_file 'cMessageQueue.zip' do path "#{Chef::Config[:file_cache_path]}\\MessageQueue.zip" action :create_if_missing end windows_zipfile "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules" do source "#{Chef::Config[:file_cache_path]}\\MessageQueue.zip" action :unzip end dsc_resource 'install-sub-features' do resource :windowsfeature property :ensure, 'Present' property :name, 'msmq' property :IncludeAllSubFeature, true end dsc_resource 'create-test-queue' do resource :cPrivateMsmqQueue property :ensure, 'Present' property :name, 'Test_Queue' end dsc_resource 'set-permissions' do resource :cPrivateMsmqQueuePermissions property :ensure, 'Present' property :name, 'Test_Queue_Permissions' property :QueueNames, 'Test_Queue' property :ReadUsers, node['msmq']['read_user'] end  Example to show usage of module properties dsc_resource 'test-cluster' do resource :xCluster module_name 'xFailOverCluster' module_version '1.6.0.0' property :name, 'TestCluster' property :staticipaddress, '10.0.0.3' property :domainadministratorcredential, ps_credential('abcd') end  ### dsc_script¶ A resource defines the desired state for a single configuration item present on a node that is under management by Chef. A resource collection—one (or more) individual resources—defines the desired state for the entire node. During a chef-client run, the current state of each resource is tested, after which the chef-client will take any steps that are necessary to repair the node and bring it back into the desired state. Windows PowerShell is a task-based command-line shell and scripting language developed by Microsoft. Windows PowerShell uses a document-oriented approach for managing Microsoft Windows-based machines, similar to the approach that is used for managing Unix and Linux-based machines. Windows PowerShell is a tool-agnostic platform that supports using Chef for configuration management. Desired State Configuration (DSC) is a feature of Windows PowerShell that provides a set of language extensions, cmdlets, and resources that can be used to declaratively configure software. DSC is similar to Chef, in that both tools are idempotent, take similar approaches to the concept of resources, describe the configuration of a system, and then take the steps required to do that configuration. The most important difference between Chef and DSC is that Chef uses Ruby and DSC is exposed as configuration data from within Windows PowerShell. Many DSC resources are comparable to built-in Chef resources. For example, both DSC and Chef have file, package, and service resources. The dsc_script resource is most useful for those DSC resources that do not have a direct comparison to a resource in Chef, such as the Archive resource, a custom DSC resource, an existing DSC script that performs an important task, and so on. Use the dsc_script resource to embed the code that defines a DSC configuration directly within a Chef recipe. New in Chef Client 12.2. Changed in Chef Client 12.6. Note Windows PowerShell 4.0 is required for using the dsc_script resource with Chef. Note The WinRM service must be enabled. (Use winrm quickconfig to enable the service.) Warning The dsc_script resource may not be used in the same run-list with the dsc_resource. This is because the dsc_script resource requires that RefreshMode in the Local Configuration Manager be set to Push, whereas the dsc_resource resource requires it to be set to Disabled. #### Syntax¶ A dsc_script resource block embeds the code that defines a DSC configuration directly within a Chef recipe: dsc_script 'get-dsc-resource-kit' do code <<-EOH Archive reskit { ensure = 'Present' path = "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip" destination = "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules" } EOH end  where the remote_file resource is first used to download the DSCResourceKit620082014.zip file. The full syntax for all of the properties that are available to the dsc_script resource is: dsc_script 'name' do code String command String configuration_data String configuration_data_script String configuration_name String cwd String environment Hash flags Hash imports Array notifies # see description subscribes # see description timeout Integer action Symbol # defaults to :run if not specified end  where • dsc_script is the resource • name is the name of the resource block • action identifies the steps the chef-client will take to bring the node into the desired state • code, command, configuration_data, configuration_data_script, configuration_name, cwd, environment, flags, imports, and timeout are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. #### Actions¶ This resource has the following actions: :nothing Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the Chef Client run. :run Default. Use to run the DSC configuration defined as defined in this resource. #### Attributes¶ This resource has the following properties: code Ruby Type: String The code for the DSC configuration script. This property may not be used in the same recipe as the command property. command Ruby Type: String The path to a valid Windows PowerShell data file that contains the DSC configuration script. This data file must be capable of running independently of Chef and must generate a valid DSC configuration. This property may not be used in the same recipe as the code property. configuration_data Ruby Type: String The configuration data for the DSC script. The configuration data must be a valid Windows Powershell data file. This property may not be used in the same recipe as the configuration_data_script property. configuration_data_script Ruby Type: String The path to a valid Windows PowerShell data file that also contains a node called localhost. This property may not be used in the same recipe as the configuration_data property. configuration_name Ruby Type: String The name of a valid Windows PowerShell cmdlet. The name may only contain letter (a-z, A-Z), number (0-9), and underscore (_) characters and should start with a letter. The name may not be null or empty. This property may not be used in the same recipe as the code property. cwd Ruby Type: String The current working directory. environment Ruby Type: Hash A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.) flags Ruby Type: Hash Pass parameters to the DSC script that is specified by the command property. Parameters are defined as key-value pairs, where the value of each key is the parameter to pass. This property may not be used in the same recipe as the code property. For example: flags ({ :EditorChoice => 'emacs', :EditorFlags => '--maximized' }). Default value: nil. ignore_failure Ruby Types: TrueClass, FalseClass Continue running a recipe if a resource fails for any reason. Default value: false. imports Ruby Type: Array Warning This property MUST be used with the code attribute. Use to import DSC resources from a module. To import all resources from a module, specify only the module name: imports 'module_name'  To import specific resources, specify the module name, and then specify the name for each resource in that module to import: imports 'module_name', 'resource_name_a', 'resource_name_b', ...  For example, to import all resources from a module named cRDPEnabled: imports 'cRDPEnabled'  To import only the PSHOrg_cRDPEnabled resource: imports 'cRDPEnabled', 'PSHOrg_cRDPEnabled'  New in Chef Client 12.1. notifies Ruby Type: Symbol, ‘Chef::Resource[String]’ A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified. A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available: :before Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. :delayed Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run. :immediate, :immediately Specifies that a notification should be run immediately, per resource notified. The syntax for notifies is: notifies :action, 'resource[name]', :timer  retries Ruby Type: Integer The number of times to catch exceptions and retry the resource. Default value: 0. retry_delay Ruby Type: Integer The retry delay (in seconds). Default value: 2. subscribes Ruby Type: Symbol, ‘Chef::Resource[String]’ A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action. Note that subscribes does not apply the specified action to the resource that it listens to - for example: file '/etc/nginx/ssl/example.crt' do mode '0600' owner 'root' end service 'nginx' do subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end  In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected. A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available: :before Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located. :delayed Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run. :immediate, :immediately Specifies that a notification should be run immediately, per resource notified. The syntax for subscribes is: subscribes :action, 'resource[name]', :timer  timeout Ruby Types: Integer The amount of time (in seconds) a command is to wait before timing out. #### Examples¶ The following examples demonstrate various approaches for using resources in recipes. If you want to see examples of how Chef uses resources in recipes, take a closer look at the cookbooks that Chef authors and maintains: https://github.com/chef-cookbooks. Specify DSC code directly DSC data can be specified directly in a recipe: dsc_script 'emacs' do code <<-EOH Environment 'texteditor' { Name = 'EDITOR' Value = 'c:\\emacs\\bin\\emacs.exe' } EOH end  Specify DSC code using a Windows Powershell data file Use the command property to specify the path to a Windows PowerShell data file. For example, the following Windows PowerShell script defines the DefaultEditor: Configuration 'DefaultEditor' { Environment 'texteditor' { Name = 'EDITOR' Value = 'c:\emacs\bin\emacs.exe' } }  Use the following recipe to specify the location of that data file: dsc_script 'DefaultEditor' do command 'c:\dsc_scripts\emacs.ps1' end  Pass parameters to DSC configurations If a DSC script contains configuration data that takes parameters, those parameters may be passed using the flags property. For example, the following Windows PowerShell script takes parameters for the EditorChoice and EditorFlags settings: $choices = @{'emacs' = 'c:\emacs\bin\emacs';'vi' = 'c:\vim\vim.exe';'powershell' = 'powershell_ise.exe'}
Configuration 'DefaultEditor'
{
[CmdletBinding()]
param
(
$EditorChoice,$EditorFlags = ''
)
Environment 'TextEditor'
{
Name = 'EDITOR'
Value =  "$($choices[$EditorChoice])$EditorFlags"
}
}


Use the following recipe to set those parameters:

dsc_script 'DefaultEditor' do
flags ({ :EditorChoice => 'emacs', :EditorFlags => '--maximized' })
command 'c:\dsc_scripts\editors.ps1'
end


Use custom configuration data

Configuration data in DSC scripts may be customized from a recipe. For example, scripts are typically customized to set the behavior for Windows PowerShell credential data types. Configuration data may be specified in one of three ways:

• By using the configuration_data attribute
• By using the configuration_data_script attribute
• By specifying the path to a valid Windows PowerShell data file

The following example shows how to specify custom configuration data using the configuration_data property:

dsc_script 'BackupUser' do
configuration_data <<-EOH
@{
AllNodes = @(
@{
NodeName = "localhost";
PSDscAllowPlainTextPassword = $true }) } EOH code <<-EOH$user = 'backup'
$password = ConvertTo-SecureString -String "YourPass$(random)" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList$user, $password User$user
{
UserName = $user Password =$cred
Description = 'Backup operator'
Ensure = "Present"
Disabled = $false PasswordNeverExpires =$true
PasswordChangeRequired = $false } EOH configuration_data <<-EOH @{ AllNodes = @( @{ NodeName = "localhost"; PSDscAllowPlainTextPassword =$true
})
}
EOH
end


The following example shows how to specify custom configuration data using the configuration_name property. For example, the following Windows PowerShell script defines the vi configuration:

Configuration 'emacs'
{
Environment 'TextEditor'
{
Name = 'EDITOR'
Value = 'c:\emacs\bin\emacs.exe'
}
}

Configuration 'vi'
{
Environment 'TextEditor'
{
Name = 'EDITOR'
Value = 'c:\vim\bin\vim.exe'
}
}


Use the following recipe to specify that configuration:

dsc_script 'EDITOR' do
configuration_name 'vi'
command 'C:\dsc_scripts\editors.ps1'
end


Using DSC with other Chef resources

The dsc_script resource can be used with other resources. The following example shows how to download a file using the remote_file resource, and then uncompress it using the DSC Archive resource:

remote_file "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip" do
source 'http://gallery.technet.microsoft.com/DSC-Resource-Kit-All-c449312d/file/124481/1/DSC%20Resource%20Kit%20Wave%206%2008282014.zip'
end

dsc_script 'get-dsc-resource-kit' do
code <<-EOH
Archive reskit
{
ensure = 'Present'
path = "#{Chef::Config[:file_cache_path]}\\DSCResourceKit620082014.zip"
destination = "#{ENV['PROGRAMW6432']}\\WindowsPowerShell\\Modules"
}
EOH
end


### env¶

Use the env resource to manage environment keys in Microsoft Windows. After an environment key is set, Microsoft Windows must be restarted before the environment key will be available to the Task Scheduler.

#### Syntax¶

A env resource block manages environment keys in Microsoft Windows:

env 'ComSpec' do
value 'C:\\Windows\\system32\\cmd.exe'
end


The full syntax for all of the properties that are available to the env resource is:

env 'name' do
delim                      String
key_name                   String # defaults to 'name' if not specified
notifies                   # see description
provider                   Chef::Provider::Env
subscribes                 # see description
value                      String
action                     Symbol # defaults to :create if not specified
end


where

• env is the resource
• name is the name of the resource block
• action identifies the steps the chef-client will take to bring the node into the desired state
• delim, key_name, provider, and value are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

#### Actions¶

This resource has the following actions:

:create
Default. Create an environment variable. If an environment variable already exists (but does not match), update that environment variable to match.
:delete
Delete an environment variable.
:modify
Modify an existing environment variable. This prepends the new value to the existing value, using the delimiter specified by the delim property.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the Chef Client run.

#### Attributes¶

This resource has the following properties:

delim

Ruby Type: String

The delimiter that is used to separate multiple values for a single key.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

key_name

Ruby Type: String

The name of the key that is to be created, deleted, or modified. Default value: the name of the resource block See “Syntax” section above for more information.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider.

retries

Ruby Type: Integer

The number of times to catch exceptions and retry the resource. Default value: 0.

retry_delay

Ruby Type: Integer

The retry delay (in seconds). Default value: 2.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
mode '0600'
owner 'root'
end

service 'nginx' do
end


In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

value

Ruby Type: String

The value with which key_name is set.

#### Examples¶

The following examples demonstrate various approaches for using resources in recipes. If you want to see examples of how Chef uses resources in recipes, take a closer look at the cookbooks that Chef authors and maintains: https://github.com/chef-cookbooks.

Set an environment variable

env 'ComSpec' do
value "C:\\Windows\\system32\\cmd.exe"
end


### powershell_script¶

Use the powershell_script resource to execute a script using the Windows PowerShell interpreter, much like how the script and script-based resources—bash, csh, perl, python, and ruby—are used. The powershell_script is specific to the Microsoft Windows platform and the Windows PowerShell interpreter.

The powershell_script resource creates and executes a temporary file (similar to how the script resource behaves), rather than running the command inline. Commands that are executed with this resource are (by their nature) not idempotent, as they are typically unique to the environment in which they are run. Use not_if and only_if to guard this resource for idempotence.

#### Syntax¶

A powershell_script resource block executes a batch script using the Windows PowerShell interpreter. For example, writing to an interpolated path:

powershell_script 'write-to-interpolated-path' do
code <<-EOH
$stream = [System.IO.StreamWriter] "#{Chef::Config[:file_cache_path]}/powershell-test.txt"$stream.WriteLine("In #{Chef::Config[:file_cache_path]}...word.")
$stream.close() EOH end  The full syntax for all of the properties that are available to the powershell_script resource is: powershell_script 'name' do architecture Symbol code String command String, Array convert_boolean_return TrueClass, FalseClass creates String cwd String environment Hash flags String group String, Integer guard_interpreter Symbol interpreter String notifies # see description provider Chef::Provider::PowershellScript returns Integer, Array sensitive TrueClass, FalseClass subscribes # see description timeout Integer, Float user String password String domain String action Symbol # defaults to :run if not specified elevated TrueClass, FalseClass end  where • powershell_script is the resource • name is the name of the resource block • command is the command to be run and cwd is the location from which the command is run • action identifies the steps the chef-client will take to bring the node into the desired state • architecture, code, command, convert_boolean_return, creates, cwd, environment, flags, group, guard_interpreter, interpreter, provider, returns, sensitive, timeout, user, password, domain and elevated are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource. #### Actions¶ This resource has the following actions: :nothing Inherited from execute resource. Prevent a command from running. This action is used to specify that a command is run only when another resource notifies it. :run Default. Run the script. #### Attributes¶ This resource has the following properties: architecture Ruby Type: Symbol The architecture of the process under which a script is executed. If a value is not provided, the chef-client defaults to the correct value for the architecture, as determined by Ohai. An exception is raised when anything other than :i386 is specified for a 32-bit process. Possible values: :i386 (for 32-bit processes) and :x86_64 (for 64-bit processes). code Ruby Type: String A quoted (” “) string of code to be executed. command Ruby Types: String, Array The name of the command to be executed. Default value: the name of the resource block See “Syntax” section above for more information. convert_boolean_return Ruby Types: TrueClass, FalseClass Return 0 if the last line of a command is evaluated to be true or to return 1 if the last line is evaluated to be false. Default value: false. When the guard_interpreter common attribute is set to :powershell_script, a string command will be evaluated as if this value were set to true. This is because the behavior of this attribute is similar to the value of the "$?" expression common in UNIX interpreters. For example, this:

powershell_script 'make_safe_backup' do
guard_interpreter :powershell_script
code 'cp ~/data/nodes.json ~/data/nodes.bak'
not_if 'test-path ~/data/nodes.bak'
end


is similar to:

bash 'make_safe_backup' do
code 'cp ~/data/nodes.json ~/data/nodes.bak'
not_if 'test -e ~/data/nodes.bak'
end

creates

Ruby Type: String

Inherited from execute resource. Prevent a command from creating a file when that file already exists.

cwd

Ruby Type: String

Inherited from execute resource. The current working directory from which a command is run.

environment

Ruby Type: Hash

Inherited from execute resource. A Hash of environment variables in the form of ({"ENV_VARIABLE" => "VALUE"}). (These variables must exist for a command to be run successfully.)

flags

Ruby Type: String

A string that is passed to the Windows PowerShell command. Default value: -NoLogo, -NonInteractive, -NoProfile, -ExecutionPolicy RemoteSigned, -InputFormat None, -File.

group

Ruby Types: String, Integer

Inherited from execute resource. The group name or group ID that must be changed before running a command.

guard_interpreter

Ruby Type: Symbol

Default value: :powershell_script. When this property is set to :powershell_script, the 64-bit version of the Windows PowerShell shell will be used to evaluate strings values for the not_if and only_if properties. Set this value to :default to use the 32-bit version of the cmd.exe shell.

Changed in Chef Client 12.0 to default to the specified property.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

interpreter

Ruby Type: String

The script interpreter to use during code execution. Changing the default value of this property is not supported.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider.

retries

Ruby Type: Integer

The number of times to catch exceptions and retry the resource. Default value: 0.

retry_delay

Ruby Type: Integer

The retry delay (in seconds). Default value: 2.

returns

Ruby Types: Integer, Array

Inherited from execute resource. The return value for a command. This may be an array of accepted values. An exception is raised when the return value(s) do not match. Default value: 0.

sensitive

Ruby Types: TrueClass, FalseClass

Ensure that sensitive resource data is not logged by the chef-client. Default value: false.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
mode '0600'
owner 'root'
end

service 'nginx' do
end


In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

timeout

Ruby Types: Integer, Float

Inherited from execute resource. The amount of time (in seconds) a command is to wait before timing out. Default value: 3600.

user

Ruby Types: String

The user name of the user identity with which to launch the new process. Default value: nil. The user name may optionally be specified with a domain, i.e. domainuser or user@my.dns.domain.com via Universal Principal Name (UPN)format. It can also be specified without a domain simply as user if the domain is instead specified using the domain attribute. On Windows only, if this property is specified, the password property must be specified.

password

Ruby Types: String

Windows only: The password of the user specified by the user property. Default value: nil. This property is mandatory if user is specified on Windows and may only be specified if user is specified. The sensitive property for this resource will automatically be set to true if password is specified.

domain

Ruby Types: String

Windows only: The domain of the user user specified by the user property. Default value: nil. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running Chef client is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property.

elevated

Ruby Type: TrueClass, FalseClass

Determines whether the script will run with elevated permissions to circumvent User Access Control (UAC) interactively blocking the process.

This will cause the process to be run under a batch login instead of an interactive login. The user running Chef needs the “Replace a process level token” and “Adjust Memory Quotas for a process” permissions. The user that is running the command needs the “Log on as a batch job” permission.

Because this requires a login, the user and password properties are required.

#### Examples¶

The following examples demonstrate various approaches for using resources in recipes. If you want to see examples of how Chef uses resources in recipes, take a closer look at the cookbooks that Chef authors and maintains: https://github.com/chef-cookbooks.

Write to an interpolated path

powershell_script 'write-to-interpolated-path' do
code <<-EOH
$stream = [System.IO.StreamWriter] "#{Chef::Config[:file_cache_path]}/powershell-test.txt"$stream.WriteLine("In #{Chef::Config[:file_cache_path]}...word.")
$stream.close() EOH end  Change the working directory powershell_script 'cwd-then-write' do cwd Chef::Config[:file_cache_path] code <<-EOH$stream = [System.IO.StreamWriter] "C:/powershell-test2.txt"
$pwd = pwd$stream.WriteLine("This is the contents of: $pwd")$dirs = dir
foreach ($dir in$dirs) {
$stream.WriteLine($dir.fullname)
}
$stream.close() EOH end  Change the working directory in Microsoft Windows powershell_script 'cwd-to-win-env-var' do cwd '%TEMP%' code <<-EOH$stream = [System.IO.StreamWriter] "./temp-write-from-chef.txt"
$stream.WriteLine("chef on windows rox yo!")$stream.close()
EOH
end


Pass an environment variable to a script

powershell_script 'read-env-var' do
cwd Chef::Config[:file_cache_path]
environment ({'foo' => 'BAZ'})
code <<-EOH
$stream = [System.IO.StreamWriter] "./test-read-env-var.txt"$stream.WriteLine("FOO is $env:foo")$stream.close()
EOH
end


### registry_key¶

Use the registry_key resource to create and delete registry keys in Microsoft Windows.

#### Syntax¶

A registry_key resource block creates and deletes registry keys in Microsoft Windows:

registry_key "HKEY_LOCAL_MACHINE\\...\\System" do
values [{
name: "NewRegistryKeyValue",
type: :multi_string,
data: ['foo\0bar\0\0']
}]
action :create
end


Use multiple registry key entries with key values that are based on node attributes:

registry_key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\name_of_registry_key' do
values [{name: 'key_name', type: :string, data: 'C:\Windows\System32\file_name.bmp'},
{name: 'key_name', type: :string, data: node['node_name']['attribute']['value']},
{name: 'key_name', type: :string, data: node['node_name']['attribute']['value']}
]
action :create
end


The full syntax for all of the properties that are available to the registry_key resource is:

registry_key 'name' do
architecture               Symbol
key                        String # defaults to 'name' if not specified
notifies                   # see description
provider                   Chef::Provider::Windows::Registry
recursive                  TrueClass, FalseClass
subscribes                 # see description
values                     Hash, Array
action                     Symbol # defaults to :create if not specified
end


where

• registry_key is the resource

• name is the name of the resource block

• values is a hash that contains at least one registry key to be created or deleted. Each registry key in the hash is grouped by brackets in which the name:, type:, and data: values for that registry key are specified.

• type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD.

Warning

:multi_string must be an array, even if there is only a single string.

• action identifies the steps the chef-client will take to bring the node into the desired state

• architecture, key, provider, recursive and values are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

##### Path Separators¶

A Microsoft Windows registry key can be used as a string in Ruby code, such as when a registry key is used as the name of a recipe. In Ruby, when a registry key is enclosed in a double-quoted string (" "), the same backslash character (\) that is used to define the registry key path separator is also used in Ruby to define an escape character. Therefore, the registry key path separators must be escaped when they are enclosed in a double-quoted string. For example, the following registry key:

HKCU\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Themes


may be enclosed in a single-quoted string with a single backslash:

'HKCU\SOFTWARE\path\to\key\Themes'


or may be enclosed in a double-quoted string with an extra backslash as an escape character:

"HKCU\\SOFTWARE\\path\\to\\key\\Themes"


#### Recipe DSL Methods¶

Six methods are present in the Recipe DSL to help verify the registry during a chef-client run on the Microsoft Windows platform—registry_data_exists?, registry_get_subkeys, registry_get_values, registry_has_subkeys?, registry_key_exists?, and registry_value_exists?—these helpers ensure the powershell_script resource is idempotent.

Note

The recommended order in which registry key-specific methods should be used within a recipe is: key_exists?, value_exists?, data_exists?, get_values, has_subkeys?, and then get_subkeys.

##### registry_data_exists?¶

Use the registry_data_exists? method to find out if a Microsoft Windows registry key contains the specified data of the specified type under the value.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_data_exists? method is as follows:

registry_data_exists?(
KEY_PATH,
{ name: 'NAME', type: TYPE, data: DATA },
ARCHITECTURE
)


where:

• KEY_PATH is the path to the registry key value. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
• { name: 'NAME', type: TYPE, data: DATA } is a hash that contains the expected name, type, and data of the registry key value
• type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD.
• ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This method will return true or false.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

##### registry_get_subkeys¶

Use the registry_get_subkeys method to get a list of registry key values that are present for a Microsoft Windows registry key.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_get_subkeys method is as follows:

subkey_array = registry_get_subkeys(KEY_PATH, ARCHITECTURE)


where:

• KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
• ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This returns an array of registry key values.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

##### registry_get_values¶

Use the registry_get_values method to get the registry key values (name, type, and data) for a Microsoft Windows registry key.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_get_values method is as follows:

subkey_array = registry_get_values(KEY_PATH, ARCHITECTURE)


where:

• KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
• ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This returns an array of registry key values.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

##### registry_has_subkeys?¶

Use the registry_has_subkeys? method to find out if a Microsoft Windows registry key has one (or more) values.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_has_subkeys? method is as follows:

registry_has_subkeys?(KEY_PATH, ARCHITECTURE)


where:

• KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
• ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This method will return true or false.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

##### registry_key_exists?¶

Use the registry_key_exists? method to find out if a Microsoft Windows registry key exists at the specified path.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_key_exists? method is as follows:

registry_key_exists?(KEY_PATH, ARCHITECTURE)


where:

• KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
• ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This method will return true or false. (Any registry key values that are associated with this registry key are ignored.)

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

##### registry_value_exists?¶

Use the registry_value_exists? method to find out if a registry key value exists. Use registry_data_exists? to test for the type and data of a registry key value.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_value_exists? method is as follows:

registry_value_exists?(
KEY_PATH,
{ name: 'NAME' },
ARCHITECTURE
)


where:

• KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
• { name: 'NAME' } is a hash that contains the name of the registry key value; if either type: or :value are specified in the hash, they are ignored
• type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD.
• ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This method will return true or false.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

#### Actions¶

This resource has the following actions:

:create
Default. Create a registry key. If a registry key already exists (but does not match), update that registry key to match.
:create_if_missing
Create a registry key if it does not exist. Also, create a registry key value if it does not exist.
:delete
Delete the specified values for a registry key.
:delete_key
Delete the specified registry key and all of its subkeys.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the Chef Client run.

Note

Be careful when using the :delete_key action with the recursive attribute. This will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by the chef-client.

#### Attributes¶

This resource has the following properties:

architecture

Ruby Type: Symbol

The architecture of the node for which keys are to be created or deleted. Possible values: :i386 (for nodes with a 32-bit registry), :x86_64 (for nodes with a 64-bit registry), and :machine (to have the chef-client determine the architecture during the chef-client run). Default value: :machine.

In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

key

Ruby Type: String

The path to the location in which a registry key is to be created or from which a registry key is to be deleted. Default value: the name of the resource block See “Syntax” section above for more information. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider.

recursive

Ruby Types: TrueClass, FalseClass

When creating a key, this value specifies that the required keys for the specified path are to be created. When using the :delete_key action in a recipe, and if the registry key has subkeys, then set the value for this property to true.

Note

Be careful when using the :delete_key action with the recursive attribute. This will delete the registry key, all of its values and all of the names, types, and data associated with them. This cannot be undone by the chef-client.

retries

Ruby Type: Integer

The number of times to catch exceptions and retry the resource. Default value: 0.

retry_delay

Ruby Type: Integer

The retry delay (in seconds). Default value: 2.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
mode '0600'
owner 'root'
end

service 'nginx' do
end


In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

values

Ruby Types: Hash, Array

An array of hashes, where each Hash contains the values that are to be set under a registry key. Each Hash must contain name:, type:, and data: (and must contain no other key values).

type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD.

Warning

:multi_string must be an array, even if there is only a single string.

#### Examples¶

The following examples demonstrate various approaches for using resources in recipes. If you want to see examples of how Chef uses resources in recipes, take a closer look at the cookbooks that Chef authors and maintains: https://github.com/chef-cookbooks.

Create a registry key

Use a double-quoted string:

registry_key "HKEY_LOCAL_MACHINE\\path-to-key\\Policies\\System" do
values [{
name: 'EnableLUA',
type: :dword,
data: 0
}]
action :create
end


or a single-quoted string:

registry_key 'HKEY_LOCAL_MACHINE\path-to-key\Policies\System' do
values [{
name: 'EnableLUA',
type: :dword,
data: 0
}]
action :create
end


Delete a registry key value

Use a double-quoted string:

registry_key "HKEY_LOCAL_MACHINE\\SOFTWARE\\path\\to\\key\\AU" do
values [{
name: 'NoAutoRebootWithLoggedOnUsers',
type: :dword,
data: ''
}]
action :delete
end


or a single-quoted string:

registry_key 'HKEY_LOCAL_MACHINE\SOFTWARE\path\to\key\AU' do
values [{
name: 'NoAutoRebootWithLoggedOnUsers',
type: :dword,
data: ''
}]
action :delete
end


Note

If data: is not specified, you get an error: Missing data key in RegistryKey values hash

Delete a registry key and its subkeys, recursively

### remote_file¶

Specify local Windows file path as a valid URI

When specifying a local Microsoft Windows file path as a valid file URI, an additional forward slash (/) is required. For example:

remote_file 'file:///c:/path/to/file' do
...       # other attributes
end


### windows_package¶

Use the windows_package resource to manage Microsoft Installer Package (MSI) packages for the Microsoft Windows platform.

Changed in 12.4 to include checksum and remote_file_attributes and URL locations on the source properties. Changed in Chef Client 12.6 to support a greater variety of installer_type; Changed in 12.0 for installer_type to require a symbol.

#### Syntax¶

A windows_package resource block manages a package on a node, typically by installing it. The simplest use of the windows_package resource is:

windows_package 'package_name'


which will install the named package using all of the default options and the default action (:install).

The full syntax for all of the properties that are available to the windows_package resource is:

windows_package 'name' do
checksum                   String
installer_type             Symbol
notifies                   # see description
options                    String
provider                   Chef::Provider::Package::Windows
remote_file_attributes     Hash
returns                    Integer, Array of integers
source                     String # defaults to 'name' if not specified
subscribes                 # see description
timeout                    String, Integer
version                    String, Array
action                     Symbol # defaults to :install if not specified
end


where

• windows_package tells the chef-client to manage a package
• 'name' is the name of the package
• action identifies which steps the chef-client will take to bring the node into the desired state
• checksum, installer_type, options, package_name, provider, remote_file_attributes, returns, source, and timeout are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

#### Actions¶

This resource has the following actions:

:install
Default. Install a package. If a version is specified, install the specified version of the package.
:nothing
Define this resource block to do nothing until notified by another resource to take action. When this resource is notified, this resource block is either run immediately or it is queued up to be run at the end of the Chef Client run.
:remove
Remove a package.

#### Attributes¶

This resource has the following properties:

checksum

Ruby Type: String

The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, the chef-client does not download it. Use when a URL is specified by the source property.

New in Chef Client 12.4, changed in 12.6.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

installer_type

Ruby Type: Symbol

A symbol that specifies the type of package. Possible values: :custom (such as installing a non-.msi file that embeds an .msi-based installer), :inno (Inno Setup), :installshield (InstallShield), :msi (Microsoft Installer Package (MSI)), :nsis (Nullsoft Scriptable Install System (NSIS)), :wise (Wise).

Changed in Chef Client 12.6 to support diverse installer types; Changed in 12.0 to require a symbol.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

options

Ruby Type: String

One (or more) additional options that are passed to the command.

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider. See “Providers” section below for more information.

remote_file_attributes

Ruby Type: Hash

A package at a remote location define as a Hash of properties that modifes the properties of the remote_file resource.

New in Chef Client 12.4.

retries

Ruby Type: Integer

The number of times to catch exceptions and retry the resource. Default value: 0.

retry_delay

Ruby Type: Integer

The retry delay (in seconds). Default value: 2.

returns

Ruby Types: Integer, Array of integers

A comma-delimited list of return codes that indicate the success or failure of the command that was run remotely. This code signals a successful :install action. Default value: 0.

source

Ruby Type: String

Optional. The path to a package in the local file system. The location of the package may be at a URL. Default value: the name of the resource block. See the “Syntax” section above for more information.

If the source property is not specified, the package name MUST be exactly the same as the display name found in Add/Remove programs or exactly the same as the DisplayName property in the appropriate registry key, which may be one of the following:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall
HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall


Note

If there are multiple versions of a package installed with the same display name, all of those packages will be removed unless a version is provided in the version property or unless it can be discovered in the installer file specified by the source property.

Changed in Chef Client 12.4 to support URL locations.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
mode '0600'
owner 'root'
end

service 'nginx' do
end


In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

timeout

Ruby Types: String, Integer

The amount of time (in seconds) to wait before timing out. Default value: 600 (seconds).

version

Ruby Types: String, Array

The version of a package to be installed or upgraded.

#### Providers¶

This resource has the following providers:

Chef::Provider::Package, package
When this short name is used, the chef-client will attempt to determine the correct provider during the chef-client run.
Chef::Provider::Package::Windows, windows_package
The provider for the Microsoft Windows platform.

#### Examples¶

The following examples demonstrate various approaches for using resources in recipes. If you want to see examples of how Chef uses resources in recipes, take a closer look at the cookbooks that Chef authors and maintains: https://github.com/chef-cookbooks.

Install a package

windows_package '7zip' do
action :install
source 'C:\7z920.msi'
end


Specify a URL for the source attribute

windows_package '7zip' do
source 'http://www.7-zip.org/a/7z938-x64.msi'
end


Specify path and checksum

windows_package '7zip' do
source 'http://www.7-zip.org/a/7z938-x64.msi'
end


Modify remote_file resource attributes

The windows_package resource may specify a package at a remote location using the remote_file_attributes property. This uses the remote_file resource to download the contents at the specified URL and passes in a Hash that modifes the properties of the remote_file resource.

For example:

windows_package '7zip' do
source 'http://www.7-zip.org/a/7z938-x64.msi'
remote_file_attributes ({
:path => 'C:\\7zip.msi',
})
end


windows_package 'Mercurial 3.6.1 (64-bit)' do
source 'http://mercurial.selenic.com/release/windows/Mercurial-3.6.1-x64.exe'
checksum 'febd29578cb6736163d232708b834a2ddd119aa40abc536b2c313fc5e1b5831d'
end


windows_package 'Microsoft Visual C++ 2005 Redistributable' do
installer_type :custom
options '/Q'
end


### windows_service¶

Use the windows_service resource to create, delete, and manage a service on the Microsoft Windows platform.

#### Syntax¶

A windows_service resource block manages the state of a service on a machine that is running Microsoft Windows. For example:

windows_service 'BITS' do
action :configure_startup
startup_type :manual
end


The full syntax for all of the properties that are available to the windows_service resource is:

windows_service 'name' do
binary_path_name           String
display_name               String
desired_access             Integer
delayed_start              [Integer] # This only applies if startup_type is :automatic
dependencies               [String, Array]
description                String
error_control              Integer
init_command               String
notifies                   # see description
pattern                    String
provider                   Chef::Provider::Service::Windows
restart_command            String
run_as_user                String
service_name               String # defaults to 'name' if not specified
service_type               Integer # defaults to 'SERVICE_WIN32_OWN_PROCESS'
start_command              String
startup_type               Symbol
status_command             String
stop_command               String
subscribes                 # see description
supports                   Hash
timeout                    Integer
action                     Symbol # defaults to :nothing if not specified
end


where

• windows_service is the resource
• name is the name of the resource block
• action identifies the steps the chef-client will take to bring the node into the desired state
• binary_path_name, display_name, desired_access, delayed_start, dependencies, description, error_control, init_command, load_order_group, pattern, provider, reload_command, restart_command, run_as_password, run_as_user, service_name, service_type, start_command, startup_type, status_command, stop_command, supports, and timeout are properties of this resource, with the Ruby type shown. See “Properties” section below for more information about all of the properties that may be used with this resource.

#### Actions¶

This resource has the following actions:

:configure_startup
Configure a service based on the value of the startup_type property.
:create

Create the service based on the value of the binary_path_name, service_name and/or display_name property.

New in Chef Client 13.7.16.

:delete

Delete the service based on the value of the service_name property.

New in Chef Client 13.7.16.

:disable
Disable a service. This action is equivalent to a Disabled startup type on the Microsoft Windows platform.
:enable
Enable a service at boot. This action is equivalent to an Automatic startup type on the Microsoft Windows platform.
:nothing
Default. Do nothing with a service.
:reload
Reload the configuration for this service.
:restart
Restart a service.
:start
Start a service, and keep it running until stopped or disabled.
:stop
Stop a service.

#### Attributes¶

This resource has the following properties:

binary_path_name

Ruby Type: String

Required The fully qualified path to the service binary file. The path can also include arguments for an auto-start service.

New in Chef Client 13.7.16.

display_name

Ruby Type: String

The display name to be used by user interface programs to identify the service. This string has a maximum length of 256 characters.

New in Chef Client 13.7.16.

delayed_start

Ruby Type: Integer

Set the startup type to delayed start. This only applies if startup_type is :automatic.

New in Chef Client 13.7.16.

dependencies

Ruby Types: String, Array

A pointer to a double null-terminated array of null-separated names of services or load ordering groups that the system must start before this service. Specify nil or an empty string if the service has no dependencies. Dependency on a group means that this service can run if at least one member of the group is running after an attempt to start all members of the group.

New in Chef Client 13.7.16.

description

Ruby Types: String

Description of the service.

New in Chef Client 13.7.16.

ignore_failure

Ruby Types: TrueClass, FalseClass

Continue running a recipe if a resource fails for any reason. Default value: false.

init_command

Ruby Type: String

The path to the init script that is associated with the service. This is typically /etc/init.d/SERVICE_NAME. The init_command property can be used to prevent the need to specify overrides for the start_command, stop_command, and restart_command attributes. Default value: nil.

load_order_group

Ruby Types: String

The name of the service’s load ordering group(s). Specify nil or an empty string if the service does not belong to a group.

New in Chef Client 13.7.16.

notifies

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may notify another resource to take action when its state changes. Specify a 'resource[name]', the :action that resource should take, and then the :timer for that action. A resource may notify more than one resource; use a notifies statement for each resource to be notified.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for notifies is:

notifies :action, 'resource[name]', :timer

pattern

Ruby Type: String

The pattern to look for in the process table. Default value: service_name.

provider

Ruby Type: Chef Class

Optional. Explicitly specifies a provider.

reload_command

Ruby Type: String

The command used to tell a service to reload its configuration.

restart_command

Ruby Type: String

The command used to restart a service.

retries

Ruby Type: Integer

The number of times to catch exceptions and retry the resource. Default value: 0.

retry_delay

Ruby Type: Integer

The retry delay (in seconds). Default value: 2.

run_as_password

Ruby Type: String

The password for the user specified by run_as_user.

New in Chef Client 12.1.

run_as_user

Ruby Type: String

The user under which a Microsoft Windows service runs.

New in Chef Client 12.1.

service_name

Ruby Type: String

The name of the service. Default value: the name of the resource block. See the “Syntax” section above for more information.

New in Chef Client 13.7.16.

start_command

Ruby Type: String

The command used to start a service.

startup_type

Ruby Type: Symbol

Use to specify the startup type for a Microsoft Windows service. Possible values: :automatic, :disabled, or :manual. Default value: :automatic.

status_command

Ruby Type: String

The command used to check the run status for a service.

stop_command

Ruby Type: String

The command used to stop a service.

subscribes

Ruby Type: Symbol, ‘Chef::Resource[String]’

A resource may listen to another resource, and then take action if the state of the resource being listened to changes. Specify a 'resource[name]', the :action to be taken, and then the :timer for that action.

Note that subscribes does not apply the specified action to the resource that it listens to - for example:

file '/etc/nginx/ssl/example.crt' do
mode '0600'
owner 'root'
end

service 'nginx' do
end


In this case the subscribes property reloads the nginx service whenever its certificate file, located under /etc/nginx/ssl/example.crt, is updated. subscribes does not make any changes to the certificate file itself, it merely listens for a change to the file, and executes the :reload action for its resource (in this example nginx) when a change is detected.

A timer specifies the point during the Chef Client run at which a notification is run. The following timers are available:

:before
Specifies that the action on a notified resource should be run before processing the resource block in which the notification is located.
:delayed
Default. Specifies that a notification should be queued up, and then executed at the very end of the Chef Client run.
:immediate, :immediately
Specifies that a notification should be run immediately, per resource notified.

The syntax for subscribes is:

subscribes :action, 'resource[name]', :timer

supports

Ruby Type: Hash

A list of properties that controls how the chef-client is to attempt to manage a service: :restart, :reload, :status. For :restart, the init script or other service provider can use a restart command; if :restart is not specified, the chef-client attempts to stop and then start a service. For :reload, the init script or other service provider can use a reload command. For :status, the init script or other service provider can use a status command to determine if the service is running; if :status is not specified, the chef-client attempts to match the service_name against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: { restart: false, reload: false, status: false } for all platforms (except for the Red Hat platform family, which defaults to { restart: false, reload: false, status: true }.)

timeout

Ruby Type: Integer

The amount of time (in seconds) to wait before timing out. Default value: 60.

#### Examples¶

Start a service manually

windows_service 'BITS' do
action :configure_startup
startup_type :manual
end


## Cookbook Resources¶

Some of the most popular Chef-maintained cookbooks that contain lightweight resources useful when configuring machines running Microsoft Windows are listed below:

Cookbook Description
iis The iis cookbook is used to install and configure Internet Information Services (IIS).
webpi The webpi cookbook is used to run the Microsoft Web Platform Installer (WebPI).
windows The windows cookbook is used to configure auto run, batch, reboot, enable built-in operating system packages, configure Microsoft Windows packages, reboot machines, and more.

## Recipe DSL Methods¶

Six methods are present in the Recipe DSL to help verify the registry during a chef-client run on the Microsoft Windows platform—registry_data_exists?, registry_get_subkeys, registry_get_values, registry_has_subkeys?, registry_key_exists?, and registry_value_exists?—these helpers ensure the powershell_script resource is idempotent.

Note

The recommended order in which registry key-specific methods should be used within a recipe is: key_exists?, value_exists?, data_exists?, get_values, has_subkeys?, and then get_subkeys.

### registry_data_exists?¶

Use the registry_data_exists? method to find out if a Microsoft Windows registry key contains the specified data of the specified type under the value.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_data_exists? method is as follows:

registry_data_exists?(
KEY_PATH,
{ name: 'NAME', type: TYPE, data: DATA },
ARCHITECTURE
)


where:

• KEY_PATH is the path to the registry key value. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
• { name: 'NAME', type: TYPE, data: DATA } is a hash that contains the expected name, type, and data of the registry key value
• type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD.
• ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This method will return true or false.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

### registry_get_subkeys¶

Use the registry_get_subkeys method to get a list of registry key values that are present for a Microsoft Windows registry key.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_get_subkeys method is as follows:

subkey_array = registry_get_subkeys(KEY_PATH, ARCHITECTURE)


where:

• KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
• ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This returns an array of registry key values.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

### registry_get_values¶

Use the registry_get_values method to get the registry key values (name, type, and data) for a Microsoft Windows registry key.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_get_values method is as follows:

subkey_array = registry_get_values(KEY_PATH, ARCHITECTURE)


where:

• KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
• ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This returns an array of registry key values.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

### registry_has_subkeys?¶

Use the registry_has_subkeys? method to find out if a Microsoft Windows registry key has one (or more) values.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_has_subkeys? method is as follows:

registry_has_subkeys?(KEY_PATH, ARCHITECTURE)


where:

• KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
• ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This method will return true or false.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

### registry_key_exists?¶

Use the registry_key_exists? method to find out if a Microsoft Windows registry key exists at the specified path.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_key_exists? method is as follows:

registry_key_exists?(KEY_PATH, ARCHITECTURE)


where:

• KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
• ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This method will return true or false. (Any registry key values that are associated with this registry key are ignored.)

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

### registry_value_exists?¶

Use the registry_value_exists? method to find out if a registry key value exists. Use registry_data_exists? to test for the type and data of a registry key value.

Note

This method can be used in recipes and from within the not_if and only_if blocks in resources. This method is not designed to create or modify a registry key. If a registry key needs to be modified, use the registry_key resource.

The syntax for the registry_value_exists? method is as follows:

registry_value_exists?(
KEY_PATH,
{ name: 'NAME' },
ARCHITECTURE
)


where:

• KEY_PATH is the path to the registry key. The path must include the registry hive, which can be specified either as its full name or as the 3- or 4-letter abbreviation. For example, both HKLM\SECURITY and HKEY_LOCAL_MACHINE\SECURITY are both valid and equivalent. The following hives are valid: HKEY_LOCAL_MACHINE, HKLM, HKEY_CURRENT_CONFIG, HKCC, HKEY_CLASSES_ROOT, HKCR, HKEY_USERS, HKU, HKEY_CURRENT_USER, and HKCU.
• { name: 'NAME' } is a hash that contains the name of the registry key value; if either type: or :value are specified in the hash, they are ignored
• type: represents the values available for registry keys in Microsoft Windows. Use :binary for REG_BINARY, :string for REG_SZ, :multi_string for REG_MULTI_SZ, :expand_string for REG_EXPAND_SZ, :dword for REG_DWORD, :dword_big_endian for REG_DWORD_BIG_ENDIAN, or :qword for REG_QWORD.
• ARCHITECTURE is one of the following values: :x86_64, :i386, or :machine. In order to read or write 32-bit registry keys on 64-bit machines running Microsoft Windows, the architecture property must be set to :i386. The :x86_64 value can be used to force writing to a 64-bit registry location, but this value is less useful than the default (:machine) because the chef-client returns an exception if :x86_64 is used and the machine turns out to be a 32-bit machine (whereas with :machine, the chef-client is able to access the registry key on the 32-bit machine).

This method will return true or false.

Note

The ARCHITECTURE attribute should only specify :x86_64 or :i386 when it is necessary to write 32-bit (:i386) or 64-bit (:x86_64) values on a 64-bit machine. ARCHITECTURE will default to :machine unless a specific value is given.

### Helpers¶

A recipe can define specific behaviors for specific Microsoft Windows platform versions by using a series of helper methods. To enable these helper methods, add the following to a recipe:

require 'chef/win32/version'


Then declare a variable using the Chef::ReservedNames::Win32::Version class:

variable_name = Chef::ReservedNames::Win32::Version.new


And then use this variable to define specific behaviors for specific Microsoft Windows platform versions. For example:

if variable_name.helper_name?
# Ruby code goes here, such as
resource_name do
# resource block
end

elsif variable_name.helper_name?
# Ruby code goes here
resource_name do
# resource block for something else
end

else variable_name.helper_name?
# Ruby code goes here, such as
log 'log entry' do
level :level
end

end


The following Microsoft Windows platform-specific helpers can be used in recipes:

Helper Description
cluster? Use to test for a Cluster SKU (Windows Server 2003 and later).
core? Use to test for a Core SKU (Windows Server 2003 and later).
datacenter? Use to test for a Datacenter SKU.
marketing_name Use to display the marketing name for a Microsoft Windows platform.
windows_7? Use to test for Windows 7.
windows_8? Use to test for Windows 8.
windows_8_1? Use to test for Windows 8.1.
windows_2000? Use to test for Windows 2000.
windows_home_server? Use to test for Windows Home Server.
windows_server_2003? Use to test for Windows Server 2003.
windows_server_2003_r2? Use to test for Windows Server 2003 R2.
windows_server_2008? Use to test for Windows Server 2008.
windows_server_2008_r2? Use to test for Windows Server 2008 R2.
windows_server_2012? Use to test for Windows Server 2012.
windows_server_2012_r2? Use to test for Windows Server 2012 R2.
windows_vista? Use to test for Windows Vista.
windows_xp? Use to test for Windows XP.

The following example installs Windows PowerShell 2.0 on systems that do not already have it installed. Microsoft Windows platform helper methods are used to define specific behaviors for specific platform versions:

case node['platform']
when 'windows'

require 'chef/win32/version'
windows_version = Chef::ReservedNames::Win32::Version.new

if (windows_version.windows_server_2008_r2? || windows_version.windows_7?) && windows_version.core?

windows_feature 'NetFx2-ServerCore' do
action :install
end
windows_feature 'NetFx2-ServerCore-WOW64' do
action :install
only_if { node['kernel']['machine'] == 'x86_64' }
end

elsif windows_version.windows_server_2008? || windows_version.windows_server_2003_r2? ||
windows_version.windows_server_2003? || windows_version.windows_xp?

if windows_version.windows_server_2008?
windows_feature 'NET-Framework-Core' do
action :install
end

else
windows_package 'Microsoft .NET Framework 2.0 Service Pack 2' do
source node['ms_dotnet2']['url']
checksum node['ms_dotnet2']['checksum']
installer_type :custom
options '/quiet /norestart'
action :install
end
end
else
log '.NET Framework 2.0 is already enabled on this version of Windows' do
level :warn
end
end
else
log '.NET Framework 2.0 cannot be installed on platforms other than Windows' do
level :warn
end
end


The previous example is from the ms_dotnet2 cookbook, created by community member juliandunn.

## 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:

• Registering and authenticating the node with the Chef server
• Building the node object
• Synchronizing cookbooks
• Compiling the resource collection by loading each of the required cookbooks, including recipes, attributes, and all other dependencies
• Taking the appropriate and required actions to configure the node
• Looking for exceptions and notifications, handling each as required

This command has the following syntax:

$chef-client OPTION VALUE OPTION VALUE ...  This command has the following options specific to Microsoft Windows: -A, --fatal-windows-admin-check Cause a chef-client run to fail when the chef-client does not have administrator privileges in Microsoft Windows. -d, --daemonize Run the executable as a daemon. This option is only available on machines that run in UNIX or Linux environments. For machines that are running Microsoft Windows that require similar functionality, use the chef-client::service recipe in the chef-client cookbook: https://supermarket.chef.io/cookbooks/chef-client. This will install a chef-client service under Microsoft Windows using the Windows Service Wrapper. Note chef-solo also uses the --daemonize setting for Microsoft Windows. ### Run w/Elevated Privileges¶ The chef-client may need to be run with elevated privileges in order to get a recipe to converge correctly. On UNIX and UNIX-like operating systems this can be done by running the command as root. On Microsoft Windows this can be done by running the command prompt as an administrator. On Microsoft Windows, running without elevated privileges (when they are necessary) is an issue that fails silently. It will appear that the chef-client completed its run successfully, but the changes will not have been made. When this occurs, do one of the following to run the chef-client as the administrator: • Log in to the administrator account. (This is not the same as an account in the administrator’s security group.) • Run the chef-client process from the administrator account while being logged into another account. Run the following command: $ runas /user:Administrator "cmd /C chef-client"


When running Microsoft Windows, the knife.rb file is located at %HOMEDRIVE%:%HOMEPATH%\.chef (e.g. c:\Users\<username>\.chef). If this path needs to be scripted, use %USERPROFILE%\.chef`.