Chef for 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)
- Over a dozen resources dedicated to the Microsoft Windows platform are built into the chef-client.
- 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.
- 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 knife windows to bootstrap the chef-client; this process requires the target node be available via the WinRM port (typically port 5985)
- 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, 2016 | 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.)
The Microsoft Installer Package (MSI) for Microsoft Windows is available at https://downloads.chef.io/chef.
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:
- Add quotes around the variable assignment strings.
- Convert
C:/
to/c/
. - 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 supermarket 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:
$ msiexec /qn /i "%LOCAL_DESTINATION_MSI_PATH%"
where /qn
is used to set the user interface level to “No UI”, /i
is used to define the location in which the chef-client is installed, and "%LOCAL_DESTINATION_MSI_PATH%"
is a variable defined in the default windows-chef-client-msi.erb bootstrap template. See http://msdn.microsoft.com/en-us/library/aa367988%28v=vs.85%29.aspx for more information about the options available to Msiexec.exe.
ADDLOCAL Options¶
The ADDLOCAL
parameter adds two setup options that are specific to the chef-client. These options can be passed along with an Msiexec.exe command:
Option | Description |
---|---|
ChefClientFeature |
Use to install the chef-client. |
ChefSchTaskFeature |
Use to configure the chef-client as a scheduled task in Microsoft Windows. |
ChefPSModuleFeature |
Used to install the chef PowerShell module. This will enable chef command line utilities within PowerShell. |
First install the chef-client, and then enable it to run as a scheduled task. For example:
$ msiexec /qn /i C:\inst\chef-client-14.5.27-1-x64.msi ADDLOCAL="ChefClientFeature,ChefSchTaskFeature,ChefPSModuleFeature"
Use MSI Installer¶
A Microsoft Installer Package (MSI) is available for installing the chef-client on a Microsoft Windows machine from Chef Downloads.
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
.
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}"
ADDLOCAL=#{node['php']['packages'].join(',')}
].join(' ')
end
...
ENV['PATH'] += ";#{install_dir}"
windows_path install_dir
...
Proxy Settings¶
To determine the current proxy server on the Microsoft Windows platform:
- Open Internet Properties.
- Open Connections.
- Open LAN settings.
- 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:
- Open System Properties.
- Open Environment Variables.
- Open System variables.
- Set
http_proxy
andhttps_proxy
to the location of your proxy server. This value MUST be lowercase.
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
, orservice
- 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 toGENERIC_READ
;:write
corresponds toGENERIC_WRITE
;:read_execute
corresponds toGENERIC_READ
andGENERIC_EXECUTE
;:modify
corresponds toGENERIC_WRITE
,GENERIC_READ
,GENERIC_EXECUTE
, andDELETE
;:full_control
corresponds toGENERIC_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
, oruser_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 Microsoft Windows: A quoted 3-5 character string that defines the octal mode that is translated into rights for Microsoft Windows security. For example: |
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 ( |
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
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 resourcename
is the name of the resource blockcommand
is the command to be run andcwd
is the location from which the command is runaction
identifies the steps the chef-client will take to bring the node into the desired statearchitecture
,code
,command
,creates
,cwd
,flags
,group
,guard_interpreter
,interpreter
,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.
Properties¶
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 Type: 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 Type: 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 thenot_if
andonly_if
properties. Set this value to:default
to use the 32-bit version of the cmd.exe shell.ignore_failure
Ruby Type: true, false | Default Value:
false
Continue running a recipe if a resource fails for any reason.
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 anotifies
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 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 | Default Value:
0
The number of times to catch exceptions and retry the resource.
retry_delay
Ruby Type: Integer | Default Value:
2
The retry delay (in seconds).
returns
Ruby Type: Integer, Array | Default Value:
0
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.
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 thenginx
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 examplenginx
) 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 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 Type: Integer, Float | Default Value:
3600
The amount of time (in seconds) a command is to wait before timing out.
user
Ruby Type: String
The user name of the user identity with which to launch the new process. 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 Type: String
Windows only: The password of the user specified by the user property. 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 Type: String
Windows only: The domain of the user user specified by the user property. 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 https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/cmd 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 toDisabled
.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 toPush
, whereas the dsc_resource resource requires it to be set toDisabled
.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 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/orInvoke-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 given to 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-clientmodule_name
,module_version
,property
, andresource
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¶
The dsc_resource resource has the following properties:
ignore_failure
Ruby Type: true, false | Default Value:
false
Continue running a recipe if a resource fails for any reason.
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
.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 anotifies
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 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
False
bool($false)
Fixnum
Integer
Float
Double
Hash
Hashtable
True
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 unpack archive (.zip) files. :environment
Use to manage system environment variables. :file
Use to manage files and directories. :group
Use to manage local groups. :log
Use to log configuration messages. :package
Use to install and manage packages. :registry
Use to manage registry keys and registry key values. :script
Use to run PowerShell script blocks. :service
Use to manage services. :user
Use to manage local user accounts. :windowsfeature
Use to add or remove Windows features and roles. :windowsoptionalfeature
Use to configure Microsoft Windows optional features. :windowsprocess
Use 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
, andxADUser
. Assuming that these resources are available to the chef-client, the corresponding values for theresource
attribute would be::xADDomain
,:xADDomainController
, andxADUser
.retries
Ruby Type: Integer | Default Value:
0
The number of times to catch exceptions and retry the resource.
retry_delay
Ruby Type: Integer | Default Value:
2
The retry delay (in seconds).
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 thenginx
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 examplenginx
) 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 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.
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 given to the resource block.action
identifies which 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
, andtimeout
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¶
The dsc_script 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¶
The dsc_script 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 theconfiguration_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 thecode
property. For example:flags ({ :EditorChoice => 'emacs', :EditorFlags => '--maximized' })
.ignore_failure
Ruby Type: true, false | Default Value:
false
Continue running a recipe if a resource fails for any reason.
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'
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 anotifies
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 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 | Default Value:
0
The number of times to catch exceptions and retry the resource.
retry_delay
Ruby Type: Integer | Default Value:
2
The retry delay (in seconds).
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 thenginx
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 examplenginx
) 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 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 Type: 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
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 windows_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.
This resource was previously called the env resource; its name was updated in Chef Client 14.0 to reflect the fact that only Windows is supported. Existing cookbooks using env
will continue to function, but should be updated to use the new name.
Syntax¶
A windows_env resource block manages environment keys in Microsoft Windows:
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:
windows_env 'name' do
delim String
key_name String # defaults to 'name' if not specified
notifies # see description
subscribes # see description
value String
action Symbol # defaults to :create if not specified
end
where
windows_env
is the resourcename
is the name of the resource blockaction
identifies the steps the chef-client will take to bring the node into the desired statedelim
,key_name
, andvalue
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 Type: true, false | Default Value:
false
Continue running a recipe if a resource fails for any reason.
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 anotifies
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 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 | Default Value:
0
The number of times to catch exceptions and retry the resource.
retry_delay
Ruby Type: Integer | Default Value:
2
The retry delay (in seconds).
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 thenginx
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 examplenginx
) 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 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
windows_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 true, false
creates String
cwd String
environment Hash
flags String
group String, Integer
guard_interpreter Symbol
interpreter String
notifies # see description
returns Integer, Array
sensitive true, false
subscribes # see description
timeout Integer, Float
user String
password String
domain String
action Symbol # defaults to :run if not specified
elevated true, false
end
where
powershell_script
is the resourcename
is the name of the resource blockcommand
is the command to be run andcwd
is the location from which the command is runaction
identifies the steps the chef-client will take to bring the node into the desired statearchitecture
,code
,command
,convert_boolean_return
,creates
,cwd
,environment
,flags
,group
,guard_interpreter
,interpreter
,returns
,sensitive
,timeout
,user
,password
,domain
andelevated
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 Type: 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 Type: true, false | Default Value:
false
Return
0
if the last line of a command is evaluated to be true or to return1
if the last line is evaluated to be false.When the
guard_interpreter
common attribute is set to:powershell_script
, a string command will be evaluated as if this value were set totrue
. 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 (Windows PowerShell 3.0+):
-NoLogo, -NonInteractive, -NoProfile, -ExecutionPolicy Bypass, -InputFormat None
.group
Ruby Type: 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 thenot_if
andonly_if
properties. Set this value to:default
to use the 32-bit version of the cmd.exe shell.ignore_failure
Ruby Type: true, false | Default Value:
false
Continue running a recipe if a resource fails for any reason.
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 anotifies
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 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 | Default Value:
0
The number of times to catch exceptions and retry the resource.
retry_delay
Ruby Type: Integer | Default Value:
2
The retry delay (in seconds).
returns
Ruby Type: Integer, Array | Default Value:
0
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.
sensitive
Ruby Type: true, false | Default Value:
false
Ensure that sensitive resource data is not logged by the chef-client.
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 thenginx
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 examplenginx
) 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 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 Type: 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 Type: String | Default Value:
nil
The user name of the user identity with which to launch the new process. The user name may optionally be specified with a domain, i.e. domain\user 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 Type: 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 Type: String
Windows only: The domain of the 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: true, false
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
andpassword
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 # default value: machine
key String # default value: 'name' unless specified
recursive true, false # default value: false
values
action Symbol # defaults to :create if not specified
end
where
registry_key
is the resourcename
is the name of the resource blockvalues
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 thename:
,type:
, anddata:
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 statearchitecture
,key
,recursive
andvalues
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, bothHKLM\SECURITY
andHKEY_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
, andHKCU
.{ name: 'NAME', type: TYPE, data: DATA }
is a hash that contains the expected name, type, and data of the registry key valuetype:
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, thearchitecture
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, bothHKLM\SECURITY
andHKEY_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
, andHKCU
.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, thearchitecture
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, bothHKLM\SECURITY
andHKEY_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
, andHKCU
.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, thearchitecture
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, bothHKLM\SECURITY
andHKEY_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
, andHKCU
.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, thearchitecture
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, bothHKLM\SECURITY
andHKEY_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
, andHKCU
.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, thearchitecture
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, bothHKLM\SECURITY
andHKEY_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
, andHKCU
.{ name: 'NAME' }
is a hash that contains the name of the registry key value; if eithertype:
or:value
are specified in the hash, they are ignoredtype:
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, thearchitecture
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 | Default Value:
:machine
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).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 Type: true, false | Default Value:
false
Continue running a recipe if a resource fails for any reason.
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, bothHKLM\SECURITY
andHKEY_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
, andHKCU
.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 anotifies
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 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
recursive
Ruby Type: true, false
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 totrue
.Note
Be careful when using the
:delete_key
action with therecursive
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 | Default Value:
0
The number of times to catch exceptions and retry the resource.
retry_delay
Ruby Type: Integer | Default Value:
2
The retry delay (in seconds).
sensitive
Ruby Type: true, false | Default Value:
false
Determines whether or not sensitive resource data (such as key information) is logged by Chef Client.
New in Chef Client 14.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 thenginx
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 examplenginx
) 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 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 Type: 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:
, anddata:
(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.
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
options String
package_name String, Array
remote_file_attributes Hash
response_file String
response_file_variables Hash
returns String, Integer, Array # default value: [0]
source String
timeout String, Integer # default value: 600
version String, Array
action Symbol # defaults to :install if not specified
end
where:
windows_package
is the resource.name
is the name given to the resource block.action
identifies which steps the chef-client will take to bring the node into the desired state.checksum
,installer_type
,options
,package_name
,remote_file_attributes
,response_file
,response_file_variables
,returns
,source
,timeout
, andversion
are the properties available to 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.ignore_failure
Ruby Type: true, false | Default Value:
false
Continue running a recipe if a resource fails for any reason.
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).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 anotifies
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 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.
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.
retries
Ruby Type: Integer | Default Value:
0
The number of times to catch exceptions and retry the resource.
retry_delay
Ruby Type: Integer | Default Value:
2
The retry delay (in seconds).
returns
Ruby Type: Integer, Array of integers | Default Value:
0
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.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 theDisplayName
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 thesource
property.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 thenginx
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 examplenginx
) 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 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 Type: String, Integer | Default Value:
600
(seconds)The amount of time (in seconds) to wait before timing out.
version
Ruby Type: 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'
checksum '7c8e873991c82ad9cfc123415254ea6101e9a645e12977dcd518979e50fdedf3'
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',
:checksum => '7c8e873991c82ad9cfc123415254ea6101e9a645e12977dcd518979e50fdedf3'
})
end
Download a nsis (Nullsoft) package resource
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
Download a custom package
windows_package 'Microsoft Visual C++ 2005 Redistributable' do
source 'https://download.microsoft.com/download/6/B/B/6BB661D6-A8AE-4819-B79F-236472F6070C/vcredist_x86.exe'
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
desired_access Integer
delayed_start [Integer] # This only applies if startup_type is :automatic
dependencies [String, Array]
description String
desired_access Integer # defaults to 983551
display_name String
error_control Integer
init_command String
load_order_group String
notifies # see description
pattern String
reload_command String # not used on the Windows platform
restart_command String
run_as_password 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 resourcename
is the name of the resource blockaction
identifies the steps the chef-client will take to bring the node into the desired statebinary_path_name
,display_name
,desired_access
,delayed_start
,dependencies
,description
,error_control
,init_command
,load_order_group
,pattern
,reload_command
,restart_command
,run_as_password
,run_as_user
,service_name
,service_type
,start_command
,startup_type
,status_command
,stop_command
,supports
, andtimeout
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¶
The windows_service 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/ordisplay_name
property.New in Chef Client 14.0.
:delete
Delete the service based on the value of the
service_name
property.New in Chef Client 14.0.
: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. This action is not supported on the Windows platform and will raise an error if used.
:restart
- Restart a service.
:start
- Start a service, and keep it running until stopped or disabled.
:stop
- Stop a service.
Attributes¶
The windows_service 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 14.0.
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 14.0.
delayed_start
Ruby Type: Integer
Set the startup type to delayed start. This only applies if
startup_type
is:automatic
.New in Chef Client 14.0.
dependencies
Ruby Type: 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 14.0.
description
Ruby Type: String
Description of the service.
New in Chef Client 14.0.
ignore_failure
Ruby Type: true, false | Default Value:
false
Continue running a recipe if a resource fails for any reason.
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
. Theinit_command
property can be used to prevent the need to specify overrides for thestart_command
,stop_command
, andrestart_command
attributes.load_order_group
Ruby Type: 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 14.0.
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 anotifies
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 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 | Default Value:
service_name
The pattern to look for in the process table.
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 | Default Value:
0
The number of times to catch exceptions and retry the resource.
retry_delay
Ruby Type: Integer | Default Value:
2
The retry delay (in seconds).
run_as_password
Ruby Type: String
The password for the user specified by
run_as_user
.run_as_user
Ruby Type: String
The user under which a Microsoft Windows service runs.
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.start_command
Ruby Type: String
The command used to start a service.
startup_type
Ruby Type: Symbol | Default Value:
:automatic
Use to specify the startup type for a Microsoft Windows service. Possible values:
:automatic
,:disabled
, or:manual
.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 subscribes :reload, 'file[/etc/nginx/ssl/example.crt]', :immediately end
In this case the
subscribes
property reloads thenginx
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 examplenginx
) 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 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 theservice_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 | Default Value:
60
The amount of time (in seconds) to wait before timing out.
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 custom 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, bothHKLM\SECURITY
andHKEY_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
, andHKCU
.{ name: 'NAME', type: TYPE, data: DATA }
is a hash that contains the expected name, type, and data of the registry key valuetype:
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, thearchitecture
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, bothHKLM\SECURITY
andHKEY_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
, andHKCU
.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, thearchitecture
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, bothHKLM\SECURITY
andHKEY_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
, andHKCU
.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, thearchitecture
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, bothHKLM\SECURITY
andHKEY_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
, andHKCU
.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, thearchitecture
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, bothHKLM\SECURITY
andHKEY_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
, andHKCU
.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, thearchitecture
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, bothHKLM\SECURITY
andHKEY_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
, andHKCU
.{ name: 'NAME' }
is a hash that contains the name of the registry key value; if eithertype:
or:value
are specified in the hash, they are ignoredtype:
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, thearchitecture
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 thechef-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"
This will prompt for the administrator account password.
Open a command prompt by right-clicking on the command prompt application, and then selecting Run as administrator. After the command window opens, the chef-client can be run as the administrator
config.rb¶
When running Microsoft Windows, the config.rb file is located at %HOMEDRIVE%:%HOMEPATH%\.chef
(e.g. c:\Users\<username>\.chef
). If this path needs to be scripted, use %USERPROFILE%\.chef
.