build variable in jenkinsfile pipeline script for emailext - jenkins-plugins

I am trying to use build variable in presendScript of emailext in jenkinsfile pipeline script as below.
emailext body: "Pipeline error: Please go to ${BUILD_URL} and verify the build",
subject: "'${JOB_NAME}' (${BUILD_NUMBER}) failed",
presendScript: '''
logger.print(build.getEnvironment());
''',
to: 'my email address'
Getting following error, upon running the build.
java.lang.NullPointerException: Cannot invoke method getEnvironment()
on null object at
org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:91)
at
org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:48)
build variable is available when the same script is run as presendScript in freestyle project
I am not sure if I am not using build variable in appropriate context.

I'm not sure what you are trying to achieve.
If you want to add the environment to the body of the message, do the following:
sh echo "Pipeline error: Please go to ${BUILD_URL} and verify the build" > mail.txt
sh printenv >> mail.txt
emailext body: readFile 'mail.txt',
subject: "'${JOB_NAME}' (${BUILD_NUMBER}) failed",
to: 'your email address'
I'm not sure about the legacy Jenkins syntax; I'm more familiar with the declarative pipeline where you would do:
sh 'echo "Pipeline error: Please go to ${BUILD_URL} and verify the build" > mail.txt'
sh 'printenv >> mail.txt'
emailext (
body: readFile('mail.txt'),
subject: "'${JOB_NAME}' (${BUILD_NUMBER}) failed",
to: 'your email address'
)

Related

fatal: could not read Username for 'https://github.com': Invalid argument

I am trying to deploy my react app on git pages and i get the following error.
bash: /dev/tty: No such device or address
error: failed to execute prompt script (exit code 1)
fatal: could not read Username for 'https://github.com': Invalid argument
I tried to setting origin url with my username and password but that does not help.
Any pointer would be helpful.
It could be solved by adding user name in {project}/.git/config file. Just like this :
[remote "origin"]
url = http://<username>#<IP_address>/Shared/Infrastructure.git/
Please note the single quotation and remove <> in original command.
Alternatively, you should try to set global user name & pwd first

Unable to execute command with forward slash

I want to create a batch file to execute a set of Git commands to:
Fetch a new remote repository.
Create a local repository to track the remote and check the new local branch out.
Second Git command uses a forward slash (origin/[repositoryName]) and gives the following error:
"fatal: Missing branch name; try -b".
#ECHO OFF
SET /P branch = Enter remote branch name:
git fetch origin %branch%
git checkout --track origin/%branch%
First, git command fetches the remote repository.
Second git command gives error:
"fatal: "Missing branch name; try -b"
As mentioned in comments you should use the following piece of code:
#echo off
set /p "branch=Enter remote branch name: "
git fetch origin %branch%
git checkout --track origin/%branch%
which is slightly modified.
You don't need to scream in batch file :) it is a case insensitive language.
When you set variables don't add extra spaces around the =. Because then, interpreter interprets it as var<space> and <space>value.
Also, quote variable name and value in format like: set "var=value".

TFS Build providing prebuild auto increment assembly information by 1 and post publish zip the files

I am trying to implement Build automation using TFS (Version 12.0.31101.0)
This is the settings I am using, It build properly and publishes to the mentioned drop location:
For PreBuild I am trying to use the following batch script and this is not incrementing:
$path = "E:\Dev\ABC\My Project\AssemblyInfo.vb"
$pattern = '\<Assembly: AssemblyVersion\(.*\)\>'
(Get-Content $path) | ForEach-Object{
if($_ -match $pattern){
# We have found the matching line
# Edit the version number and put back.
$fileVersion = [version]$matches[1]
Write-Output "Major is $Matches[0] Minor is $Matches[1] Build is $Matches[2] Revision is [version]$matches[3]"
$newVersion = "{0}.{1}.{2}.{3}" -f $fileVersion.Major, $fileVersion.Minor, $fileVersion.Build, ($fileVersion.Revision + 1)
'<Assembly: AssemblyVersion("{0}")>' -f $newVersion
} else {
# Output line as is
$_
}
} | Set-Content $path
For 'post build script path' i want to zip the contents and put it into another folder, I am using the following script for this.
powershell.exe -nologo -noprofile -command "& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::CreateFromDirectory('\$(TF_BUILD_DROPLOCATION)\MySolution\_PublishedWebsites\ABC', 'ABC_Deploy.zip'); }"
On Executon it throws the following error:
Exception calling "CreateFromDirectory" with "2" argument(s): "Could not find
a part of the path 'C:\$TF_BUILD_DROPLOCATION\MySolution\_PublishedWebsites\ABC
At line:1 char:53
+ & { Add-Type -A 'System.IO.Compression.FileSystem';
[IO.Compression.ZipFile]::Cr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DirectoryNotFoundException
What changes should i make for both prebuild script and post build script to get this working?
For Prebuild:
Create a C# project(i used console project) which updates the assembly information..
Add RunScript to TFS build template before MSBuild.
Call the exe which is generated from c# project from your batch file, and pass the parameter as where your source code location.
Eg: (START "C:\UpdateAssemblyTest.exe" "\TFS-Server\TFSMapPath\ABC\")
PostBuild: I found a workaround for getting the TF_BUILD_DROPLOCATION. I modified the TFS Build Template and added a 'RunScript' tool and called my batch file from there and passed the drop location as an argument.
For 'Post Build Script' If build drop location is not accessible via the variable you are using; try using COPY command and copy the dropped folders to a known location on TFS Build server and then give that path in the ZIP Powershell command. (Though it is workaround for now. :) )
For 'Pre build Script', I will check and come back to you.
For 'post build script path', according to the Exception message it cannot identify the variable $TF_BUILD_DROPLOCATION.
As it's environment variable, So,please try to access the variables using $env:. The drop location would be
$env:TF_BUILD_DROPLOCATION for example.
For PreBuild, if you want to version the assemblies, you can try to put all custom Versioning work into a custom Version.proj MsBuild script and call it in TFS build definition before the .sln. The script injects Version into source code (SharedAssemblyInfo.cs, Wix code, readme.txt), and then solution build builds that source code. Please reference this thread :Versioning .NET builds
You can also reference this article :
https://www.stevefenton.co.uk/2012/11/automatically-updating-your-assemblyinfo-with-a-batch-file/

Get credentials in pipeline script

I'm using "Parameterized Build" and in particular "Credentials parameter"
In my Pipeline script how can I access to the username and password of TEST variable?
timeout(time: 5, unit: 'MINUTES') {
node('jenkins-slave1') {
....
sh 'echo ${TEST_USER}'
sh 'echo ${TEST_PASSWORD}'
}
}
I know that I can use inside the script
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: '5994c63b-ee86-4ef1-b28a-ee2236662226',
passwordVariable: 'TEST_PASSWORD',
usernameVariable: 'TEST_USER']]) {
sh "echo ${env.TEST_USER}"
sh "echo ${env.TEST_PASSWORD}"
}
but I need to provide this choice to the final user running the job
Thanks!
Riccardo

How to set the server variable on the fly using capistrano 3

we're trying to make our deployment scripts as generic as possible. Is it possible to have capistrano 3 prompt for the server address rather than setting it in the config files.
So far i have a capistrao task that does
namespace :config do
task :setup do
ask(:db_user, 'db_user')
ask(:db_pass, 'db_pass')
ask(:db_name, 'db_name')
ask(:db_host, 'db_host')
ask(:application, 'application')
ask(:web_server, 'server')
setup_config = <<-EOF
#{fetch(:rails_env)}:
adapter: postgresql
database: #{fetch(:db_name)}
username: #{fetch(:db_user)}
password: #{fetch(:db_pass)}
host: #{fetch(:db_host)}
EOF
on roles(:app) do
execute "mkdir -p #{shared_path}/config"
upload! StringIO.new(setup_config), "# {shared_path}/config/database.yml"
end
end
end
and in my production.rb file i have
set :application, "#{fetch(:application)}"
set :server_name, "#{fetch(:application)}.#{fetch(:server)}"
set :app_port, "80"
But when I do cap production config:setup to run the config script I get an error asking me for a password. If i hard code the server address in the production.rb file it works fine...how can I resolve this?
Thanks
I hope that someone else offers a more elegant solution, but if not:
I've done this in some cases with environment variables. If you want, you can also use a Makefile to simplify some of the env combinations.

Resources