chef recipe FileEdit insert_line_after_match and insert_line_if_no_match - ruby

I want to edit file using chef cookbook recipe.
The file appears now as,
[attribute1]
foo=bar
[attribute2]
....
I want to change it like:
[attribute1]
foo=bar
newfoo=newbar
[attribute2]
....
So basically, I want to add a line if it does not exist in the file and I want to add it after a particular line in that file.
I found 2 options under Class: Chef::Util::FileEdit which could be useful here insert_line_after_match and insert_line_if_no_match. But I want an option which can perform both of the actions. If I use insert_line_after_match, it works for first run but for next run it just keep adding lines even if line is already in the file. And insert_line_if_no_match adds line at the end of file if line does not exist in file but I want to add line after particular line in that file.
I am bit new to chef recipes. Is there any solution to solve above problem?

I would suggest not editing files, but rather overwriting them. You should create a template or a file inside the cookbook and then using template or cookbook_file resource overwrite the file on the machine with the one from cookbook.
Your config file looks similar to toml, so you can also use toml-rb gem to generate this file from json (data bag) or attributes like that:
chef_gem 'toml-rb' do
compile_time false
end
file '/path/to/file.conf' do
content( lazy do
require 'toml'
"# This file is managed by Chef\n" +
TOML.dump( my_json )
end )
end

Pretty please don't use FileEdit. It is an internal API and not intended for public use. What you want is the line cookbook, specifically the replace_or_add custom resource. Make sure you craft your regexp very carefully.
In general we do not recommend this kind of management style as it is very brittle and easily broken by unrelated changed. A better option is to use a template resource or similar to manage the whole file in a convergent manner.

Related

How check is my file create/modyfy after other file?

I need a function similar 'make' program.
If my file not exist or if file need update (modyfy time is before my other file) tell me true.
I have one file dependencies to other file. How update it only if neccesary.
You might want to use FileUtils.uptodate?.
uptodate?(new, old_list)`
Returns true if new is newer than all old_list. Non-existent files are older than any file.
In your example you can use it like this:
unless FileUtils.uptodate?('file_a', ['file_b'])
# file_a needs to be updated
end
require 'time_difference'
TimeDifference.between(File.ctime("FilenameA"), File.ctime("FilenameB.txt")).humanize
Using gem 'time_difference'
trouble with other lang than english (withouth .humanize You get number)

Fetch variable from yaml in puppet manifest

I'm doing one project for puppet, however currently stuck in one logic.
Thus, want to know can we fetch variable from .yaml, .json or plain text file in puppet manifest file.
For example,
My puppet manifest want to create user but the variable exist in the .yaml or any configuration file, hence need to fetch the varibale from the outside file. The puppet manifest also can do looping if it exist multiple users in .yaml file.
I read about hiera but let say we are not using hiera is there any possible way.
There are a number of ways you can do this using a combination of built-in and stdlib functions, at least for YAML and JSON.
Using the built-in file function and the parseyaml or parsejson stdlib functions:
Create a file at mymodule/files/myfile.yaml:
▶ cat files/myfile.yaml
---
foo: bar
Then in your manifests read it into a string and parse it:
$myhash = parseyaml(file('mymodule/myfile.yaml'))
notice($myhash)
That will output:
Notice: Scope(Class[mymodule]): {foo => bar}
Or, using the loadyaml or loadjson stdlib functions:
$myhash = loadyaml('/etc/puppet/data/myfile.yaml')
notice($myhash)
The problem with that approach is that you need to know the path to file on the Puppet master. Or, you could use a Puppet 6 deferred function and read the data from a file on the agent node.
(Whether or not you should do this is another matter entirely - hint: answer is you almost certainly should be using Hiera - but that isn't the question you asked.)

Edit json file using ansible

I am trying to edit a particular JSON file using Ansible. The file is present in remote servers which have to be logged in using LDAP authentication.
The file path is /etc/sensu/conf.d/client.json
and the line that I want to edit is as follows:
"subscriptions": ["Nginx", "Primus", "B2B", "Docker_Process_Check", "EBS", "base"],
I want to add one more value ("filebeat") in that line which after that should look like
"subscriptions": ["Nginx", "Primus", "B2B", "Docker_Process_Check", "EBS", "base","filebeat"],
AFAIK there's still no builtin module for JSON manipulation.
Either use 3rd-party module (like ghetto-json),
or make a complex regular expression with replace module (i.e. search for "subscriptions": [<...>] and place ,"filebeat" just before closing ]. You can use regex101.com to craft and test required expression.
Please also inspect this answer for additional info.

Run arbitrary ruby code in a chef cookbook

I have a simple chef cookbook and all it does is it sets the MOTD on a CentOS machine. It takes the content of the /tmp/mymotd.txt and turns it into the MOTD.
I also have a simple ruby script (a full-fledged ruby script) that simply reads the text from the web-server and puts in into the /tmp/mymotd.txt.
My questions are:
how do I run this ruby script from within the cookbook?
how do I pass some parameters to the script (e.g. the address of the web-server)
Thanks a lot beforehand.
Ad 1.
You can use libraries directory in scripts to place there your ruby script and declare it in a module. Example:
# includes
module MODULE_NAME
# here some code using your script
# Example function
def example_function (text)
# some code
end
end
You can use then
include MODULE_NAME
in your recipe to import those functions and just use it like
example_function(something)
What's good - you can use there also Chef functions and resources.
IMPORTANT INFO: Just remember that Chef has 2 compilation phases. First will be all of Ruby code, second all of Chef resources. This means, that you have to remember priority of code. I won't write here more info about it, since you haven't asked for this, but if you want, you can find it here.
Ad 2.
You can do this in several ways, but it seems to me, that the best option for you would be to use environments. You can find more info in here. Basically, you can set up environment for script before it will run - this way you can define some variables you would use later.
Hope this helps.

Unable to figure out ruby method "directory" and what it does

I am very new to ruby and was trying to understand some code when I got stuck at this snippet:
directory "test_dir" do
action :create
recursive true
end
I tried googling directory class but was unsuccessful. I found a class Dir but its not the same. I see that intuitively this snippet should create a new directory and name it test_dir but I do not want to assume things and move forward.
EDIT
This was a part of a chef-recipe which is used to launch a particular task. For the purposes of launching, it needs to create a directory and download some jars to it. There is an execute method below which goes like this:
execute 'deploy' do
action :nothing
# ignore exit status of storm kill command
command <<-EOH
set -e
storm kill #{name} -w 1 || true
sleep 3
storm jar #{points to the jar}
EOH
end
Sorry I have to be a bit obfuscated as some of the things are not open sourced.
It is the Directory resource of the Chef framework. (DSL stands for domain-specific language. Ruby is well suited for them.)
It's the Chef internal DSL for Directory management. Read more here: http://wiki.opscode.com/display/chef/Resources#Resources-Directory
PS: The recursive true tells it to create the folder much like mkdir -p.
The snippet you pasted is not really enough information to go on (need context; where is the snippet from?)
That said directory looks more like a method than a class. First, it's lowercased and classes are CamelCased.
If it's a method, it's defined somewhere within the application. Have you tried something like this:
grep -r "def directory" ./ or
grep -r "directory" ./| grep "def"
If not in the application itself, it would be defined in one of the application's dependencies (grep -r "..." $GEM_HOME/gems instead)
directory is not a class, it is a method. I do not know what module it is a part of, but that snippet is about equivalent to this:
Kernel.directory.call("test_dir",lambda {action :create; recursive true})
That snippet uses some gem that adds a directory method to the Kernel object.
As others have mentioned, it is part of the directory management DSL Chef. A DSL is a set of methods integrated into the Kernel object; because of the very flexible method calling syntax of Ruby, method calls can look a lot like language keywords. That makes task specific commands (Domain Specific Languages: DSL) look very nice in Ruby; easy to use and flexible. Thus gems that add DSLs are very common.

Resources