When I run the job I should create a freestyle job with a parameter name and repo.
I already try this but it doesn't work.
freeStyleJob('seed') {
parameters {
stringParam("GITHUB_REPO_NAME", "", "repo_name")
stringParam("JOB_NAME", "", "name for the job")
}
steps {
dsl {
job('\$DISPLAY_NAME') {
}
}
}
}
You can create a job inside a job by using 'text': https://jenkinsci.github.io/job-dsl-plugin/#path/freeStyleJob-steps-dsl-text
steps {
dsl {
text('job ("name") {}')
}
}
Here is the script that will help you out. It will create a Freestyle Job named example with Build Parameters JOB_NAME and GITLAB_REPOSITORY_URL. This job will have Job DSL Scripts.
freeStyleJob('example') {
logRotator(-1, 10)
parameters{
stringParam('JOB_NAME', '', 'Set the Gitlab repository URL')
stringParam('GITLAB_REPOSITORY_URL', '', 'Set the Gitlab repository URL')
}
steps {
dsl {
external('**/project.groovy')
}
}
}
In project.groovy, I have written my DSL scripts.
project.groovy
import hudson.model.*
def thr = Thread.currentThread()
def build = thr?.executable
def jobname_param = "JOB_NAME"
def resolver = build.buildVariableResolver
def jobname = 'TEST/'+ resolver.resolve(jobname_param)
println "found jobname: '${jobname}'"
def project_url_param = "GITLAB_REPOSITORY_URL"
def resolver2 = build.buildVariableResolver
def project_url = resolver2.resolve(project_url_param)
println "found project_url: '${project_url}'"
def repoUrl = "https://example.com/gitlab/repoA/jenkinsfile-repo.git"
pipelineJob(jobname) {
parameters {
stringParam('GITLAB_REPOSITORY_URL', '', 'Set the Gitlab repository URL')
}
logRotator {
numToKeep(5)
daysToKeep(5)
}
definition {
cpsScm {
scm {
git {
remote {
url(repoUrl)
credentials('gitlab-test')
}
branches('master')
extensions {
cleanBeforeCheckout()
}
}
}
scriptPath("Jenkinsfile")
}
}
}
For more reference:
https://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.DslFactory.freeStyleJob
https://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.helpers.step.StepContext.dsl
Related
I have this output.txt file:
cg-123456
cg-456789
cg-987654
cg-087431
Is it possible to get these values into a jenkins dropdown, like by using choice-parameter or active-choice-reactive parameter?
You can do something like the below.
pipeline {
agent any
stages {
stage ("Get Inputs") {
steps {
script{
script {
def input = input message: 'Please select the choice', ok: 'Ok',
parameters: [
choice(name: 'CHOICE', choices: getChoices(), description: 'Please select')]
}
}
}
}
}
}
def getChoices() {
filePath = "/path/to/file/output.txt"
def choices = []
def content = readFile(file: filePath)
for(def line : content.split('\n')) {
if(!line.allWhitespace){
choices.add(line.trim())
}
}
return choices
}
In my pipeline I have this:
steps {
script
{
def TAG_NAME = env.GIT_BRANCH.split("/")[1]
}
sshagent(credentials: ["<snip>"]) {
sh """
git tag -a "v.${TAG_NAME}.${env.BUILD_NUMBER}" -m "Add tag"
git push --tags
"""
}
}
But when this runs, I see that TAG_NAME is 'null.'
How do I make it so that I can see it in the sshagent.
A declarative pipeline example to set and get variables across the stages in a different ways .
def x
pipeline {
agent any;
stages {
stage('stage01') {
steps {
script {
x = 10
}
}
}
stage('stage02') {
steps {
sh "echo $x"
echo "${x}"
script {
println x
}
}
}
}
}
on your example, it could be
def TAG_NAME
pipeline {
agent any;
stages {
stage('stageName') {
steps {
script {
TAG_NAME = env.GIT_BRANCH.split("/")[1]
}
sshagent(credentials: ["<snip>"]) {
sh """
git tag -a "v.${TAG_NAME}.${env.BUILD_NUMBER}" -m "Add tag"
git push --tags
"""
}
}
}
}
}
I want use grrovy constant from Shared Libray in my Jenkins pipeline. I try this but I have this error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: WorkflowScript: 27: Not a valid stage section definition: "def paramChecker = ParameterChecker.new(this)". Some extra configuration is required. # line 27, column 9. stage('Checkout') {
def libIdentifier = "project-jenkins-pipeline"
def libGitBranch = params.LIB_GIT_BRANCH
if(libGitBranch) {
libIdentifier += "#${libGitBranch}"
}
def com = library(identifier: libIdentifier, changelog: false).com
def Constants = com.project.Constants
def ParameterChecker = com.project.ParameterChecker
pipeline {
agent {
docker {
label "linux"
image "my-host:8082/project-build-java:jdk1.6-jdk1.8-mvn3.2.5"
registryUrl 'http://my-host:8082'
registryCredentialsId 'ReadNexusAccountService'
}
}
stages {
stage('Clean workspace') {
steps {
deleteDir()
}
}
stage('Checkout') {
def paramChecker = ParameterChecker.new(this)
paramChecker.checkProjectAndBranchNames()
checkoutGitSCM(
url: "${Constants.BITBUCKET_URL}/${paramChecker.projectName}.git",
tag: Constants.GIT_PROJECT_DEFAULT_BRANCH
)
}
stage('Compilation Maven') {
steps {
timestamps {
sh 'mvn -version'
}
}
}
}
}
I had script in steps in stage('Checkout')
def libIdentifier = "project-jenkins-pipeline"
def libGitBranch = params.LIB_GIT_BRANCH
if(libGitBranch) {
libIdentifier += "#${libGitBranch}"
}
def com = library(identifier: libIdentifier, changelog: false).com
pipeline {
agent {
docker {
label "linux"
image "my-host:8082/project-build-java:jdk1.6-jdk1.8-mvn3.2.5"
registryUrl 'http://my-host:8082'
registryCredentialsId 'ReadNexusAccountService'
}
}
stages {
stage('Clean workspace') {
steps {
deleteDir()
}
}
stage('Checkout') {
steps {
script {
def Constants = com.project.Constants
def ParameterChecker = com.project.ParameterChecker
def paramChecker = ParameterChecker.new(this)
paramChecker.checkProjectAndBranchNames()
checkoutGitSCM(
url: "${Constants.BITBUCKET_URL}/${paramChecker.projectName}.git",
tag: Constants.GIT_PROJECT_DEFAULT_BRANCH
)
}
}
}
stage('Compilation Maven') {
steps {
timestamps {
sh 'mvn -version'
}
}
}
}
}
Thanks at #Matt Schuchard and Jenkins: Cannot define variable in pipeline stage
I've seen this example on how to load declarative piplines form a shared Library:
https://jenkins.io/doc/book/pipeline/shared-libraries/#defining-declarative-pipelines
But I would like to have the pipeline as inline functions:
def linux_platform = "U1604_x64_gcc54"
def windows_platform = "WIN10_x64_vc141"
properties(
[
parameters(
[
choice(name: 'platform', choices: [linux_platform, windows_platform], description: 'Platform'),
string(defaultValue: "-1", description: 'Upsteam Project build number', name: 'upsteam_project_build_number')
]
)
]
)
if(params.platform == windows_platform) {
windows(params.upsteam_project_build_number)
}
def windows(upsteam_project_build_number) {
pipeline {
agent {
label windows_platform
}
environment {
WINDOWS_ENV = "C:/my_path"
}
stages {
stage('Do stuff') {
steps{
echo "Doing stuff"
}
}
}
post {
failure {
job_status_mail(currentBuild.currentResult, JOB_NAME, BUILD_NUMBER, BUILD_URL)
}
fixed {
job_status_mail("fixed", JOB_NAME, BUILD_NUMBER, BUILD_URL)
}
}
}
}
Im getting the following error:
java.lang.NoSuchMethodError: No such DSL method 'agent' found among steps
Is my syntax some how wrong or is it not possible to load a pipeline from a inlne function?
I'm running:
Jenkins ver. 2.138.4
Declarative Pipeline Plugin ver. 1.3.8
I have many similar configs in declarative pipelines, like agent, tools, options, or post section. Is there any option to define those option somehow, so that an individual job has only to define the steps (which may come from a shared library)?
There is a description at "Defining a more stuctured DSL", where there is something similar to that what I want to achieve, but this seems to apply to scripted pipelines.
pipeline {
agent {
label 'somelabel'
}
tools {
jdk 'somejdk'
maven 'somemaven'
}
options {
timeout(time: 2, unit: 'HOURS')
}
stages {
stage('do something') {
steps {
doSomething()
}
}
}
post {
failure {
emailext body: '${DEFAULT_CONTENT}', subject: '${DEFAULT_SUBJECT}',
to: 'some#mail.com', recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider'], [$class: 'DevelopersRecipientProvider']]
}
}
}
Actually, I tried something like that, trying to pass a closure to the pipeline, but this does not seem to work. Probably if it worked, there was some documentation on how to do it.
def call(stageClosure) {
pipeline {
agent {
label 'somelabel'
}
tools {
jdk 'somejdk'
maven 'somemaven'
}
options {
timeout(time: 2, unit: 'HOURS')
}
stages {
stageClosure()
}
post {
failure {
emailext body: '${DEFAULT_CONTENT}', subject: '${DEFAULT_SUBJECT}',
to: 'some#mail.com', recipientProviders: [[$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider'], [$class: 'DevelopersRecipientProvider']]
}
}
}
}
and calling it somehow like this:
library 'my-library#master'
callJob{
stage('do something') {
steps {
doSomething()
}
}
}
I created a full flow
//SbtFlowDockerLarge.groovy
def call(int buildTimeout,String sbtVersion,List<String> fbGoals, List<String> masterGoals ){
def fbSbtGoals = fbGoals.join ' '
def masterSbtGoals = masterGoals.join ' '
pipeline {
agent { label DPgetLabelDockerLarge() }
options {
timestamps()
timeout(time: buildTimeout, unit: 'MINUTES')
disableConcurrentBuilds()
buildDiscarder(logRotator(daysToKeepStr: '35'))
}
stages {
stage('Prepare') {
steps {
setGitHubBuildStatus("Running Build", "PENDING")
echo "featureTask : ${fbSbtGoals}"
echo "masterTask : ${masterSbtGoals}"
}
}
stage('Build') {
when {
not { branch 'master' }
}
steps {
sbtTask tasks: "${fbSbtGoals}", sbtVersion: sbtVersion
}
}
stage('Deploy') {
when {
branch 'master'
}
environment {
TARGET_ENVIRONMENT='prod'
}
steps {
sbtTask tasks: "${masterSbtGoals}", sbtVersion: sbtVersion
}
}
}
post {
success {
setGitHubBuildStatus("Build complete", "SUCCESS")
}
failure {
setGitHubBuildStatus("Build complete", "FAILED")
}
always {
junit allowEmptyResults: true, testResults: '**/target/test-reports/*.xml'
dockerCleanup()
}
}
}
}
and here is the Jenkinsfile
#Library('aol-on-jenkins-lib') _
def buildTimeout = 60
def sbtVersion = 'sbt-0.13.11'
OathSbtFlowDockerLarge (buildTimeout, sbtVersion,['clean test-all'],['clean test-all publish'])