what is the right way to use if statement in chef? - if-statement

here the else part is not working I'm unable to figure out why , how do I execute this code successfully?
service 'McAfeeFramework' do
if{ supports :status =>true}
File.write('c:\chef-repo\n1.txt','running')
else
File.write('c:\chef-repo\n1.txt','not running')
end

As pointed out in your last question, what you have there is literally not related to Chef code. Please start with the https://learn.chef.io tutorials to learn the basics of writing Chef recipe code.

Here is a way to check if given process is running with chef. You need to replace procname with your process name. However this is example for Linux if you need Windows you need to change only_if statement to something like sc query | find "RUNNING
file 'running process' do
path '/tmp/running_process'
content 'services is running'
only_if 'pgrep procname && echo 0'
action :create
end
file 'stoped process' do
path '/tmp/stoped_process'
content 'services is not running'
only_if 'pgrep procname || echo 1'
action :create
end

Related

Extracting User Story from Commit Message in Jenkins

I'm using the ext-email extension to extract the User Story which is added as a commit message to include in the mail body.
This is the console output:
Commit message: "US285568"
I used the Build Log Excerpt method of the ext-email plug-in as follows:
STORY: ${BUILD_LOG_EXCERPT, start="Commit message:\ \"", end="\'"}
However, this does not match anything and I'm not able to understand why it's failing.
I couldn't find a proper documentation for this plug-in.
I used a work-around solution by triggering a helper job at the end of the current job (which contains the commit message in the console output).
I am executing the following shell code in the helper job:
result=$(curl -GET {JENKINS_IP}/jenkins/job/{UPSTREAM_JOB_NAME}/consoleFull --user "user:pass")
comm=$(grep "Commit message:" <<< "$result")
if grep -E "US[0-9]+" <<< "$comm"
then
final=$(grep -o "US[0-9]*" <<< "$comm")
else
final="<font color=\"red\">User Story not found</font>"
fi
echo FINAL=$final > env.properties
To access the FINAL variable (which contains the value of the user story) as an environment variable, I have used the EnvInject plug-in.
To access the FINAL variable outside the shell code in the job, add the "Inject environment variables" build step after the shell code and enter "env.properties" in the Properties File Path.

Perl - Regular expression yielding strange results

I am running a Perl script that runs a Linux system command, namely service --status-all in order to list services which have stopped and services which are currently running. The code that I am using runs the system command, and then chomps the input into an array. Followed by this the code is supposed to check if the service that the user promts for is running or has stopped, this is done using a regex that does yield the correct result. The problem lies in the additional information that the program lists, namely lines such as dnsdomainname: Unknown host and sometimes prints several lines of the same result.
The code that I am running is as follows:
use warnings;
use strict;
#Looping variables
my $service_query = 1;
#Command
my $command_3 = "service --status-all";
#Input variables
my $service = 0;
while ($service_query == 1){
print "Please choose the service that you wish to analyze (Named service):\n";
$service = <>;
if ($service =~ /^[a-zA-Z0-9.:_-]+$/)
{
$service_query = 0;
}
else
{
print "Argument not allowed.\n";
}
}
chomp(my #service_data_1 = qx/$command_3/);
chomp($service);
foreach my $line4(#service_data_1) #Filter output according to "$service".
{
if ($line4 =~ /$service\s\Spid\s[0-9]+\S\s(\S+)/)
{
print "1 $service is running\n";
}
elsif ($line4 =~ /$service\sis\s(\S+)/)
{
print "0 $service has stopped\n";
}
}
The system command yields results such as these:
sandbox is stopped
rpc.svcgssd is stopped
rpcbind (pid 1284) is running...
saslauthd is stopped
openssh-daemon (pid 1593) is running...
wpa_supplicant (pid 1444) is running...
What I want to be listed:
User inputs sandbox, program should print: 0 sandbox has stopped
What I actually get:
User inputs sandbox, program prints:
dnsdomainname: Unknown host
0 sandbox has stopped
I appreciate any help on the matter, thank you.
Most likely the service command clears the environment and does other things to ensure consistent results from what are essentially shell scripts n your service.d directory. In fact service itself may be a shell script (it usually was when I used Linux long ago). You can inspect it to help figure out why you are seeing dnsdomainname: Unknown host (it may be due to an environment variable like $HOSTNAME being cleared, or a missing name in /etc/hosts that normally wouldn't be an issue for the service command, for example).
Following on #choroba's query the output you see on your console when you run service --status-all in your shell might not be the same output you get from qx/ / in your perl script because of the way service itselfs handles STDOUT and STDERR.
From perdoc -f qx (cf. #TLP's remarks):
To read both a command's STDOUT and its STDERR separately, it's
easiest to redirect them separately to files, and then read from
those files when the program is done.
Another approach, if you are willing to use a CPAN module, is Capture::Tiny which is a great tool for grabbing what you want from perl code or external commands.

Manually specify location of .vagrant folder in Vagrantfile

The folder where I have Vagrantfile is being auto-generated during the build, so it gets cleaned up, but I'd like to still be able to use the created machines. The easiest way would be to put .vagrant folder somewhere outside the auto-generated folder. Is this possible?
You have (at least) two options:
Use VAGRANT_DOTFILE_PATH to set the the location where the project specific data is stored (defaults to .vagrant as you already know). Note that the path has to be project/Vagrantfile specific.
cd to a directory where you want the .vagrant directory to be created, and use VAGRANT_VAGRANTFILE to specify the path to the generated Vagrantfile.
I know this is an old question, but for anyone arriving here via Google, there is a workaround if you really want to specify the metadata directory without mucking about with environment variables each time. Just put this in the top of your Vagrantfile:
VAGRANT_DOTFILE_PATH = 'custom/dotfile/path'
if(ENV['VAGRANT_DOTFILE_PATH'].nil? && '.vagrant' != VAGRANT_DOTFILE_PATH)
puts 'changing metadata directory to ' + VAGRANT_DOTFILE_PATH
ENV['VAGRANT_DOTFILE_PATH'] = VAGRANT_DOTFILE_PATH
puts 'removing default metadata directory ' + FileUtils.rm_r('.vagrant').join("\n")
system 'vagrant ' + ARGV.join(' ')
ENV['VAGRANT_DOTFILE_PATH'] = nil #for good measure
abort 'Finished'
end
I wanted each provider to use a separate Vagrant directory to easily be able to swap between them. I could not get #hairraisin's solution to work, but based on that I ended up with the following:
Vagrant.configure('2') do |config|
config.vm.provider :lxd do |lxd, override|
if ENV['VAGRANT_DOTFILE_PATH'].nil?
ENV['VAGRANT_DOTFILE_PATH'] = '.vagrant-lxd'
puts 'Removing default metadata directory ' + FileUtils.rm_r('.vagrant').join("\n")
exec 'vagrant ' + ARGV.map{|arg| Shellwords.escape arg}.join(' ')
end
…
This avoids endless recursion or aborting too early. exec rather than system avoids a non-zero exit code from every vagrant command.

Windows Command Line Processor: Multiple and Nested IF Statements

Intended software: windows command line processor (version 6.1.7601.17514)
Hi,
I've been trying to build a multiple-statement command line that runs within a short-cut. My goal is to be able to click one short-cut that checks if my hosted network is started or not, and then takes appropriate action based on the check. The code that starts and stops the hosted network is fine, and for the most part, the logic works, but I notice odd behavior when I check the outputs of the logic. I suspect that my problem has to do with the way I structured the statements, but I'm having difficulty properly interpreting the built-in documentation and the documentation I can find in the MSDN library. If it's possible, I want to avoid using batch files for this solution.
To keep things simple, I've substituted my lengthy "netsh" commands with "echo" commands that show the errorcode. The code below is what I'm using to test my logic:
Test Code
netsh wlan show hostednetwork | find "Not" && echo found %errorlevel% || echo lost %errorlevel%
Currently, the way I'm reading this is:
Show me hostednetwork's status and send the output to input
Attempt to find the string "Not" in the input
If the attempt succeeds, output "found" and the errorcode to the screen
If the attempt fails, then output "lost" and the errorcode to the screen
Notice that I'm not using any flags on the find command. I'm doing this because I want to reduce the chance of finding a false match. To clarify what I mean, I'll show the output if I just put in
netsh wlan show hostednetwork:
Sample Output of Hostednetwork Status
C:\Windows\system32>netsh wlan show hostednetwork
Hosted network settings
-----------------------
Mode : Allowed
SSID name : "TestHost"
Max number of clients : 100
Authentication : WPA2-Personal
Cipher : CCMP
Hosted network status
---------------------
Status : Not started
If I search for the string "Not", then that's sufficient to tell me that the hosteadnetwork is not started, because when the hosteadnetwork is started, the output shows "Started".
The way I'm simulating the conditions of the hostednetwork is with the following commands:
netsh wlan start hostednetwork
netsh wlan stop hostednetwork
I expect that when I open a command prompt (as an administrator):
If the hostednetwork is not started, I should see a "found 0" in the output, meaning that the string was found and that there were no errors.
If the hostednetwork is started, I should see a "lost 1" in the output, meaning that the string was not found and that there was an error.
Case #1 works, but case #2 doesn't work on the first try. Here's my output when the hostednetwork is already started:
Output With Hostednetwork Started
C:\Windows\system32>netsh wlan start hostednetwork
The hosted network started.
C:\Windows\system32>netsh wlan show hostednetwork | find "Not" && echo found %er
rorlevel% || echo lost %errorlevel%
lost 0
C:\Windows\system32>netsh wlan show hostednetwork | find "Not" && echo found %er
rorlevel% || echo lost %errorlevel%
lost 1
Other Attempted Solutions
The way I've written the test code is the best I could come up with so far. In previous attempts, I've tried:
Setting a custom variable instead of using the errorlevel variable, but I get the same output on case #2.
Changing the code into an if else equivalent, but that didn't pan out very well.
Wrapping the conditional statements in brackets "()" after the pipe and using different combinations of the special symbols "&" and "|".
Other Questions
This question is related to another that I've been trying to figure out. If I wanted to search for three different strings in a command's output and exit on a different error code for each string, how can I do this? The syntax below is my starting point:
myCommand [/options] | ((find "string1" && exit /b 2 || ver>nul) &&
(find "string2" && exit /b 3 || ver>nul) && (find "string3" && exit /b 4 || ver>nul))
For the same reasons above, I didn't use any flags on the "find" commands. Also, I used "ver>nul" in an attempt to keep the syntax correct since I know the "ver" operation succeeds.
Any assistance is appreciated.
I don't understand why you want to avoid use of a batch script. Your shortcut can simply point to a small batch script, and life will be much easier.
But it is possible to do what you want. The value of %errolevel% is determined during parsing, and the entire shortcut is parsed in one pass, so you get the value that existed prior to execution of your FIND commands. You need delayed expansion !errorlevel! to get your desired results.
In batch you use setlocal enableDelayedExpansion, but that does not work from the command line (or a shortcut). Instead you must instantiate an extra CMD.EXE with the /V:ON option.
netsh wlan show hostednetwork | cmd /v:on /c "find "Not" && echo found !errorlevel! || echo lost !errorlevel!"
There are multiple levels of quoting going on, and that can sometimes cause problems. You can eliminate the quotes enclosing the command if you escape the special characters.
netsh wlan show hostednetwork | cmd /v:on /c find "Not" ^&^& echo found !errorlevel! ^|^| echo lost !errorlevel!
Regarding your 2nd question, I see 2 problems.
1) I don't understand the point of having a shortcut designed to exit with different error codes. How can you possibly make use of the returned error code?
2) You cannot pipe content into multiple FIND commands. The first FIND command will consume all the content and close the pipe, and then subsequent FIND commands will wait indefinitely for content from the keyboard.
You would have to redirect your command output to a temp file, and then redirect input of each FIND command to the temp file.
You cannot evaluate a variable in the same line. It needs delayed expansion and !errorlevel! to be used.
Do it in a batch file and you won't have a problem using delayed expansion.

Checking return value of a C++ executable through shell script

I am running a shell script on windows with cygwin in which I execute a program multiple times with different arguments each time. Sometimes, the program generates segmentation fault for some input arguments. I want to generate a text file in which the shell script can write for which of the inputs, the program failed. Basically I want to check return value of the program each time it runs. Here I am assuming that when program fails, it returns a different value from that when it succeeds. I am not sure about this. The executable is a C++ program.
Is it possible to do this? Please guide. If possible, please provide a code snippet for shell script.
Also, please tell what all values are returned.
My script is .sh file.
The return value of the last program that finished is available in the environment variable $?.
You can test the return value using shell's if command:
if program; then
echo Success
else
echo Fail
fi
or by using "and" or "or" lists to do extra commands only if yours succeeds or failed:
program && echo Success
program || echo Fail
Note that the test succeeds if the program returns 0 for success, which is slightly counterintuitive if you're used to C/C++ conditions succeeding for non-zero values.
if it is bat file you can use %ERRORLEVEL%
Assuming no significant spaces in your command line arguments:
cat <<'EOF' |
-V
-h
-:
-a whatnot peezat
!
while read args
do
if program $args
then : OK
else echo "!! FAIL !! ($?) $args" >> logfile
fi
done
This takes a but more effort (to be polite about it) if you must retain spaces. Well, a bit more effort; you probably use an eval in front of the 'program'.