Set environment variables in Jenkins Declarative Pipeline - jenkins-pipeline

Below is my code for deploy stage in jenkinsfile
stage('Deploy') {
node('slave1') {
if ("${env.Build_testapp1}" == 'true') {
script {
env.packageid = "Applications/testapp1/revesion1"
env.environmentId = "Environments/SysTest1/machine1"
}
xldDeploy serverCredentials: 'developer', environmentId: env.environmentId, packageId: env.packageid
}
but how I can make it variable as per environment?
I was looking for something like this
if ("${env.Build_EVN}" == 'dev'){
env.environmentId = "Environments/Dev/machine1"
}
if ("${env.Build_EVN}" == 'systest1'){
env.environmentId = "Environments/SysTest1/machine1"
}
then using "env.environmentId" in stage('Deploy')

You can add one more stage before Deploy to handle env.environmentId for subsequent stages to use.
stage('Prepare env') {
steps {
script {
if ("${env.Build_EVN}" == 'dev'){
env.environmentId = "Environments/Dev/machine1"
}
if ("${env.Build_EVN}" == 'systest1'){
env.environmentId = "Environments/SysTest1/machine1"
}
}
}
}
stage('Deploy') {
...
}

Related

For statement in jenkinsfile but using the variable for different stages

I have a list variable that i want to cycle over and i am able to do that but i can't seem to call it in my bat statement. Any idea how?
def birds = ["Parrot", "Cockatiel", "Pigeon"]
pipeline
{
agent any
stages
{
stage('Build Job1')
{
steps
{
script
{
for (int i = 0; i < birds.size(); ++i)
{
echo "Testing the ${birds[i]} browse"
bat 'echo ${birds[i]}'
}
}
}
}
stage ('Hello')
{
steps
{
script
{
for (int i = 0; i < birds.size(); ++i)
{
echo "Testing the ${birds[i]} browser"
}
}
}
}
}
}
Change the batch statements like below. Simply surround with double quotes.
bat "echo ${birds[i]}"

Shorten an || or if statement in Golang

Learning Golang and was wondering if there is a shorter way to write this
if tiletype == 0 || tiletype == 2 {
levelmap[passage1block] = "wall"
} else {
levelmap[passage1block] = "floor"
}
Was thinking this would be the way though it does not work
if tiletype ==0,2 {
levelmap[passage1block] = "wall"
} else {
levelmap[passage1block] = "floor"
}
You can write a switch-case statement:
switch tiletype {
case 0,2: levelmap[passage1block]="wall"
default: levelmap[passage1block]="floor"
}

JenkinsFile default workspace name is too long

I am currently setting up jenkins with bitbucket.
I have create a new jenkins project as multibranch project.
The JenkinsFile is hosted inside the git repository.
How can I force jenkins to generate a shorter branch name than the default one.
E:\jenkins\workspace\reposName-BrancheName-ZKIZ7BNGL6RTDKLQAQ7QR4FKZMOB3DDAVZ564BLWT2BY5ZV652VA
How can I get ride of ZKIZ7BNGL6RTDKLQAQ7QR4FKZMOB3DDAVZ564BLWT2BY5ZV652VA
This is my jenkinsFile
#!/usr/bin/env groovy
env.PATH = env.PATH + ";c:\\Windows\\System32"
def call(String label = null, Closure body) {
node(label) {
String path = pwd()
String branchName = env.BRANCH_NAME
if (branchName) {
path = path.split(Pattern.quote(File.separator))
def workspaceRoot = path[0..<-1].join(File.separator)
def currentWs = path[-1]
String newWorkspace = env.JOB_NAME.replace('/', '-')
newWorkspace = newWorkspace.replace(File.separator, '-')
newWorkspace = newWorkspace.replace('%2f', '-')
newWorkspace = newWorkspace.replace('%2F', '-')
if (currentWs =~ '#') {
newWorkspace = "${newWorkspace}#${currentWs.split('#')[-1]}"
}
path = "${workspaceRoot}${File.separator}${newWorkspace}"
}
ws(path) {
body()
}
}
}
pipeline
{
} // pipeline
Is there a way to force Jenkins to generate a shorter name?
You can change value of jenkins.branch.WorkspaceLocatorImpl.PATH_MAX=20 in jenkins's script console.
Changes will be lost if you restart jenkins server. To make the changes permanent, add this java property -Djenkins.branch.WorkspaceLocatorImpl.PATH_MAX=20
This is not the best way to fix it, but it is working :)
First create a method to get the current workspace and rework the final path like this:
def GetWorkspace()
{
node
{
String path = pwd()
String branchName = env.BRANCH_NAME
if(branchName)
{
path = path.split(Pattern.quote(File.separator))
def workspaceRoot = path[0..<-1].join(File.separator)
def currentWs = path[-1]
// Here is where we make branch names safe for directories -
// the most common bad character is '/' in 'feature/add_widget'
// which gets replaced with '%2f', so JOB_NAME will be
// ${PR}}OJECT_NAME}%2f${BRANCH_NAME}
String newWorkspace = env.JOB_NAME.replace('/', '-')
newWorkspace = newWorkspace.replace(File.separator, '-')
newWorkspace = newWorkspace.replace('%2f', '-')
newWorkspace = newWorkspace.replace('%2F', '-')
// Add on the '#n' suffix if it was there
if (currentWs =~ '#')
{
newWorkspace = "${newWorkspace}#${currentWs.split('#')[-1]}"
}
path = "E:\\Jenkins\\workspace\\${File.separator}${newWorkspace}"
}
return path
}
}
Then you have to set it up to our agent like this
pipeline {
environment {
//Your Env Setup
}
agent { //Global Agent.
node {
label 'AgentName'
customWorkspace GetWorkspace()
}
}

Cannot invoke 'SecPolicyCreateSSL' with an argument list of type '(Bool, String?)'

HTTPSecurity.swift:124:22: Cannot invoke 'SecPolicyCreateSSL' with an argument list of type '(Bool, String?)'
I'm getting the above error when trying to build a project containing this code:
public func isValid(trust: SecTrustRef, domain: String?) -> Bool {
var tries = 0
while(!self.isReady) {
usleep(1000)
tries += 1
if tries > 5 {
return false //doesn't appear it is going to ever be ready...
}
}
var policy: SecPolicyRef
if self.validatedDN {
policy = SecPolicyCreateSSL(true, domain)
} else {
policy = SecPolicyCreateBasicX509()
}
SecTrustSetPolicies(trust,policy)
if self.usePublicKeys {
if let keys = self.pubKeys {
var trustedCount = 0
let serverPubKeys = publicKeyChainForTrust(trust)
for serverKey in serverPubKeys as [AnyObject] {
for key in keys as [AnyObject] {
if serverKey.isEqual(key) {
trustedCount++
break
}
}
}
if trustedCount == serverPubKeys.count {
return true
}
}
} else if let certs = self.certificates {
let serverCerts = certificateChainForTrust(trust)
var collect = Array<SecCertificate>()
for cert in certs {
if let c = SecCertificateCreateWithData(nil,cert) {
collect.append(c)
}
}
SecTrustSetAnchorCertificates(trust,collect)
var result: SecTrustResultType = 0
SecTrustEvaluate(trust,&result)
let r = Int(result)
if r == kSecTrustResultUnspecified || r == kSecTrustResultProceed {
var trustedCount = 0
for serverCert in serverCerts {
for cert in certs {
if cert == serverCert {
trustedCount++
break
}
}
}
if trustedCount == serverCerts.count {
return true
}
}
}
return false
}
This code is from:
https://github.com/mpclarkson/SwiftHTTP/blob/swift-2/HTTPSecurity.swift#L124
Method using old fashion Boolean which is in fact UInt8. Method also use CFString and not String.
Easy solution is following:
policy = SecPolicyCreateSSL(1, domain as CFString)
More sophisticated solution is use extension for Bool:
extension Bool {
var booleanValue : Boolean {
return self ? 1 : 0
}
init(booleanValue : Boolean) {
self = booleanValue == 0 ? false : true
}
}
Then you can use:
policy = SecPolicyCreateSSL(true.booleanValue, domain as CFString)

Can I get gradle build to fail when there is version conflict between two dependencies when one of them doesn't have group specified

I am trying to figure out how to get gradle to fail a build on a version conflict between two dependencies when one of them doesn't have group specified.
For example I have a project that depends on jar from configured flat directory repository (for a vendor)
compile ':guava:r09'
and a transitive dependency that points to module retrieved from maven repository
compile 'com.google.guava:guava:13.0.1'
I understand that by design failOnVersionConflict resolution strategy will not raise a conflict for the above example. I cannot determine group name for jars in flat directory and hence would like to raise a conflict where developer can force one of the module accordingly. Thank you for taking the time to read by question.
Update:
Based on Ben's comment, I am attaching the code snippet used to raise custom conflict. But this is not helpful in my case since I cannot take advantage of force resolution strategy to resolve the conflict. I could exclude transitive dependencies or remove direct dependency altogether. Hopefully it is useful to someone else.
gradle.afterProject {
project.configurations.each { conf ->
def map = new HashMap<String, List<Dependency>>()
//println "\tConfiguration- ${project.name}:${conf.name}"
conf.allDependencies.each { dep ->
//println "\t\t${dep.group}:${dep.name}:${dep.version}"
ArrayList<Dependency> dependencies = null
if(map.containsKey(dep.name))
{
dependencies = map.get(dep.name)
}
else
{
dependencies = new ArrayList<>()
map.put(dep.name, dependencies)
dependencies.add(dep)
}
if(dep.group == null || dep.group.equals("unspecified"))
{
for(Dependency depInMap : dependencies) {
if(depInMap.version == null && dep.version == null)
continue;
if(depInMap.version != null && depInMap.version.equals(dep.version))
continue;
throw new GradleException("Customized Conflict: A conflict was found in " +
"${project.name}:${conf.name} between the following modules:" +
"\n- ${dep.group}:${dep.name}:${dep.version}" +
"\n- ${depInMap.group}:${depInMap.name}:${depInMap.version}")
}
}
dependencies.add(dep);
}
}
}
Here is solution I came up with. Given below is code snippet for some one else who may have use for it. The code isn't neat but is functional. Any suggestions are welcome.
private static boolean isGroupEmpty(DependencyResolveDetails details){
if (details.requested.group == null) {
return true;
} else if (details.requested.group == "unspecified"){
return true;
} else if(details.requested.group.isEmpty()) {
return true;
} else {
return false;
}
}
configurations.all {
def dependencyMap = [:]
def forcedModules = resolutionStrategy.forcedModules
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def targetToUse = null
for (forcedModule in forcedModules) {
if(forcedModule.name == details.requested.name &&
(forcedModule.group == details.requested.group || isGroupEmpty(details))) {
targetToUse = "${forcedModule.group}:${forcedModule.name}:${forcedModule.version}"
}
}
if(targetToUse != null) {
println "Forcing: " + targetToUse
details.useTarget targetToUse
}
else {
if(dependencyMap.containsKey(details.requested.name)) {
DependencyResolveDetails prevDetails = dependencyMap.get(details.requested.name);
boolean groupMatches = false
if(isGroupEmpty(prevDetails) || isGroupEmpty(details) ||
prevDetails.requested.group == details.requested.group){
groupMatches = true
}
if(groupMatches)
{
boolean versionMatches = false
if(prevDetails.requested.version == details.requested.version) {
versionMatches = true
}
if(!versionMatches)
{
//If versions don't match throw an exception.
throw new GradleException("Custom Conflict: A conflict was found in " +
"${project.name} between the following modules:" +
"\n- ${prevDetails.requested.group}:${prevDetails.requested.name}:" +
"${prevDetails.requested.version}" +
"\n- ${details.requested.group}:${details.requested.name}:" +
"${details.requested.version}")
}
else {
//Use either one (in this case I force the one with empty group)
DependencyResolveDetails repl
DependencyResolveDetails pref
if(isGroupEmpty(prevDetails)) {
pref = prevDetails
repl = details
}
else {
pref = details
repl = prevDetails
dependencyMap.put(details.requested.name, details)
}
repl.useTarget "unspecified:${pref.requested.name}:${pref.requested.version}"
println "Replacing module " +
"\n - ${repl.requested.group}:${repl.requested.name}:${repl.requested.version}" +
"\n with " +
"\n - ${pref.requested.group}:${pref.requested.name}:${pref.requested.version} ."
}
}
}
else {
dependencyMap.put(details.requested.name, details)
}
}
}
}

Resources