Foodcritic - A lint tool for your Chef cookbooks
Time 2021-10-31 23:06:05Web Name: Foodcritic - A lint tool for your Chef cookbooks
WebSite: http://www.foodcritic.io
ID:217921
Keywords:
tool,lint,Foodcritic,for,cookbooks,Chef,your,Description:
keywords: description: Foodcritic Choosing rules to run Tags Extra rules Code Dash Docset Issues Changelog License About FoodcriticFoodcritic is a helpful lint tool you can use to check your Chef cookbooks for common problems.
It comes with 112 built-in rules that identify problems ranging from simple style inconsistencies to difficult to diagnose issues that will hurt in production.
Various nice people in the Chef community have also written extra rules for foodcritic that you can install and run. Or write your own!
It's easy to get started with Foodcritic in Chef-DK already
$ foodcritic my_cookbook_dir
FC001 Use strings in preference to symbols to access node attributes FC002 Avoid string interpolation where not required FC003
style
attributes
Use strings rather than symbols when referencing node attributes. Thiswarning will be shown if you reference a node attribute using symbols.
Symbols in node attributes.This example would match the FC001 rule because node[:cookbook][:package]
accesses node attributes with symbols
This modified example would not match the FC001 rule:
# Don't do thispackage node[:cookbook][:package] do action :installend
package node['cookbook']['package'] do action :installend
style
strings
When you declare a resource in your recipes you frequently want toreference dynamic values such as node attributes. This warning will beshown if you are unnecessarily wrapping an attribute reference in astring.
Unnecessary string interpolationThis example would match the FC002 rule because the version
attribute has been unnecessarily quoted.
This modified example would not match the FC002 rule:
# Don't do thispackage 'mysql-server' do version "#{node['mysql']['version']}" action :installend
# Do this insteadpackage 'mysql-server' do version node['mysql']['version'] action :installend
This rule has been deprecated. Chef 12.11 switched Chef Solo to use ChefLocal mode which eliminates the need to avoid server specific Cheffunctionality in recipes. With that change this rule became obsolete.
portability
services
This warning is shown if you are starting or stopping a service using theChef execute
resource rather than the more idiomatic service
resource.You can read more about the service resource here:
This example would match the FC004 rule because it uses execute
forservice control. There is no reason to use execute because the serviceresource exposes the start_command
attribute to give you fullcontrol over the command issued.
This modified example would not match the FC004 rule:
# Don't do thisexecute 'start-tomcat' do command '/etc/init.d/tomcat6 start' action :runend
# Do this insteadservice 'tomcat' do action :startend
style
When writing Chef recipes you have the full power of Ruby at yourdisposal. One of the cases where this is helpful is where you need todeclare a large number of resources that only differ in a single attribute- the canonical example is installing a long list of packages.
Unnecessarily repetitiveThis example matches the FC005 rule because all the resources of typepackage
differ only in a single attribute - the name of the packageto be upgraded. This rule is very simple and looks only for resourcesthat all differ in only a single attribute. For example - if only oneof the packages specified the version then this rule would not match.
This modified example would not match the FC005 rule. It takesadvantage of the fact that Chef processes recipes in two distinctphases. In the first ‘compile’ phase it builds the resourcecollection. In the second phase it configures the node against theresource collection.
Don’t worry about changing your recipe if it already does what youwant - the amount of Ruby syntactic sugar to apply is very much amatter of personal taste. Note that this rule also isn’t clever enoughyet to detect if your resources are wrapped in a control structure andnot suitable for ‘rolling up’ into a loop.
# You could do thispackage 'erlang-base' do action :upgradeendpackage 'erlang-corba' do action :upgradeendpackage 'erlang-crypto' do action :upgradeendpackage 'rabbitmq-server' do action :upgradeend
# It's shorter to do this%w(erlang-base erlang-corba erlang-crypto rabbitmq-server).each do |pkg| package pkg do action :upgrade endend
correctness
files
When setting file or directory permissions via the mode attribute youshould either quote the octal number or ensure it is specified to fivedigits. Otherwise the permissions that are set after Ruby coerces thenumber may not match what you expect.
File mode won't be interpreted correctly Modified versionsThese modified examples would not match the FC006 rule:
# Don't do thisdirectory '/var/lib/foo' do owner 'root' group 'root' mode 644 action :createend
# This is okdirectory '/var/lib/foo' do owner 'root' group 'root' mode '644' action :createend# And so is thisdirectory '/var/lib/foo' do owner 'root' group 'root' mode 00644 action :createend
correctness
metadata
This warning is shown when you include a recipe that is not in the currentcookbook and not defined as a dependency in your cookbook metadata. Thisis potentially a big problem because things will blow up if the necessarydependency cannot be found when Chef tries to converge your node. For moreinformation refer to the Chef metadata page:
https://docs.chef.io/config_rb_metadata.htmlThe fix is to declare the cookbook of the recipe you are including as adependency in your metadata.rb
file.
You may also see this warning if foodcritic has not been able to infer thename of your cookbook correctly when the cookbook directory does not matchthe name of the cookbook specified in the include.
Example dependency on another cookbookAssuming you have a recipe that had the following line:
Adding metadata dependency for ChefThen to remove this warning you would add the apache2
cookbook as adependency to your own cookbook metadata in the metadata.rb
file atthe root of your cookbook.
include_recipe 'apache2::default'
depends 'apache2'
metadata
supermarket
This warning is shown if you used knife cookbook create
to create a newcookbook and didn’t override the maintainer and maintainer email. You needto set these to real values in metadata.rb
or run knife again with thereal values.
This modified example would not match the FC008 rule:
# Don't do thismaintainer 'YOUR_COMPANY_NAME'maintainer_email 'YOUR_EMAIL'license 'All rights reserved'description 'Installs/Configures example'long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))version '0.0.1'
# Do this insteadmaintainer 'Example Ltd'maintainer_email 'postmaster@example.com'license 'All rights reserved'description 'Installs/Configures example'long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))version '0.0.1'
correctness
This warning is likely to mean that your recipe will fail to run whenyou attempt to converge. Your recipe may be syntactically valid Ruby,but the attribute you have attempted to set on a built-in Chef resourceis not recognised. This is commonly a typo or you need to check thedocumentation to see what the attribute you are trying to set is called:
https://docs.chef.io/resource.html#resources Resource with an unrecognised attributeThis example matches the FC009 rule because punter
is not arecognised attribute for the file resource.
Checking the documentation we can see the correct attribute isowner
.
# Don't do thisfile '/tmp/something' do punter 'root' group 'root' mode '0755' action :createend
# Do this insteadfile '/tmp/something' do owner 'root' group 'root' mode '0755' action :createend
correctness
search
The search syntax used is not recognised as valid Lucene search criteria.This is commonly because you have made a typo or are not escaping specialcharacters in the query syntax.
https://docs.chef.io/chef_search.html#query-syntaxNote that this rule will not identify syntax errors in searches composedof subexpressions. It checks only for literal search strings.
Unescaped search syntaxThis example matches the FC010 rule because search metacharacters -in this case the square brackets - have not been properly escaped.
Modified versionWith the characters escaped this will no longer match the rule.
# Don't do thissearch(:node, 'run_list:recipe[foo::bar]') do |matching_node| puts matching_node.to_send
# Do this insteadsearch(:node, 'run_list:recipe\[foo\:\:bar\]') do |matching_node| puts matching_node.to_send
readme
supermarket
Supermarket will nowrender your cookbook README documentation inline - see this example forthe mysql cookbook.
Your README needs to be inMarkdown format forthis to work. This rule will match any cookbook that does not have aREADME.md
file in the root directory.
supermarket
readme
Deprecated. These haven’t existed since the very early days of Chef, andthe check for README.md files will catch what this rule used to.Writing cookbook documentation in RDoc has been deprecated in favour ofMarkdown format.This rule will match any cookbook that has a README.rdoc
file in theroot directory.
portability
files
This warning means that you have hard-coded a file download path in yourcookbook to a temporary directory. This can be a problem on boxes builtwith a small /tmp
mount point. Chef has its own configuration optionfile_cache_path
you should use instead:
This example matches the FC013 rule because it hard-codes the downloadpath to /tmp
.
To remove this warning use the configured file_cache_path
:
# Don't do thisremote_file '/tmp/large-file.tar.gz' do source 'http://www.example.org/large-file.tar.gz'end
# Do this insteadremote_file "#{Chef::Config[:file_cache_path]}/large-file.tar.gz" do source 'http://www.example.org/large-file.tar.gz'end
style
libraries
Your cookbook has a fairly long ruby_block
resource. Long ruby_block
resources are often candidates for extraction to a separate module orclass under the libraries
directory.
style
definitions
Chef definitions are an older approach to creating a higher-levelabstraction for a group of resources. Unlike Custom Resources they are notfirst class resources, cannot receive notifications, and do not support why-runmode. You should prefer Custom Resources for new development.
https://docs.chef.io/custom_resources.html correctness
lwrp
This warning means that the LWRP does not declare a default action. Youshould normally define a default action on your resource to avoidconfusing users. Most resources have an intuitive default action.
Resource without a default actionThis example matches the FC016 rule because it does not declare adefault action.
Modified versionWith a default action specified this warning will no longer bedisplayed.
# Don't do thisactions :create, :delete
# Do this insteadactions :create, :deletedefault_action :create
This rule has been deprecated. Chef 13 now uses use_inline_resources by default so LWRPs always notify updates.
correctness
lwrp
deprecated
Provider uses deprecated syntax
This example matches the FC018 rule because it uses the old syntax forindicating it has been updated.
Modified versionThis example uses the newer syntax and will not raise the warning.
# Don't do thisaction :create do # create action implementation # My state has changed so I'd better notify observers, but I'm using # a deprecated syntax new_resource.updated = trueend# Also don't do thisaction :create do # create action implementation # My state has changed so I'd better notify observers, but I'm using # a deprecated syntax @updated = trueend
# Approach 1: Using converge_byaction :create do converge_by("Creating my_resource #{new_resource.name}") do # create action implementation endend# Approach 2: Using use_inline_resourcesuse_inline_resourcesaction :create do # create action implementationend
style
attributes
Node attributes can be accessed in multiple ways in Chef. This warning isshown when a cookbook is not consistent in the approach it uses to accessattributes. It is not displayed for variations between cookbooks.
Recipe mixes symbols and strings for accessing node attributes Modified version# Don't do thisnode[:apache][:dir] = '/etc/apache2'directory node['apache']['dir'] do owner 'apache' group 'apache' action :createend
# Do this insteadnode['apache']['dir'] = '/etc/apache2'directory node['apache']['dir'] do owner 'apache' group 'apache' action :createend
This rule has been deprecated due to the frequency of false positives.See the discussion againstissue #30 for moredetail.
correctness
lwrp
A change introduced in Chef 0.10.6 means that conditions may not work asexpected for resources redeclared with the same name. If your LWRP definesa resource and that resource:
Has an associated guardwhich references a resource attribute. AND The resource has a fixed name.Then you will likely find that only the first resource will be applied. See this ticket for more background:
http://tickets.chef.io/browse/CHEF-2812 Resource condition will be evaluated only onceBecause the feed_pet
resource will have the same name across allinstances of your LWRP, the condition will only be checked for thefirst resource.
By making the resource name change for each unique instance of ourLWRP instance we avoid this behaviour.
# Don't do thisaction :feed do execute 'feed_pet' do command "echo 'Feeding: #{new_resource.name}'; touch '/tmp/#{new_resource.name}'" not_if { ::File.exists?("/tmp/#{new_resource.name}")} endend
# Do this insteadaction :feed do execute "feed_pet_#{new_resource.name}" do command "echo 'Feeding: #{new_resource.name}'; touch '/tmp/#{new_resource.name}'" not_if { ::File.exists?("/tmp/#{new_resource.name}")} endend
correctness
A change introduced in Chef 0.10.6 means that conditions may not work asexpected for resources declared within a loop. If your recipe defines aresource and that resource:
Has an associated conditionwhich references a block variable. AND The resource has a fixed name.Then you will likely find that only the first resource will be applied. See this ticket for more background:
http://tickets.chef.io/browse/CHEF-2812 Resource condition will be evaluated only onceBecause the feed_pet resource will have the same name for everyiteration of the loop, the condition will only be checked for thefirst resource.
Modified versionBy making the resource name change for each iteration of the loop we avoid this behaviour.
# Don't do this%w(rover fido).each do |pet_name| execute 'feed_pet' do command "echo 'Feeding: #{pet_name}'; touch '/tmp/#{pet_name}'" not_if { ::File.exists?("/tmp/#{pet_name}")} endend
# Do this instead%w(rover fido).each do |pet_name| execute "feed_pet_#{pet_name}" do command "echo 'Feeding: #{pet_name}'; touch '/tmp/#{pet_name}'" not_if { ::File.exists?("/tmp/#{pet_name}")} endend
This rule has been deprecated. While it’s often considered a more chef likecoding style to use not_if and only_if within the resources, there are severaldownsides to this including the inclusion of the resources within resource collectionand reporting.
portability
This warning is shown when:
you have a conditional statement in your cookbook based on the platformof the node and at least two platforms are included as equivalent in yourconditional and the conditional does not include a platform known to belong to thesame familyIf at all possible you should consider using platform_family
instead ofplatform to ensure you support similar distros. Otherwise for the greatestportability consider adding the missing platforms to your conditional.
This example matches the FC024 rule because it includes a case
statement that matches more than one flavour of a platform familybut omits other popular flavours from the same family.
This warning is no longer raised when the other common equivalentRHEL-based distributions have been added to the when
.
# The RHEL platforms branch below omits popular distributionscase node[:platform] when 'debian', 'ubuntu' package 'foo' do action :install end when 'centos', 'redhat' package 'bar' do action :install endend
case node[:platform] when 'debian', 'ubuntu' package 'foo' do action :install end when 'centos', 'redhat', 'scientific', 'oracle' package 'bar' do action :install end end
correctness
deprecated
This warning is shown if:* you have a cookbook that installs a Rubygem for use from Chef* the cookbook uses the compile-time gem install trick which is deprecated from Chef 0.10.10 and is replaced by the first class chef_gem
resource.
This example matches the FC025 rule because it uses the olderapproach for installing a gem so that it is available in the currentrun.
Modified versionUse chef_gem
to install the gem to avoid this warning.
r = gem_package 'mysql' do action :nothingendr.run_action(:install)Gem.clear_paths
chef_gem 'mysql' do compile_time trueend
correctness
This warning is shown if you have a conditional attribute declared on aresource as a block that contains only a single string.
Conditional attribute returns a stringThis example matches the FC026 rule because it returns a string fromthe block. This will always evalute to true, and often indicates thatyou are trying to run a command rather than execute a Ruby block asyour condition.
Modified versionIf the intention is to run the string as an operating system commandthen remove the block surrounding the command.
# Don't do thistemplate '/etc/foo' do mode '0644' source 'foo.erb' not_if { 'test -f /etc/foo' }end
# Do this insteadtemplate '/etc/foo' do mode '0644' source 'foo.erb' not_if 'test -f /etc/foo'end
correctness
This warning is shown if you set an attribute on a Chef resource that istechnically accessible but should not be set in normal usage.To avoid this warning allow Chef to set the value of the internalattribute rather than setting it yourself.
Service resource sets internal attributeThis example matches the FC027 rule because it sets the running
attribute on a service resource. This attribute should normally beset by the provider itself and not in normal recipe usage.
In this particular example you can achieve the same effect by usingthe service :start
action.
# Don't do thisservice 'foo' do running trueend
# Do this insteadservice 'foo' do action :startend
correctness
This warning is shown if you attempt to use the platform?
Chef built-inmethod as node.platform?
. Because of the way Chef attributes work thelater approach will not error but will do the wrong thing which mayresult in resources you had intended to apply only to a single platforminstead being applied to all platforms.
This example matches the FC028 rule because the platform?
methodis incorrectly prefixed with node
.
Remove the leading node.
from the use of platform?
to resolvethis warning.
# Don't do thisfile '/etc/foo' do only_if { node.platform?('commodore64') }end
# Do this insteadfile '/etc/foo' do only_if { platform?('commodore64') }end
correctness
metadata
This warning is shown if you declare a recipe in your cookbook metadatawithout including the cookbook name as a prefix.
Recipe declared without cookbook name prefixThis example matches the FC029 rule because the metadata declares arecipe without prefixing it with the name of the current cookbook.
Modified versionThis modified example would not match the FC029 rule:
# Don't do thisname 'example'version '1.2.3'recipe 'default', 'Installs Example'
# Do this insteadname 'example'version '1.2.3'recipe 'example::default', 'Installs Example'
correctness
Pry is a fantastic tool for interactiveexploration of a running Ruby program. You can place breakpoints in yourcookbook code that will launch a Pry console. This warning is shown whenyour cookbook code contains these breakpoints, as failing to remove thesewill cause your Chef run to halt.
This rule currently only checks for use of binding.pry
and not the Chefbuilt-in breakpoint
resource which is never used outside ofchef-shell.
This example matches the FC030 rule because it includes a Prybreakpoint declared with binding.pry
.
This modified example would not match the FC030 rule:
# Don't do thistemplate '/etc/foo' do source 'foo.erb'endbinding.pry
# Do this insteadtemplate '/etc/foo' do source 'foo.erb'end
correctness
metadata
Chef cookbooks normally include a metadata.rb
file which can be usedto express awide range of metadata about a cookbook.This warning is shown when a directory appears to contain a cookbook, butdoes not include the expected metadata.rb
file at the top-level.
correctness
notifications
Chef notificationsallow a resource to define that it should be actioned when anotherresource changes state.
Notification timing can be controlled and set to immediate
, or delayed
until the end of the Chef run. This warning is shown when the timingspecified is not recognised.
This example matches the FC032 rule because it specifies an invalidnotification timing.
Modified versionThis modified example would not match the FC032 rule because themispelt timing has been corrected.
# Don't do thistemplate '/etc/foo' do notifies :restart, 'service[foo]', :imediatelyend
# Do this insteadtemplate '/etc/foo' do notifies :restart, 'service[foo]', :immediateend
correctness
templates
This warning is shown when the erb template associated with atemplate resourcecannot be found.
correctness
templates
This warning is shown when one or more variables passed into a templateby a template resourceare not then used within the template.
This is often a sign that a template still contains hard-coded values thatyou intended to parameterise.
Unused template variablesThis example matches the FC034 rule because it passes two variablesto the template, of which only the first is used.
Modified versionThis modified example would not match the FC034 rule becuse thetemplate has been updated to include both variables passed through.
template '/etc/foo/config.conf' do source 'config.conf.erb' variables( 'config_var_a' = node['config']['config_var_a'], 'config_var_b' = node['config']['config_var_b'] )end# config.conf.erb# var_a=%= @config_var_a %
template '/etc/foo/config.conf' do source 'config.conf.erb' variables( 'config_var_a' = node['config']['config_var_a'], 'config_var_b' = node['config']['config_var_b'] )end# config.conf.erb# var_a=%= @config_var_a %# var_b=%= @config_var_b %
This rule has been deprecated. See the discussion againstissue #60 for moredetail.
correctness
notifications
This warning is shown when a resourcenotifiesanother resource to take an action, but the action is invalid for thetarget resource type.
Invalid notification actionThis example matches the FC037 rule because :activate_turbo_boost
isnot a valid action for services.
This modified example would not match the FC037 rule because theaction has been corrected.
# Don't do thistemplate '/etc/foo.conf' do notifies :activate_turbo_boost, 'service[foo]'end
# Do this insteadtemplate '/etc/foo.conf' do notifies :restart, 'service[foo]'end
correctness
This warning is shown when a resource action is not valid for the type ofresource.
Invalid resource actionThis example matches the FC038 rule because :none
isnot a valid action.
This modified example would not match the FC038 rule because theaction has been corrected.
# Don't do thisservice 'foo' do action :noneend
# Do this insteadservice 'foo' do action :nothingend
correctness
Chef allows you to use varying syntax to refer to node attributes.This warning is shown when you attempt to reference a method onChef::Node
using the same string or symbol syntax reserved for nodeattributes.
This example matches the FC039 rule because run_state
isonly accessible as a method and cannot be referenced as an attribute.
This modified example would not match the FC039 rule because therun_state
is referenced as a method.
# Don't do thisnode['run_state']['nginx_force_recompile'] = false
# Do this insteadnode.run_state['nginx_force_recompile'] = false
style
This warning is shown if you declare an execute
resource that uses git.If the command you are attempting to execute is supported by the git
resource you should probably use that instead.
This example matches the FC040 rule because an execute
resource isused where you could instead use a git
resource.
This modified example would not match the FC040 rule because theexecute
resource has been replaced by a git
resource.
# Don't do thisexecute 'git clone https://github.com/git/git.git' do action :runend
# Do this insteadgit '/foo/bar' do repository 'git://github.com/git/git.git' reference 'master' action :syncend
style
portability
This warning is shown if you use an execute resource to run the curl
orwget
commands. If you are downloading a file consider using theremote_file
resource instead.
This example matches the FC041 rule because an execute
resource isused where you could instead use a remote_file
resource.
This modified example would not match the FC041 rule because theexecute
resource has been replaced by a remote_file
resource.
# Don't do thisexecute "cd /tmp wget 'http://example.org/'" do action :runend
# Do this insteadremote_file '/tmp/testfile' do source 'http://www.example.org/'end
deprecated
correctness
This warning is shown when require_recipe
is used. Becauserequire_recipe
has been deprecated you should replace any references toto require_recipe
with include_recipe
.
This example matches the FC042 rule because the deprecatedrequire_recipe
statement is used.
This modified example would not match the FC042 rule because therequire_recipe
statement has been replaced with include_recipe
.
# Don't do thisrequire_recipe 'apache2::default'
# Do this insteadinclude_recipe 'apache2::default'
correctness
notifications
deprecated
This warning is shown when you use the old-style notification syntax. Youshould prefer the new-style notification syntax which has the advantagethat you can notify resources that are defined later.
Old notification syntaxThis example matches the FC043 rule because it uses the oldernotification syntax.
Modified versionThis modified example would not match the FC043 rule because thesyntax of the notification has been updated to use the new format.
# Don't do thistemplate '/etc/www/configures-apache.conf' do notifies :restart, resources(:service = 'apache')end
# Do this insteadtemplate '/etc/www/configures-apache.conf' do notifies :restart, 'service[apache]'end
style
This warning is shown when, within a cookbook attributes file, you referto an attribute as you would a local variable rather than as an attributeof the node
object. It is valid to do the former, but you should preferthe later more explicit approach to accessing attributes because it iseasier for users of your cookbooks to understand.
This example matches the FC044 rule because it refers to thehostname
attribute as a bare attribute.
This modified example would not match the FC044 rule because thereference to the hostname
attribute has been qualified so thatthe meaning is more apparent.
# Don't do thisdefault['myhostname'] = hostname
# Do this insteaddefault['myhostname'] = node['hostname']
correctness
metadata
chef12
This warning is shown when your cookbook does not define a name withinthe cookbook metadata.rb
file. It’s a good idea to specify a name inyour cookbook metadata to avoid breakage if the name of the containingdirectory changes. Additionally, Chef 12 requires the name to be includedin the metadata.rb file.
This example matches the FC045 because it lacks the name property
Modified versionThis modified example would not match the FC045 because it contains thename property
# Don't do thismaintainer 'The Authors'maintainer_email 'you@example.com'license 'All Rights Reserved'description 'Installs/Configures test'long_description 'Installs/Configures test'version '0.1.0'
# Do this insteadname 'example'maintainer 'The Authors'maintainer_email 'you@example.com'license 'All Rights Reserved'description 'Installs/Configures test'long_description 'Installs/Configures test'version '0.1.0'
attributes
correctness
It is acommon convention in Ruby developmentto use ||=
to assign a value to variable if it is false
or nil
.Frequently developers with earlier exposure to Ruby attempt to use thesame approach to assign a default value to node attributes within Chef.
This doesn’t work correctly because Chef auto-vivifies attributes so amissing attribute is never falsey.
Using assign unless nil with node attributesThis example matches the FC046 rule because it uses assign unless nil(||=
) with node attributes.
This modified example would not match the FC046 rule because theassign unless nil expression has been replaced with default_unless
.
# Don't do thisdefault['somevalue'] ||= []
# Do this insteaddefault_unless['somevalue'] = []
attributes
correctness
chef11
From Chef 11 it is no longer possible to set attributes without specifyingtheir precedence level. For more information refer to the list ofBreaking Changes in Chef 11.
Assign an attribute value without specifying precedenceThis example matches the FC047 rule because it writes to the attributewithout specifying the precedence level to set.
This will work in Chef versions 11 but you should prefer the newsyntax.
Modified versionThis modified example would not match the FC047 rule because theattribute assignment has been updated to specify a precedence levelof normal
.
# Don't do thisnode['foo'] = 'bar'
# Do this insteadnode.normal['foo'] = 'bar'
portability
Normally to execute an operating system command with Chef you would usea built-in resource such as the execute
resource.
You might also have a need to spawn processes from Ruby, either inlineor within a ruby_block
. There are many different ways to do this in Ruby- my favourite reference isJesse Storimer’s Working with Unix Processes.
Chef comes with a library calledMixlib::ShellOut thatprovides a more convenient interface and it is idiomatic to use it ratherthan the backtick `
or %x{}
syntaxes.
This example matches the FC048 rule because it uses the %x{}
sigil.
This modified example would not match the FC048 rule because it isusing the Mixlib::ShellOut
library.
# Don't do thisresult = %x{some_command}raise 'Problem executing some_command' unless $?.success?
# Do this insteadcmd = Mixlib::ShellOut.new('some_command')cmd.run_commandcmd.error!
style
roles
This warning is shown if you declare a name
in arole filethat does not match the containing file name. Using the same name for bothis more consistent.
correctness
environments
roles
This warning is shown if the name declared in a roleor environmentfile contains characters that are not allowed.
“[Names should be] made up of letters (upper-and lower-case), numbers, underscores, and hyphens:[A-Z][a-z][0-9]
and [_-]
. Spaces are not allowed.”
This example matches the FC050 rule because the name includes a space character.
Modified versionThis modified example would not match the FC050 rule because the spacehas been removed from the role name.
# Don't do thisname 'web server'run_list 'recipe[apache2]'
# Do this insteadname 'webserver'run_list 'recipe[apache2]'
correctness
templates
This warning is shown if a template uses template partials in a way thatwould cause an infinite loop. For example if two template partials bothinclude each other.
style
deprecated
metadata
This warning is shown if metadata.rb includes the suggests metadata. Suggestsmetadata was often used to inform users that a cookbook was required fora particular use case, but suggests itself was never implemented in chef-client.Adding suggests has no impact on the chef-client run and should be avoided.
Metadata with the deprecated suggests keyword Metadata instead using a depends keyword# Don't do thisname 'example'version '1.0.0'suggests 'windows'
# Do this insteadname 'example'version '1.0.0'depends 'windows'
style
deprecated
metadata
This warning is shown if metadata.rb includes the recommends metadata.Recommends metadata was often used to inform users that a cookbook wasrecommended for a particular use case, but recommends itself was neverimplemented in chef-client. Adding recommends has no impact on thechef-client run and should be avoided.
Metadata with the deprecated recommends keyword Metadata instead using a depends keyword# Don't do thisname 'example'version '1.0.0'recommends 'windows'
# Do this insteadname 'example'version '1.0.0'depends 'windows'
correctness
supermarket
metadata
This warning is shown if the metadata does not include the maintainerkeyword. Cookbooks should always contain maintainer information so userscan determine the maintainer of the cookbook.
correctness
supermarket
metadata
This warning is shown if the metadata does not include the maintainer_emailkeyword. Cookbooks should always contain maintainer_email so users cancontact the maintainer.
This rule has been deprecated. Chef 13 now uses use_inline_resources by default so LWRPs always notify updates.
correctness
lwrp
This warning is shown if a library provider includes use_inline_resources,but declares it’s actions using action_
This rule has been deprecated. Chef 13 now uses use_inline_resources by default so LWRPs always notify updates.
correctness
lwrp
This warning is shown if a LWRP provider includes use_inline_resources,but declares it’s actions using action_
correctness
metadata
supermarket
This warning is shown if a cookbook includes an invalid version string inthe metadata file. Cookbooks that do not follow this format cannot beuploaded to the chef server.
Metadata with incorrect version Metadata with valid version# Don't do thisname 'example'version '1.0.0.1'depends 'example'
# Do this insteadname 'example'version '1.0.1'
metadata
supermarket
This warning is shown if a cookbook does not contain a version string inthe metadata file. Without a version string cookbooks will be uploaded asversion 0.0.0 each time. It is best practice to provide accurate versionsthat are incremented on each release, which requires specifying the string.
metadata
correctness
This warning is shown if a cookbook depends on itself within its own metadata.Cookbooks need specify a dependency on other cookbooks which they rely on, butall recipes, resources and libraries within the cookbook itself are loaded andavailable so there is noneed for a self dependency.
Metadata depending on itself Modified metadata that doesn't depend on itself# Don't do thisname 'example'version '1.0.0'depends 'example'
# Do this insteadname 'example'version '1.0.0'
metadata
supermarket
This warning is shown if a cookbook does not include the issues_url property inits metadata file. issues_url is used to point to the location for submitting issues(bugs) for the cookbook and is currently parsed by Supermarket to add links to communitycookbooks. Note: issues_url requires Chef 12+.
Metadata without issues_url Modified version# Don't do thisname 'example'version '1.0.0'
# Do this insteadname 'example'version '1.0.0'issues_url 'https://github.com/chef-cookbooks/something/issues'
metadata
supermarket
This warning is shown if a cookbook does not include the source_url property inits metadata file. source_url is used to point to the source location for thecookbook and is currently parsed by Supermarket to add links to community cookbooks.Note: source_url requires Chef 12+.
Metadata without source_url Modified versionname 'example'version '1.0.0'
name 'example'version '1.0.0'source_url 'https://github.com/chef-cookbooks/something'
metadata
This warning is shown if a cookbook does not include the chef_version propertyin its metadata file. chef_version is used to clearly specify chef versioncompatibility to users and to chef-client.
Metadata without chef_version Modified version with chef_versionname 'example'version '1.0.0'
name 'example'version '1.0.0'chef_version '= 12.5' if respond_to?(:chef_version)
metadata
supermarket
This warning is shown if a cookbook does not include any supports propertiesin its metadata file. supports is used to clearly specify platform supportto users. Platform badges are added to cookbooks on Supermarket which allowsusers to search for specific platform supported cookbooks.
Metadata without supports Modified version with supportsname 'example'version '1.0.0'
name 'example'version '1.0.0'supports 'redhat'
metadata
supermarket
license
This warning is shown if a cookbook does not include a license propertyin its metadata file. license is used to clearly specify how the cookbookcan be used, modified, and shared to users and is displayed on Supermarket.
Metadata without license Modified version with licensename 'example'version '1.0.0'
name 'example'version '1.0.0'license 'Apache-2.0'
metadata
supermarket
license
This warning is shown if a cookbook does not use a standardized SPDX.orgdefined license for the license property in its metadata file. Using astandardized license list enables users to identify valid compliant licenses.
Metadata with non-standardized license Modified version with standardized licensename 'example'version '1.0.0'license 'Apache 2.0'
name 'example'version '1.0.0'license 'Apache-2.0'
metadata
supermarket
This warning is shown if a cookbook uses an invalid platform for a supports propertyin its metadata file. Using a valid platform enables users to identify supportedcookbooks and ensures that searching on Supermarket with platforms specifiedreturns the supported cookbooks.
Metadata with an invalid supports property Modified version with valid supports propertyname 'example'version '1.0.0'supports 'rhel'
name 'example'version '1.0.0'supports 'redhat'
style
license
This warning is shown if a cookbook does not include a LICENSE file. A LICENSEfile allows consumers of cookbooks to determine if the terms allow them to use,change or distribute a cookbook. The file is also parsed by many many onlineservices such as Github to provide addition functionality within their services.
metadata
style
This warning is shown if a cookbook defines its attributes in the metadata.rb file.Attributes defined in the metadata.rb file are not used by the chef-client orSupermarket and often become out of sync with the attributes files or readme.Documentation for attributes should instead be placed in the readme itself.
Metadata with a deprecated attributes keyword Metadata without a deprecated attributes keyword# Don't do thisname 'example'version '1.0.0'attribute 'something', :display_name = 'Something', :description = 'Hash of Something attributes', :type = 'hash'
# Do this insteadname 'example'version '1.0.0'
correctness
chef13
This warning is shown if a cookbook contains both a root alias and the target of thealias. Chef will ignore the non-alias file so it should be removed.
correctness
lwrp
Chef 11 introduced a new DSL method ‘default_action’ for LWRPs that allowsdefining the default action a LWRP should run if no action is specified.This method should be used instead of defining the default actoin throughan initialize method in the resource.
LWRP defining a default action through an initialize method LWRP defining a default action through the DSL method# Don't do thisactions :add, :removedef initialize(*args) super @action = :addend
# Do this insteadactions :add, :removedefault_action :add
correctness
Chef provides a ‘node.save’ method, which allows saving the state of thenode part way through a chef-client run. This is often used to ensure a run_listis saved or so that other state information is immediately available for searchby other nodes in your environment. The use of node.save can be incrediblyproblematic and should be avoided as a run failure will still result in thenode data being saved to the Chef server. If search is used to put nodes intoproduction state this may result in non-functioning nodes being used.
style
deprecated
metadata
This warning is shown if metadata.rb includes the conflicts metadata. Conflictsmetadata was often used to inform users of an incompatible cookbook that shouldnot be used in conjunction with the current cookbook. Conflicts was never actuallyimplemented in chef-client and its inclusion had no actual impact on the chef-clientrun.
Metadata with the deprecated conflicts keyword Metadata without conflicts keyword# Don't do thisname 'example'version '1.0.0'conflicts 'foo'
# Do this insteadname 'example'version '1.0.0'
style
deprecated
metadata
This warning is shown if metadata.rb includes the replaces metadata. Replacesmetadata was often used to inform users of a previous cookbook that was replacedby the current cookbook. Replaces was never actually implemented in chef-clientand its inclusion had no actual impact on the chef-client run.
Metadata with the deprecated replaces keyword Metadata without replaces keyword# Don't do thisname 'example'version '1.0.0'replaces 'foo'
# Do this insteadname 'example'version '1.0.0'
opensource
license
supermarket
This warning is shown if metadata.rb includes a cookbook license value that is not denotedas being an OSI approved open source license by SPDX.org.
deprecated
chef13
This warning is shown if a cookbook uses the legacy easy_install_package resource. Thisresource was deprecated in Chef 12 and removed in Chef 13.
deprecated
chef13
This warning is shown if a user resource includes the supports property, which was deprecatedin Chef 12 and removed in Chef 13. See the example below for properly specificing valuespreviously in supports
User resource using deprecated supports property Metadata properly specifying manage_home and non_unique# Don't do thisuser 'betty' do action :create supports({ manage_home: true, non_unique: true })end
# Do this insteaduser 'betty' do action :create manage_home true non_unique trueend
chef12
This warning is shown if a cookbook metadata depends on the ‘partial_search’ cookbook. Chef12 included the partial search functionality in chef-client itself so this cookbook is nolonger necessary. See the Chef search filtering docsfor usage of the built in functionality.
deprecated
chef14
This warning is shown if node.set or node.set_unless are used to set a value on the node.Both of these methods for setting attributes will be removed in Chef 14 as thenames were confusing and particularly attractive to new users. These methods permanentlyset the attribute on the node even if the cookbook code is later removed, which isgenerally not what the user wants. If this functionality is in fact what you desire youshould use node.normal or node.normal_unless, which are functionally equivalent. In generalusers should fully understand the implications of choosing a particular attribute level byreading the Chef attributes type documentation.
node.set used to set a node attribute value node.normal used to set a node attribute# Don't do thisnode.set['foo']['bar'] = 'baz'node.set_unless['foo1']['bar1'] = 'baz1'
# Do this instead if you actually want persistent attributesnode.normal['foo']['bar'] = 'baz'node.normal_unless['foo1']['bar1'] = 'baz1'
deprecated
chef12
This warning is shown if an execute resource includes the deprecated path property, whichwas removed in Chef 12. You should instead using the environment property to set the PATHvariable.
execute source with the path property execute resource with the environment property# Don't do thisexecute 'some_binary some_option' do path '/some/path/to/my/bin'end
# Do this insteadexecute 'some_binary some_option' do environment 'PATH' = '/some/path/to/my/bin'end
deprecated
chef13
This warning is shown if the deprecated Chef::REST class used in a cookbook.Chef::REST has been replaced by Chef::ServerAPI. See Chef Deprecation CHEF-9
correctness
This warning is shown if a LWRP or Custom Resource uses new_resource.updated_by_last_action(true) to signal that a resource has been updated, and thus any necessary notification should fire. This method of controlling resource state was necessary with Chef 10 and earlier, however it is no longer required when writing resources. Additionally updated_by_last_action often leads to resources notifying on every Chef run, regardless of actual change. By utilizing use_inline_resources it is no longer necessary to manually control resource state when resources are comprised of built-in Chef resources such as execute, file, directory, etc. For resources comprised of non-Chef Ruby code, such as API calls or Mixlib::ShellOut calls, resource state should be controlled with the converge_by helper. Converge_by wraps code that would make a change to the node, allowing for why-run mode and providing a friendly log message on convergence.
LWRP with all chef resources using new_resource.updated_by_last_action(true) LWRP with all chef resources using use_inline_resources LWRP with custom ruby using new_resource.updated_by_last_action(true) LWRP with custom ruby using converge_by# Don't do thisaction :create do directory '/foo/bar' do action :create end new_resource.updated_by_last_action(true)end
# Do this insteaduse_inline_resourcesaction :create do directory '/foo/bar' do action :create endend
# Don't do thisaction :create do create_something_api_call new_resource.updated_by_last_action(true)end
# Do do thisaction :create do converge_by "create something" do create_something_api_call endend
style
This warning is shown if the data bag helper methods are not used to load data from a data bag. The data bag helpers are much simpler and also work for both encrypted and plain text data bags. See the Chef Data Bag Docs for additional usage details
Accessing a data bag item without the helper Accessing a data bag item using the helper# Don't do thisplain_text_data = Chef::DataBagItem.load('foo', 'bar')encrypted_data = Chef::EncryptedDataBagItem.load('foo2', 'bar2')
# Do do thisplain_text_data = data_bag_item('foo', 'bar')encrypted_data = data_bag_item('foo2', 'bar2')
deprecated
chef13
This warning is shown if the deprecated Chef::Platform.set method is used to define the platforms a HWRP runs on. This method has been removed from Chef 13. To create resources that map to specific platforms you should instead consider using provides in a custom resource. See the Chef Custom Resources Documention for additional details.
deprecated
chef13
This warning is shown if the deprecated Chef::Mixin::Command class is used to shell out within a recipe, library, or resource. This class has been removed in Chef 13 and Mixlib::Shellout should be used instead.
deprecated
chef13
This warning is shown if the deprecated Chef::ShellOut class is used to shell out within a recipe, library, or resource. This class has been removed in Chef 13 and Mixlib::ShellOut should be used instead.
Using Chef::Shellout to Shellout Mixlib::ShellOut version# Don't do thisChef::ShellOut.new('some_command').run_command
# Do this insteadMixlib::ShellOut.new('some_command').run_command
correctness
This warning is shown if a custom resource defines attributes instead of properties. While Chef will do the right thing this may not always be the case and custom resources should be properly defined using properties.
Defining attributes in a custom resource Defining properties in a custom resource# Don't do thisattribute :source, String, name_attribute: trueaction :create do # some resource code hereend
# Do this insteadproperty :source, String, name_property: trueaction :create do # some resource code hereend
correctness
This warning is shown if a custom resource declare its actions instead of letting Chef determine the set of actions defined in the resource itself.
Declaring actions in a custom resource Not declaring actions in a custom resource# Don't do thisactions :createaction :create do # some resource code hereend
# Do this insteadaction :create do # some resource code hereend
readme
supermarket
This warning is shown if you used chef generate cookbook
to create a newcookbook and didn’t change boilerplate text in README file. You need toupdate it with real description.
FC093 will match README files containing TODO: Enter the cookbook description here.
deprecated
chef14
This warning is shown if a cookbook uses the node[‘filesystem2’] attributes. In Chef 13 the filesystem Ohai plugin was replaced with the filesystem2 plugin. Data is written to both locations for now, but the existing node[‘filesystem2’] namespace will be removed in Chef 14 (April 2018). See https://docs.chef.io/deprecations_ohai_filesystem.html and https://docs.chef.io/deprecations_ohai_filesystem_v2.html.
Using node['filesystem2'] Using node['filesystem']# Don't do thisblocksize = node['filesystem2']['by_device']['/dev/disk1s1']['blocksize']
# Do thisblocksize = node['filesystem']['by_device']['/dev/disk1s1']['blocksize']
deprecated
chef14
This warning is shown if a cookbook uses the node[‘cloud_v2’] attributes. In Chef 13 the cloud Ohai plugin was replaced with the cloud_v2 plugin. Data is written to both locations for now, but the existing node[‘cloud_v2’] namespace will be removed in Chef 14 (April 2018). See https://docs.chef.io/deprecations_ohai_cloud.html and https://docs.chef.io/deprecations_ohai_cloud_v2.html.
Using node['cloud_v2'] Using node['cloud']# Don't do thisprovider = node['cloud_v2']['provider']
# Do thisprovider = node['cloud']['provider']
deprecated
chef14
This warning is shown if a cookbook uses the node[‘virtualization’] attributes populated by the libvirt Ohai plugin. This plugin polls data from libvirt, but requires installing an extra gem into the Chef installation, and therefore is not heavily used. In Chef 14 these attributes will be moved into their own namespace at node[‘libvirt’]. See https://docs.chef.io/deprecations_ohai_libvirt_plugin.html.
Using node['virtualization'] libvirt attributes Using node['libvirt'] attributes# Don't do thisuri = node['virtualzation']['uri']
# Do thisuri = node['libvirt']['uri']
deprecated
chef14
This warning is shown if a cookbook uses the Chef::Mixin::LanguageIncludeAttribute mixin. This mixin was deprecated with the release of Chef 11 and will be removed in Chef 14. Chef::DSL::IncludeAttribute should be used in its place.
Using LanguageIncludeAttribute mixin Using IncludeAttribute DSL# Don't do thisinclude Chef::Mixin::LanguageIncludeAttribute
# Do thisinclude Chef::DSL::IncludeAttribute
deprecated
chef14
This warning is shown if a cookbook uses the Chef::Mixin::RecipeDefinitionDSLCore mixin. This mixin was deprecated with the release of Chef 11 and will be removed in Chef 14. Chef::DSL::Recipe should be used in its place.
Using RecipeDefinitionDSLCore mixin Using Recipe DSL# Don't do thisinclude Chef::Mixin::RecipeDefinitionDSLCore
# Do thisinclude Chef::DSL::Recipe
deprecated
chef14
This warning is shown if a cookbook uses the Chef::Mixin::LanguageIncludeRecipe mixin. This mixin was deprecated with the release of Chef 11 and will be removed in Chef 14. Chef::DSL::IncludeRecipe should be used in its place.
Using LanguageIncludeRecipe mixin Using Recipe DSL# Don't do thisinclude Chef::Mixin::LanguageIncludeRecipe
# Do thisinclude Chef::DSL::IncludeRecipe
deprecated
chef14
This warning is shown if a cookbook uses the Chef::Mixin::Language mixin. This mixin was deprecated with the release of Chef 11 and will be removed in Chef 14. Chef::DSL::PlatformIntrospection or/and Chef::DSL::DataQuery should be used in its place.
Using Language mixin Using DataQuery/PlatformIntrospection DSL# Don't do thisinclude Chef::Mixin::Language
# Use one or both of theseinclude Chef::DSL::PlatformIntrospectioninclude Chef::DSL::DataQuery
deprecated
chef14
This warning is shown if a cookbook uses the deploy resource. The deploy and deploy_revision resources have been deprecated as of Chef 13.6, and will be removed in Chef 14 (April 2018). See https://docs.chef.io/deprecations_deploy_resource.html.
deprecated
chef14
This warning is shown if a cookbook uses the Chef::DSL::Recipe::FullDSL Ruby module.
Using Chef::DSL::Recipe::FullDSL module Using Chef::DSL::Recipe# Don't do thisinclude Chef::DSL::Recipe::FullDSL
# Use this insteadinclude Chef::DSL::Recipe
deprecated
chef14
This warning is shown if a cookbook includes a chocolatey_package resource using the :uninstall action. The :remove action should be used instead.
correctness
This warning is shown if a cookbook includes a ruby_block resource with the :create action or another resource notifies a ruby_block with the :create action. The :create action is an alias to :run and the :run action should be used instead as it is more clear what action Chef will be performing.
deprecated
chef14
This warning is shown if a cookbook uses the erl_call resource. The erl_call resource has been deprecated as of Chef 13.7, and will be removed in Chef 14 (April 2018). See https://docs.chef.io/deprecations_erl_call_resource.html.
deprecated
chef13
This warning is shown if a cookbook includes a launchd resource with a ‘hash’ property. In Chef 13.0 this property was renamed to plist_hash to avoid conflicts with Ruby itself.
deprecated
chef14
This warning is shown if a cookbook includes a resource with the ‘epic_fail’ property. The epic fail property is an alias to ‘ignore_failure’, which better describes the desired outcome. In Chef 14 (April 2018) epic_fail will be removed.
epic_fail usage ignore_failure usage# Don't do thisexecute 'some command' do epic_fail trueend
# Do this insteadexecute 'some command' do ignore_failure trueend
correctness
This warning is shown if a resource defines a property with the name of ‘:name’. Chef itself creates this same name property by default, and it’s not necessary or desirable to define it again. This property can be removed from any resource. It should be noted that setting ‘name_property: true’ on properties with any other name is still entirely valid as that allows overriding the name specified when using the resource.
Specifying a :name property Omitting the name property# Don't do thisproperty :name, String, name_property: trueproperty :foo, Stringproperty :bar, String
# Do this insteadproperty :foo, Stringproperty :bar, String
correctness
This warning is shown if a cookbook contains a package resource that defines its provider. If a specific package resource is needed for a package install that resource should be used instead of the package resource with a provider specified. The package resource wraps multiple platform specific platform specific package resources and dynamically uses the correct provider under the hood such as rpm_package or apt_package. Defining the provider outside of this logic will not always produce the intended results and may cause failures. It should also be noted that unless there is a specific reason for using a specific package resource you should always use ‘package’ and let Chef dynamically choose the right platform specific package resource at runtime.
Specifying the provider Using a specific package resource# Don't do thispackage 'foo' do provider Chef::Provider::Package::Apt action :installend
# Do this insteadapt_package 'foo' do action :installend
deprecated
chef13
This warning is shown if a cookbook contains a script resource that defines the script in a ‘command’ property instead of a ‘code’ property
Using the command property Using the code property# Don't do thisscript 'foo' do command 'run some things'end
# Do this insteadscript 'foo' do code 'run some things'end
deprecated
chef13
This warning is shown if a cookbook uses search with the ‘sort’ flag. This flag hasn’t worked since Chef Server 9 and the flag was removed in Chef 13.
deprecated
chef13
This warning is shown if a cookbook contains a resource using the deprecated dsl_name method.
Using dsl_name Using resource_name# Don't do thismy_resource = MyResource.dsl_name
# Do this insteadmy_resource = MyResource.resource_name
deprecated
chef15
This warning is shown if a cookbook contains a resource using the deprecated use_inline_resources method. use_inline_resources is the default with Chef 13 and this call can be removed from all resources unless Chef 12 compatibility is needed.
deprecated
chef13
This warning is shown if a cookbook uses the legacy Ohai configuration syntax. This syntax needs to be used for Chef/Ohai 13. See https://docs.chef.io/deprecations_ohai_legacy_config.html for more information.
correctness
This warning is shown if a custom resource property has both required: true and name_property: true set. name_property: true instructs Chef to use the name of the resource unless the user has explicitly passed a value for the property. Since there is always a value for properties with name_property set there is no need to set required: true.
Setting both name_property and required Setting just name_property# Don't do thisproperty :my_property_name, String, name_property: true, required: true
# Do this insteadproperty :my_property_name, String, name_property: true
deprecated
This warning is shown if a cookbook depends on the now deprecated compat_resource cookbook. This cookbook backported newer Chef 12 functionality to older Chef 12 client releases. It was primarily used to provide custom resource fuctionality to 12.0-12.4 clients, but also backported several resources such as apt_repository and yum_repository. Chef 12 is end of life and this cookbook wasn’t necessary after Chef 12.19. Cookbooks should no longer rely on this cookbook, but should instead increase the minimal chef_version requirements in their metadata.
depending on compat_resource require a newer chef-client release# Don't do this in metadata.rbname 'my_cookbook'depends 'compat_resource'chef_version '= 12.0'
# Do this instead in metadata.rbname 'my_cookbook'chef_version '= 12.19'
correctness
This warning is shown if a custom resource property sets its type using kind_of. kind_of was used in LWRPs to set type in attributes, but should not be used in custom resources. Instead simply set the Ruby type for the property after the name as shown below.
Using kind_of in a custom_resource property Using just a Ruby type# Don't do thisproperty :my_property_name, kind_of: String
# Do this insteadproperty :my_property_name, String
correctness
This warning is shown if a custom resource property sets name_attribute: true instead of name_property: true. This is generally found in LWRPs that were updated to custom resources as name_attribute was valid for LWRPs. They are currently aliases, but this may eventually cause failures.
Using name_attribute in a custom resource Using name_property in a custom resource# Don't do thisproperty :my_property_name, String, name_attribute: true
# Do this insteadproperty :my_property_name, String, name_property: true
chef13
deprecated
This warning is shown if a cookbook uses a windows_task resource with the action of :change. The original windows_task resource in the Windows cookbook required creating the task with the :create action and updating it with the :change action. In Chef 13 the windows_task shipped built into chef-client and was rewritten to properly update if necessary when using the :create action. Cookbooks using both :create and :change will need to be tested on Chef 13 using just the :create action.
correctness
A resource’s name should not be set via the name
property.
correctness
The build-essential
, dmg
, chef_handler
, chef_hostname
, mac_os_x
, swap
, or sysctl
cookbooks have been deprecated by built-in resources included with Chef 14. Removing these dependencies requires that metadata be changed to chef_version = 14.0
.
deprecated
Chef 14 introduces a built-in resource, build_essential
, which deprecates the build-essential
cookbook. The cookbook has included this resource since v5.0.0.
files
Chef cookbooks should not be used to distribute binary files. This is better done via artifact stores such as Artifactory/Nexus or via a simple FTP/HTTP site.
Choosing which rules to run
Foodcritic comes with a bunch of rules built-in. You will probably find some of them useful and others annoying. The trick to only running the rules you actually care about are what foodcritic calls tags.
TagsEach rule has a number of associated tags. You can filter which rules are actually checked by specifying the tags that you want to apply at the command line.Only check against correctness rules
As an example, the following arguments will run foodcritic but only showing warnings for rules tagged with the correctness
tag.
$ foodcritic -t correctness
Excluding a particular rule Each rule is tagged with its own code, normally something like FC123
. To avoid checking a particular rule use the ~
(tilde) modifier at the command line.
$ foodcritic -t ~FC002
Running only rules tagged with both tags Let's say we want to only check against rules that are tagged with both style
and services
. We don't want to check against rules that have only one or the other. Our command line to do this would look like this:
$ foodcritic -t style -t services
Running rules tagged with either tag Alternatively we might want to run rules that are tagged with either style
or services
. To do this we separate the rule codes with a comma:
$ foodcritic -t style,services
Tag ReferenceBelow is the list of built-in foodcritic rules shown by tag:
attributes FC001: Use strings in preference to symbols to access node attributes FC019: Access node attributes in a consistent manner FC046: Attribute assignment uses assign unless nil FC047: Attribute assignment does not specify precedence chef11 FC047: Attribute assignment does not specify precedence chef12 FC045: Metadata does not contain cookbook name FC081: Cookbook depends on the partial_search cookbook FC083: Execute resource using deprecated 'path' property chef13 FC073: Root alias file shadowing non-alias file FC079: Deprecated easy_install_package resource usage FC080: User resource uses deprecated supports property FC084: Deprecated Chef::REST class used FC087: Library maps provider with deprecated Chef::Platform.set FC088: Prefer Mixlib::Shellout over deprecated Chef::Mixin::Command FC089: Prefer Mixlib::Shellout over deprecated Chef::ShellOut FC106: Use the plist_hash property in launchd instead of hash FC110: Script resources should use 'code' property not 'command' property FC111: search using deprecated sort flag FC112: Resource using deprecated dsl_name method FC114: Cookbook uses legacy Ohai config syntax FC119: windows_task :change action no longer exists in Chef 13 chef14 FC082: node.set or node.set_unless used to set node attributes FC094: Cookbook uses deprecated filesystem2 ohai plugin data FC095: Cookbook uses deprecated cloud_v2 ohai plugin data FC096: Cookbook uses deprecated libvirt virtualization ohai data FC097: Deprecated Chef::Mixin::LanguageIncludeAttribute mixin used FC098: Deprecated Chef::Mixin::RecipeDefinitionDSLCore mixin used FC099: Deprecated Chef::Mixin::LanguageIncludeRecipe mixin used FC100: Deprecated Chef::Mixin::Language mixin used FC101: Deprecated deploy resource used FC102: Deprecated Chef::DSL::Recipe::FullDSL class used FC103: Deprecated :uninstall action in chocolatey_package used FC105: Deprecated erl_call resource used FC107: Resource uses epic_fail instead of ignore_failure chef15 FC113: Resource declares deprecated use_inline_resources correctness FC006: Mode should be quoted or fully specified when setting file permissions FC007: Ensure recipe dependencies are reflected in cookbook metadata FC009: Resource attribute not recognised FC010: Invalid search syntax FC016: LWRP does not declare a default action FC018: LWRP uses deprecated notification syntax FC021: Resource condition in provider may not behave as expected FC022: Resource condition within loop may not behave as expected FC025: Prefer chef_gem to compile-time gem install FC026: Conditional execution block attribute contains only string FC027: Resource sets internal attribute FC028: Incorrect #platform? usage FC029: No leading cookbook name in recipe metadata FC030: Cookbook contains debugger breakpoints FC031: Cookbook without metadata.rb file FC032: Invalid notification timing FC033: Missing template FC034: Unused template variables FC037: Invalid notification action FC038: Invalid resource action FC039: Node method cannot be accessed with key FC042: Prefer include_recipe to require_recipe FC043: Prefer new notification syntax FC045: Metadata does not contain cookbook name FC046: Attribute assignment uses assign unless nil FC047: Attribute assignment does not specify precedence FC050: Name includes invalid characters FC051: Template partials loop indefinitely FC055: Ensure maintainer is set in metadata FC056: Ensure maintainer_email is set in metadata FC058: Library provider declares use_inline_resources and declares action_Disabling certain tags is useful on the command line, but what if you need to disable a tag or a particular rule for just a single part of a recipe? Foodcritic allows you to disable individual rules or tags using a special code comment.
Disabling FC033 for a single template resourcetemplate 'my_awesome_template' do # ~FC033 source 'path/to/template'end
Enabling and Disabling Tags Per Cookbook Foodcritic tags can be enabled or disabled by including a .foodcritic
file at the root of your cookbook directory. Within this file you can use tags or rules similar to how you would do on the command line.
To check rules with the style or services tag you would create a .foodcritic file containing style,services
. For example: $ echo "style,services" my_cookbook/.foodcritic
To disable just a single rule such as FC016 create a .foodcritic file containing ~FC016
. For example: $ echo "~FC016" my_cookbook/.foodcritic
Extra Rules
Awesome people have written additional rules that you can use with Foodcritic.
Sous Chefs Foodcritic Ruleshttps://github.com/sous-chefs/sc-foodcritic-rules
SC001 Missing Berksfile SC002 Missing CHANGELOG in markdown format SC004 Missing CODE_OF_CONDUCT in markdown format SC005 Missing CONTRIBUTING in markdown format SC014 metadata.rb should use sous-chefs style source_url SC015 metadata.rb should use sous-chefs style issues_url SC016 metadata.rb should use sous-chefs style maintainer SC017 metadata.rb should use sous-chefs style maintainer_email SC020 Missing .kitchen.yml SC021 Missing .travis.yml CustomInk Foodcritic Ruleshttps://github.com/customink-webops/foodcritic-rules
CINK001 Missing CHANGELOG in markdown format CINK002 Prefer single-quoted strings CINK003 Don't hardcode apache user or group Etsy Foodcritic Ruleshttps://github.com/etsy/foodcritic-rules
ETSY001 Package or yum_package resource used with :upgrade action ETSY004 Execute resource defined without conditional or action :nothing ETSY005 Action :restart sent to a core service ETSY006 Execute resource used to run chef-provided command ETSY007 Package or yum_package resource used to install core package without specific version number Lookout Foodcritic Ruleshttps://github.com/lookout/lookout-foodcritic-rules
LKOUT001 Include a chefspec test for every recipe LKOUT002 apt_repository should not download a key over plain http LKOUT003 specify a uid and gid when creating a user LKOUT004 specify a gid when creating a groupRule API Reference attribute_access
Find attributes accesses by type.
You might use this method to enforce local style rules on how attributesare accessed.
# All references to attributes using strings# For example: node['foo']attribute_access(ast, :type = :string)# All references to attributes using symbols# For example: node[:foo]attribute_access(ast, :type = :symbol)# All references to attributes using dots (vivified methods)# For example: node.fooattribute_access(ast, :type = :symbol)
Nokogiri::XML::Node
ast
The AST of the cookbook recipe to check
paramHash
options
The options hash (see allowed values below)
optionSymbol
:type
The approach used to access the attributes. One of :string
,:symbol
, :vivified
or :any
.
Boolean
:ignore_calls
Exclude attribute accesses that mix strings/symbols with dot notation.Defaults to false
.
Array
The matching nodes if any
chef_dsl_methodsThe set of methods in the Chef DSL.
You can use this to see if a method reference is part of the Chef DSL ordefined in a cookbook.
# Is search a method in the Chef DSL?chef_dsl_methods.include?(:search)= true
Array
Array of method symbols
cookbook_nameThe name of the cookbook containing the specified file.
You can use this method in rules that need to work out if recipe coderefers to the current cookbook: for example when looking atincluded_recipe
statements or LWRP usage.
cookbook_name('foo/recipes/default.rb')= "foo"
String
file
The file in the cookbook
returnString
The name of the containing cookbook
declared_dependenciesThe dependencies declared in cookbook metadata.
You can use this to check if all dependencies have been declaredcorrectly or to find all cookbooks that share a common dependency.
ast = read_ast('postgresql/metadata.rb')declared_dependencies(ast)= ["openssl"]
Nokogiri::XML::Node
ast
The metadata rb AST
returnArray
List of cookbooks depended on
fieldThe key / value pair in a ruby environment or role file.
# Retrieve the key and value of the 'name' fieldfield(ast, :name)
Nokogiri::XML::Node
ast
The environment or role AST
paramString
field_name
The name of the field to retrieve
returnNokogiri::XML::Node
The matched key / value pair
field_valueRetrieve the value from a ruby environment or role file.
# Retrieve the value of the 'name' fieldfield_value(ast, :name)
Nokogiri::XML::Node
ast
The environment or role AST
paramString
field_name
The name of the field to retrieve
returnString
The string value if specified as a literal.
file_matchCreate a match for a specified file. Use this if the presence of the filetriggers the warning rather than content.
This is an alternative to match
where you don’t have a specific ASTelement to associate the warning with. The call to file_match
willtypically be the last line in your rule.
file_match('foo/recipes/default.rb')= {:filename="foo/recipes/default.rb", :matched="foo/recipes/default.rb", :line=1, :column=1}
String
file
The filename to create a match for
returnHash
Hash with the match details
find_resourcesFind Chef resources of the specified type.
Note that currently this method does not return blockless resources.
# Returns all resources in the ASTfind_resources(ast)# Returns just the packagesfind_resources(ast, :type = :package)
Nokogiri::XML::Node
ast
The AST of the cookbook recipe to check
paramHash
options
The options hash (see allowed values below)
optionSymbol
:type
The type of resource to look for (or :any
for all resources)
Array
AST nodes of Chef resources.
included_recipesRetrieve the recipes that are included within the given recipe AST.
You can use this method to determine (and validate) recipe runtimedependencies.
# Find all include_recipe statements, discarding the AST nodes to just# show the recipe names.included_recipes(ast).keys= ["postgresql::client"]included_recipes(ast, :with_partial_names = false).keys= ["postgresql::client"]
Nokogiri::XML::Node
ast
The recipe AST
paramHash
options
:with_partial_names
- Include string literals for recipes thathave embedded sub-expressions. This defaults to true
for backwardcompatibility.
Hash
Hash keyed by included recipe name where the value is the AST nodeof the include_recipe
statement.
Searches performed by the specified recipe that are literal strings.Searches with a query formed from a subexpression will be ignored.
ast = read_ast('zenoss/recipes/server.rb')literal_searches(ast).size= 3
Nokogiri::XML::Node
ast
The AST of the cookbook recipe to check
returnArray
The matching nodes
matchCreate a match from the specified node.
Return matches when a rule has matched against a recipe. A call to match
is typically the last line of your rule.
Ensure that the AST node you are passing to this method has a descendantpos
node so that the match can be associated with a line in the file.
# You will frequently use map to apply the match function to an array of# nodes that you consider matches for your rule.attribute_access(ast, :type = :string).map{|s| match(s)}
Nokogiri::XML::Node
node
The node to create a match for
returnHash
Hash with the matched node name and position with the recipe
notificationsProvides convenient access to resource notification details.You can pass either the AST for an individual resource or the entirerecipe to this method. Note that a resource may be registered formultiple notifications / subscriptions.
While Chef permits either :immediate
or :immediately
to be specifiedin cookbooks, the timing for both will be returned as :immediate
toremove the need for callers to switch on both values.
find_resources(ast).select do |resource| notifications(resource).any? do |notification| ! [:delayed, :immediate].include? notification[:timing] endend
Nokogiri::XML::Node
ast
The AST to check for notifications.
returnArray
A flat array of notification hashes.
:type
- Either :notifies
or :subscribes
:resource_type
- The type of resource to be notified :resource_name
- The name of the resource to be notified. Thiscan be an AST if the resource name is not a string literal. :action
- The notification action :timing
- Either :delayed
or :immediate
:style
- The syntax used in the cookbook to define thenotification, either :old
or :new
os_command? Does the provided string look like an Operating System command? This is arough heuristic to be taken with a pinch of salt.
String
str
The string to check
returnBoolean
True if this string might be an OS command
read_astRead the AST for the given Ruby or erb source file.
Many of the other functions documented here take an ast
as an argument.You can also use Nokogiri’s support querying the AST with XPath or CSSto implement your own rules.
# Normally the recipe AST will be passed in to your rule without you# needing to use read_ast.# However if you need to you can read in the AST for a cookbook recipe# directly.ast = read_ast('apache2/recipes/default.rb')
String
file
The file to read
returnNokogiri::XML::Node
The recipe AST
resource_action?Determine if an action is valid for the given resource type.
resource_action?(:service, :restart)= true
Symbol
resource_type
The type of resource
paramSymbol
action
The name of the action
returnBoolean
True if the action is valid for this type of resource.
resource_attributeRetrieve a single-valued attribute from the specified resource.
# Given resource is a packageresource_attribute(resource, 'action')= :install
Nokogiri::XML::Node
resource
The resource AST to lookup the attribute under
paramString
name
The attribute name
returnString
The attribute value for the specified attribute
resource_attribute?Is the specified attribute valid for the type of resource? Note that thismethod will return true if the resource_type
is not recognised.
resource_attribute?(:file, :mode)= trueresource_attribute?(:file, :size)= false# If the resource is not a Chef built-in then the attribute is always# validresource_attribute?(:my_custom_resource, :whatever)= true
Symbol
resource_type
The type of Chef resource
paramSymbol
attribute_name
The attribute name
returnBoolean
True if the attribute is valid for this type of resource
resource_attributesRetrieve all attributes from the specified resource.
Use this method for convenient access to the resource attributes withoutneeding to query the AST.
resource_attributes(resource)= {:name="zenoss", "arch"="kernel", "action"=:install}
Nokogiri::XML::Node
resource
The resource AST
returnHash
The resource attributes
resource_attributes_by_typeRetrieve the attributes as a hash for all resources of a given type.
Use this if you want to compare the attributes and values used byresources of the same type.
# The values of the Hash (ignored here) are arrays of resource ASTs.resource_attributes_by_type(ast).keys.sort= ["apt_package", "apt_repository", "execute", "package", "ruby_block"]
Nokogiri::XML::Node
ast
The recipe AST
returnHash
Resources keyed by type, with an array for each
resource_nameRetrieve the name attribute associated with the specified resource.
resource_name(resource)= "zenoss"
Nokogiri::XML::Node
resource
The resource AST to lookup the name attribute under
returnString
The name attribute value
resource_typeReturn the type, e.g. ‘package’ of a given resource.
You could use this if you wanted to take different action in your rulebased on the resource type.
resource_type(resource)= "yum_package"
Nokogiri::XML::Node
resource
The resource AST
returnString
The type of resource
resources_by_typeRetrieve all resources of a given type.
The key of the hash is the type of resource (as a string). The value isan array of Hashes.
resources_by_type(ast).keys= ["yum_key", "yum_repository", "package", "service", "yum_package", "apt_repository", "apt_package"]
Nokogiri::XML::Node
ast
The recipe AST
returnHash
The matching resources
ruby_code?Does the provided string look like ruby code?This does not evaluate the expression, instead only checking that itappears syntactically valid.
You can use this method to check that ruby_block
resources and recipesthemselves look like Ruby code.
# Lots of strings are well-formed Ruby statements, including some strings# you might not expect:ruby_code?('System.out.println("hello world");')= true# This operating system command doesn't look like valid Ruby but others# might.ruby_code?('find -type f -print')= false
String
str
The string to check for rubiness
returnBoolean
True
if this string could be syntactically valid Ruby
Searches performed by the specified recipe.In contrast to literal_searches
this method returns all searches.
You could use this method to identify all searches that search for aparticular type of object, or to identify searches that are validfor a particular Chef version.
Nokogiri::XML::Node
ast
The AST of the cookbook recipe to check.
returnArray
The AST nodes in the recipe where searches are performed
standard_cookbook_subdirsThe list of standard cookbook sub-directories.
You can use this method when you need to traverse cookbooks manuallyyourself in order to determine directories to descend into.
standard_cookbook_subdirs= ["attributes", "definitions", "files", "libraries", "providers", "recipes", "resources", "templates"]
Array
The standard list of directories.
templates_includedList of templates that are included, including transitive includes.
templates_included(template_paths(filename), template_path)
Array
all_templates
The set of all templates
paramString
template_path
The path to look under
returnArray
The set of included templates
valid_query?Is this a valid Lucene query?
Use this method when acting on searches in a recipe in order to check thatthey are valid before continuing with the rest of your rule.
valid_query?('run_list:recipe[foo::bar]')= falsevalid_query?('run_list:recipe\[foo\:\:bar\]')= true
String
query
The query to check for syntax errors
returnBoolean
True
if the query is well-formed
TAGS:tool lint Foodcritic for cookbooks Chef your
<<< Thank you for your visit >>>
Websites to related : Free tube sex movies
keywords:
description:
Home Free tube sex movies
keywords:
description:
Menu
keywords:
description:
Korean Perfectionism Welcome to SsangYong Middle Eu
keywords:
description:
Français Trica Furniture The heart and soul of your home Trica Furniture The heart and soul o
keywords:
description:
INÍCIO I HABILITAÇÃO AMADOR I CURSOS APOSTILAS I CARTAS NÁUTICAS DIGITAIS I VELEIRO VADYO I SOBRE NÓS I MÍDIA I CONTATO
keywords:
description:Fort Dodge Trailer World, Trailers, aluminum, steel, cargo trailers, utility, enclosed, gooseneck trailers, carhaulers, motorcy
keywords:Lawrenceburg Speedway
description:Lawrenceburg Speedway
keywords:
description:
We are your one stop shop for vehicle graphics. We focus on one project at a time and a
keywords:
description:Model Railroad: All the information, tools and techniques you need to design and build your own realistic, artistic and operati
keywords:Paisley, Mod, Scooters, Paisley 2021, Abbey, Buddies, Coats, Mill, Thread History News, Gerry Rafferty, Music
description:Paisley Online is
Hot Websites