Determine logged in user ID in Jenkins workflow - jenkins-workflow

Is there any way to determine the currently logged in user in workflow? In our traditional jobs we use Build User Vars Plugin but that doesn't appear to be available in workflow.

JENKINS-26953 tracks the integration.
In the meantime you could try
def cause = currentBuild.rawBuild.getCause(Cause.UserIdCause)
if (cause != null) {
def user = cause.userId ?: 'anonymous'
echo "started by ${user}"
} else {
echo "started some other way"
}
Note that this code will not work when run from the Groovy sandbox, as it accesses Jenkins APIs directly, so it is not suitable for a secured installation.

Related

How do I pass environment configuration like URLs to Flutter application using Jenkins?

I have a Jenkins job that builds my Flutter application based on different parameters like flavor (for different environments), backend URLs, etc. Right now in the build phase, I have a bash script that creates a new dart file based on my parameters and then Flutter uses that file as its environment configuration.
Future<void> main() async {
final config = {
'param1': Platform.environment['param1'],
};
final filename = 'lib/env.dart';
await File(filename)
.writeAsString('final environment = ${json.encode(config)};');
}
Is there a better way to send parameters like URLs from Jenkins to the Flutter application during the build process?
Maybe you must try pass your URLs with environments variables from jenkins to flask app.
In jenkins for example you can create a build stage like this
stage('Build') {
agent {
label 'master'
}
environment {
YOUR_URL = "https://example.com/api/v1"
}
steps {
script {
/* Some actions */
}
}
}
So, in your flask app only just missing get the env variables with any method like os.environ method like this example
import os
YOUR_URL = os.environ.get("YOUR_URL")

VSTS REST API for creating TFVC Branch

I am trying to automate some of my build related tasks, which includes creating new release branch and build definitions for each release. I use VSTS TFVC for version management. When i am trying to do it with TFS REST API, i couldn't find any API for creating branch (microsoft documentation).
I can see .NET API available to do this; unable to find one as REST API.
No such a REST API to create branch for now, I have submitted a user voice here to suggest the feature, you can go and vote it up to achieve that in future.
As a workaround you can try below ways to create a branch in code or script:
Just as #Shayki mentioned you can use Client Object Model Reference
if you want to manage the Version Control programmatically.
Just use the "CreateBranch()" method in
Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
class to create a branch.
Besides, you can also use the Branch Command to create a branch.
tf branch olditem newitem [/version:versionspec] [/noget] [/lock:(none|checkin|checkout)] [/noprompt] [/silent] [/checkin] [/comment:("comment"|#commentfile)] [/author:authorname] [/login:username, [password]] [/recursive]
Just as what you see in "Branches" page, there isn't any way to create branch with the Rest API. And mostly, you can only read/get the information with the Version Control API for now.
If you don't want use C#, you can automate the process with Powerhshell:
param(
)
begin
{
# load the required dll's
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.VersionControl.Client")
}
process
{
$server = New-Object Microsoft.TeamFoundation.Client.TeamFoundationServer("http://tfsserver:8080/tfs/DefaultCollection")
$vcServer = $server.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]);
$changesetId = $vcServer.CreateBranch('$/Demo/Code/Main', '$/Demo/Code/Dev/Branch', [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest, $null, "New branch from script", $null, $null, $null)
"Branch created with ChangesetID: $changesetId"
}

Retrieve custom variable from a successful jenkins job run via REST api call

I would like to retrieve a custom variable from a successful last stable build jenkins job. I was able to retrieve the build number using curl on this link using Execute Shell. It's an internal server. https://jenkinsci.internalsvr/view/webapps/job/common-tools/lastStableBuild/buildNumber
Now, I'd like to do the same for a custom variable using curl. But I know that I may need to save the value of the custom variable but not sure how and to where.
So this is how I got it to work
I have this code in our dsl.groovy file
....
parameters {
stringParam('CUSTOM_VAR1', '', 'Custom Variable')
stringParam('CUSTOM_VAR2', '', 'Custom Variable')
}
shellCommands = sprintf('''#/bin/bash
echo "CUSTOM_VAR1=\${%s}" > env.properties
echo "CUSTOM_VAR2=\${%s}" >> env.properties
''', ['CUSTOM_VARIABLE1','CUSTOM_VARIABLE1'])
shell(shellCommands)
// This is extremely important
environmentVariables {
propertiesFile('env.properties')
}
// This allowed me to retrieve env.properties via http call from browser or curl.
publishers {
archiveArtifacts {
pattern('env.properties')
}
}
So if I need to access it, the http url should be formed like this
curl https://our-internal-server/job/theNameOfTheJob/lastStableBuild/artifact/env.properties
You can do it with the API of the EnvInject plugin, either with:
curl <jenkins-host>/job/<job_name>/<buildNumber>/injectedEnvVars/export
curl <jenkins-host>/job/<job_name>/<buildNumber>/injectedEnvVars/api/python
More info here.

Generate jenkins jobs for all github repos

I would like to set up some automation inside Jenkins that periodically polls the list of repos in our github organization and automatically sets up a jenkins job for each of that Git repos based on a job template.
What would be a possible solution to achieve this? Thanks!
You can use the Jenkins Job DSL plugin
which is a build step in jobs to create and modify other jobs
From the Wiki:
The job-dsl-plugin allows the programmatic creation of projects using
a DSL. Pushing job creation into a script allows you to automate and
standardize your Jenkins installation, unlike anything possible
before.
An example would be:
def organization = 'jenkinsci'
repoApi = new URL("https://api.github.com/orgs/${organization}/repos")
repos = new groovy.json.JsonSlurper().parse(repoApi.newReader())
repos.each {
def repoName = it.name
job {
name "${organization}-${repoName}".replaceAll('/','-')
scm {
git("git://github.com/${organization}/${repoName}.git", "master")
}
}
}
Jenkins Pipeline is nowadays the way to go.
It defines pipelines using a Jenkinsfile, which you can check into your repos.
Which the best practice is a file like this
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building..'
}
}
stage('Test') {
steps {
echo 'Testing..'
}
}
stage('Deploy') {
steps {
echo 'Deploying....'
}
}
}
}
As described in the documentation.

How do I set up AD FS 2.0 with a SAML 1.1 profile using Powershell?

I’m working on a Windows 2008 R2 Enterprise server. I am trying to script the creation of a relying party trust for our production servers. I’ve written a powershell script. When I create the relying party trust manually, I selelct SAML 1.1 profile and everything works. When I create a script and use the powershell command Add-ADFSRelyingPartyTrust, it does not work the same and I get the following error:
The Federation Service could not authorize token issuance for caller 'xxxx\xxxxx
'. The caller is not authorized to request a token for the relying party 'https://example.com/forms/'. Please see event 501 with the same instance id for caller identity.
When I search on that error, it appears to me (though I could be wrong) that it’s a SAML 2.0 profile issue. But I need SAML 1.1.
Here is the code where I create the relying party trust:
Write-Host "Configuring relying party trust."
Add-ADFSRelyingPartyTrust -Identifier "$endpoint" -Name "$name" -WSFedEndpoint "$endpoint/" -SignatureAlgorithm "http://www.w3.org/2000/09/xmldsig#rsa-sha1"
Write-Host "Configuring rules."
$ruleSet = New-ADFSClaimRuleSet -ClaimRule 'c:[Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", Issuer == "AD AUTHORITY"] => issue(store = "Active Directory", types = ("http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname"), query = ";userPrincipalName,mail,givenName,sn;{0}", param = c.Value);'
Set-ADFSRelyingPartyTrust -TargetIdentifier "$endpoint" -IssuanceTransformRules $ruleSet.ClaimRulesString
Write-Host "Done."
When I do a GetADFSRelyingPartyTrust on the relying trust that works and compare it to the one the does not work, see a difference in the rule template:
Works:
IssuanceAuthorizationRules : #RuleTemplate = "AllowAllAuthzRule"
=> issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Val
ue = "true");
Doesn’t Work:
IssuanceAuthorizationRules :
Any ideas on how to get rid of the above error message?
By asking the question and providing the above information I found my own answer:
I needed to pass the -IssuanceAuthorizationRules parameter to the command.
-IssuanceAuthorizationRules '#RuleTemplate = "AllowAllAuthzRule" => issue(Type = "http://schemas.microsoft.com/authorization/claims/permit", Value = "true");'