Chef user group permissions on subfolders - ruby

I am working trying to give user group permissions on subfolders in a Linux environment. In Linux that would be:
chown -R user:group /var/lib/temp/*
How can I acheive the same in Chef with Ruby? I have tried this:
directory '/opt/jenkins/plugins' do
owner 'jenkins'
group 'jenkins'
mode '0755'
recursive true
action :create
end
By specifying recursive it does not help.

From the chef docs:
recursive
Ruby Types: TrueClass, FalseClass
Create or delete parent directories recursively. For the owner, group, and mode properties, the value of this attribute applies only to the leaf directory. Default value: false.
User and group permissions won't recurse, you'll have to set them on each sub-directory manually.
You could make this slightly easier by doing something like the following:
plugins = %w(plugin1 plugin2)
plugins.each do |plugin|
directory "/opt/jenkins/plugins/#{plugin}" do
owner 'jenkins'
group 'jenkins'
mode '0755'
action :create
end
end

Related

chef guard only_if with '&&' not adhering to both statements

I have the below hash in a chef recipe, that creates a directory/s
node['fnb_base_directory']['directory_name'].map do |directory_name, dir|
next if directory_name.empty?
directory directory_name do
owner dir['owner']
group dir['group']
mode dir['mode']
recursive dir['recursive']
action dir['action']
only_if "getent passwd #{dir['owner']}" && "getent group #{dir['group']}"
end
end
I ONLY want chef to try create the directory based on this guard:
only_if "getent passwd #{dir['owner']}" && "getent group #{dir['group']}"
So that basically means that BOTH the user and the group must exist before trying to create the directory.
The problem appears to be that when chef interprets this, I see it is only adhering to ONE of the statements i.e. ONLY checks that group exists and then proceeds to attempt to create the directory, but will fail because the user does not exist yet.
See below interpretation:
directory("/opt/test_dir_creation") do
action [:create]
default_guard_interpreter :default
declared_type :directory
cookbook_name "fnb_base_wrapper"
recipe_name "fnb_base_directory"
recursive false
owner "nonexistent_user"
group "opc"
mode "0755"
only_if "getent group opc"
end
Failure:
directory[/opt/test_dir_creation] action create
* cannot determine user id for 'nonexistent_user', does the user exist on this system?
================================================================================
Error executing action `create` on resource 'directory[/opt/test_dir_creation]'
================================================================================
Chef::Exceptions::UserIDNotFound
--------------------------------
cannot determine user id for 'nonexistent_user', does the user exist on this system?
The reason the user does not exist yet, is because that user is created in another cookbook whose priority is not as high as our base cook (which creates directories), hence why the directory creation is done before the user is created.
The directory will then be created on the 2nd converge, where the user will then exist, and proceed to create the directory ONLY then.
FYI.
I am using getent because we use AD on our servers, so it may not always be a static user/group, but one that resides in AD.
I have also checked this question:
Using multiple conditions in Chef only_if guard
It does not help me.
Your help, guidance and advice will be greatly appreciated.
Try removing the quotes in the middle so the whole expression including the && condition runs in the shell.
only_if "getent passwd #{dir['owner']} && getent group #{dir['group']}"
Chef accepts a string shell command or a ruby block
only_if "some shell commands which are possibly in a pipeline return 0"
only_if {
return true if <condition1> && <condition2>
return true if <condition3> || <condition4>
return false
}

Execute instructions in chef recipes only for Test Kitchen converge action

I need a way to run parts of chef recipes only in case of converge action in Test Kitchen.
I found a way to do it for ChefSpec:
unless defined?(ChefSpec)
cookbook_file "/home/#{node['user']}/script.sh" do
source 'install.sh'
owner node['user']
mode '0755'
action :create
end
end
How I can do it for Kitchen tool?
This requirement has been discussed in detail on a feature request on Github.
There are two ways to do this. One is to define an environment variable such as TEST_KITCHEN, then use it in recipe with if condition, only_if or not_if guards.
Below should work:
Set the environment variable:
export TEST_KITCHEN="1"
Run the resource conditionally:
if ENV['TEST_KITCHEN']
cookbook_file "/home/#{node['user']}/script.sh" do
source 'install.sh'
owner node['user']
mode '0755'
action :create
end
end
Other way is to use a node attribute, something like node['test_kitchen'] set to true and use it to run actions conditionally.
cookbook_file "/home/#{node['user']}/script.sh" do
source 'install.sh'
owner node['user']
mode '0755'
action :create
only_if { node['test_kitchen'] }
end

How to do an "unless" conditional when changing permissions in a ruby_block in chef?

In chef I Have a ruby_block where I am changing permissions and ownership of a directory. How can I do a check where the permissions are only changed if they have not already been changed by the " FileUtils.chown" statement? I need to do this within the ruby_block if possible because i am ganna have other code in the ruby block. What would my "unless" statement be? Here is my code:
ruby_block 'exe' do
block do
FileUtils.chmod 0755, '/make/news'
FileUtils.chown('root', 'root', '/make/news')
end
end
The correct way to do this is to use Chef's file resource:
file '/make/news' do
mode 0755
owner 'root'
group 'root'
end
You're going down the road of trying to re-write the file resource which is not a good idea.
Using the Chef Resource's not_if Guard
Chef resources share a number of common functions. The ruby_block resource supports the not_if property as a conditional guard. The general format is:
ruby_block 'custom chmod' do
block do
#
end
not_if { true }
end
So, you could program your logic this way, but it will eventually bite you badly. Chef often works better if you use a file or directory resource declaratively using a separate block to manage permissions, and then (if necessary) chain it with a notification from some other block that needs a given permission set. For example:
directory '/make/news' do
mode '0755'
owner 'root'
group 'root'
action :nothing
end
ruby_block 'do something with news' do
block do
#
end
only_if { true }
notifies :create, 'directory[/make/news]', :before
end
That said, the goal of configuration management is to continuously converge, so I'd strongly question whether creating this interdependency between resource blocks is truly necessary in the first place. If possible, just converge your directory permissions every time to enforce them. While this may create a sequencing dependency within your recipe, a more declarative approach often simplifies cookbook and recipe debugging in the long run. Your individual mileage may vary.

Keeping files updated with a Chef recipe

The challenge prompt is above, and my latest attempt is below. The directories and files are created as expected, and the read-out after executing chef-apply multipleCopies.rb tells me the files are linked, but when I update any one of the files, the others do not follow suit. Any ideas? Here is my code:
for x in 1..3
directory "multipleCopy#{x}" do
mode '0755'
action :create
end
end
file "multipleCopy1/secret.txt" do
mode '0755'
action :create
end
for x in 2..3
link "multipleCopy#{x}/secret.txt" do
to "multipleCopy1/secret.txt"
link_type :hard
subscribes :reload, "multipleCopy1/secret.txt", :immediately
end
end
Note: For less headache, I am testing the recipe locally before uploading to the ubuntu server referenced in the prompt, which is why my file paths are different and why I have not yet included the ownership properties.
So a file hard link doesn't seem to be what the question is going for (though I would say your solution is maybe better since this is really not what Chef is for, more on that later). Instead they seem to want you to have three actually different files, but sync the contents.
So first the easy parts, creating the directories and the empty initial files. It's rare to see those for loops used in Ruby code, though it is syntactically valid:
3.times do |n|
directory "/var/save/multipleCopy#{n+1}" do
owner "ubuntu"
group "root"
mode "755"
end
file "/var/save/multipleCopy#{n+1}/secret.txt" do
owner "root
group "root"
mode "755"
end
end
But that doesn't implement the hard part of sync'ing the files. For that we need to first analyze the mtimes on the files and use the most recent as the file content to set.
latest_file = 3.times.sort_by { |n| ::File.mtime("/var/save/multipleCopy#{n+1}/secret.txt") rescue 0 }
latest_content = ::File.read("/var/save/multipleCopy#{latest_file+1}/secret.txt") rescue nil
and then in the file resource:
file "/var/save/multipleCopy#{n+1}/secret.txt" do
owner "root
group "root"
mode "755"
content latest_content
end
As for this not being a good use of Chef: Chef is about writing code which asserts the desired state of the machine. In the case of files like this, rather than doing this kind of funky stuff to check if a file has been edited, you would just say that Chef owns the file content for all three and if you want to update it, you do it via your cookbook (and then usually use a template or cookbook_file resource).

Removing boilerplate attributes from resources

In chef, each resource is defined like this:
directory "/home/akihiro/folder" do
owner "akihiro"
group "akihiro"
mode 0755
end
If this is the only task under akihiro's home directory, that's fine.
Unfortunately, I have to create directories, copy files, and apply templates, all under the same home directory as the owner. Therefore owner "akihiro"; group "akihiro" must be set on every resource, which is very redundant.
If the resource could be written like this,
directory "/home/akihiro/folder" do
as_akihiro
mode 0755
end
where as_akihiro is defined somewhere outside the resource, the recipe would get much clearer.
Is it possible to remove the boilerplate attributes by defining a new method?
You have a few options here.
Rubyish
You can create a Ruby module that defines this method:
module Impersonator
def as(person, perms = '0755')
send(:owner, person)
send(:group, person)
send(:mode, perms)
end
end
And then include this module in the resource:
Chef::Resource.send(:include, Impersonator)
And then use it:
directory '/foo/bar' do
as 'akihiro' # or as 'akihiro', '0644'
end
Chefish
If I understand your use case correct, the preferred way to handle this is with an LWRP (or HWRP). You indicated this process occurs multiple times and wraps core Chef resources. This is a great use case for an LWRP. Essentially you wrap and parameterize all of these resources into a single "wrapper".
# providers/default.rb
action :run do
user new_resource.username do
# ...
end
directory "/home/#{new_resource.username}" do
owner new_resource.username
group new_resource.group
mode new_resource.mode
end
# Other resources, using the `new_resource` object
end
And then in a Chef recipe, you would use this resource (assuming it is named "company_user"):
company_user 'akihiro'
That is possible. What works for me is to open the class that implements the "directory" resource, Chef::Resource::Directory and add a method as_akihiro. To do so, add a library to *your_cookbook*/libraries/as_user_helper.rb
class Chef::Resource::Directory
def as_akihiro()
owner "akihiro"
group "akihiro"
end
and you're done.

Resources