All of these examples were tested with the ‘Multibranch Pipeline’ type jobs. This may not work with other types of jobs in Jenkins.

Validate Jenkinsfile for syntax

Navigate to the directory which has the Jenkinsfile file. You’ll need the Jenkins host URL, username/password of your Jenkins host.

curl --user username:password -X POST -F "jenkinsfile=<Jenkinsfile" http://jenkins.example.com/pipeline-model-converter/validate

Conditional credential variable based on the branch name

If you have different credential names per environment (you should!), you can declare it at the top of the Jenkinsfile and use them in any step.

// define an environment variable that contains the credential name based on the branch name
def PASSWORD_ENV = env.BRANCH_NAME == 'master' ? 'PROD_PASSWORD' : 'DEV_PASSWORD'

pipeline {
     stages {
         stage('Deploy') {
             environment {
                 PASSWORD = credentials("${PASSWORD_ENV}")
             }
             steps {
                 sh './deploy.sh ${PASSWORD}'
             }
          }
     }
 }

Get output of script and store in an environment variable

If you need to create a variable which is the output of a shell command, use the sh command with returnStdout: true.

pipeline {
     environment {
           TEST_DATABASE_NAME = """${sh(
                   returnStdout: true,
                   script: "echo \"test_database_\" + ${env.BRANCH_NAME} | tr -cd '[:alnum:]_' | head -c 64 | tr '[:upper:]' '[:lower:]'"
               )}""".trim()
     }
     stages {  
         stage('Run tests') {
             steps {
                  withCredentials([string(credentialsId: 'MYSQL_TEST_PASSWORD', variable: 'MYSQL_TEST_PASSWORD')]) {
                     sh '''
                          echo "Will be using ${TEST_DATABASE_NAME} for tests"
                          mysql -u test_username -p${MYSQL_TEST_PASSWORD} -e "DROP DATABASE IF EXISTS ${TEST_DATABASE_NAME}; CREATE DATABASE ${TEST_DATABASE_NAME}";
                        MYSQL_TEST_PASSWORD=${MYSQL_TEST_PASSWORD} TEST_DATABASE_NAME=${TEST_DATABASE_NAME} ./vendor/bin/phpunit
                        mysql -u test_username -p${MYSQL_TEST_PASSWORD} -e "DROP DATABASE IF EXISTS ${TEST_DATABASE_NAME};";

                     '''
                  }
              }
         }     
     }

Run a stage only on specific branches

If you want to run deployment only on builds from specific branches, eg. master and integration:

stage('Deploy') {
    when {
        anyOf {
            branch 'master'
            branch 'integration'
        }
    }
    steps {
        sh './deploy.sh'
    }
}

Disable Concurrent/Parallel builds of the same branch

pipeline {
     options {
        disableConcurrentBuilds()
     }
}

Leave a Reply

Your email address will not be published. Required fields are marked *