preface

The above mentioned mentioned how to install Jenkins on Docker, briefly introduced the use of Jenkins, and also demonstrated the assembly line Hello World. This article will demonstrate and explain some common syntax for pipelining. In order to be more relevant to the actual case, the grammar sample presented in this paper is illustrated with the grammar that may be used in the actual case.

Release Process Analysis

Springboot project release process

  1. Pull the code
  2. Compile the package
  3. Building a new image
  4. Push to a private repository
  5. Call publish command

Vue project release process

  1. Pull the code
  2. Packaging generates static resources
  3. Static resources are copied to a specified directory
  4. Call publish command

Case,

Simple assembly line instructions

pipeline {
    agent any
    // Define environment variables
    environment {
        ENV_A = "Hello World A"
        ENV_B = "Hello World B"
    }
    // Define the input parameter
    parameters {
    	string(name: 'app_name'.defaultValue: 'mldong-admin'.description: 'Application Name')}// Step definition
    stages {
        / / step one
        stage('step1') {
        	agent { 
                docker {
                	image 'maven:3-alpine'
                    args '-v /root/.m2:/root/.m2'
                }
            }
            steps {
                sh 'mvn --version'}}/ / in step 2
        stage('step2') {
            steps {
                sh "echo ${ENV_A}"
                sh "echo ${ENV_B}"
                sh "echo ${params.app_name}"}}/ / step 3
        stage('step3') {
            // Specify the runtime environment
            agent {
            	docker {
                    image 'node:10-alpine'
                    args '-p 3000:3000'
            	}
            }
            steps {
                sh 'node -v'}}}}Copy the code

You can select a successful pipeline for playback debugging

Copy the text, run it

If no local image is displayed for the first time, the system automatically downloads the image

Of course, we can also open Blue Ocean to see

Click for details

The environment variable

pipeline {
    agent any
    // Define environment variables
    environment {
        ENV_A = "Hello World A"
        ENV_B = "Hello World B"
    }
    stages {
        stage('step') {
            // Environment variable value ${XXX}
            steps {
                sh "echo ${ENV_A}"
                sh "echo ${ENV_B}"
                // Built-in environment variables
                sh "echo ${env.JOB_NAME}"}}}}Copy the code

There are many more built-in environment variables, which will not be listed here, but will be explained later. In addition to built-in variables and custom environment variables in the pipeline, it can also be configured globally. Here is a simple screenshot, not demo.

Jenkins-> System Administration -> System Configuration -> Environment Variables -> New

Into the reference configuration

Assembly line

Parameters {string(name: 'app_name', defaultValue: 'mldong-admin', description: 'Project name ') string(name: 'deploy_type', defaultValue: 'deploy', description:' build environment ') string(name: 'branch_name', defaultValue: 'master', description: 'git branch ') string(name: 'profile', defaultValue: 'test', description: 'Environment ')} stages {stage('step') {// ${params. XXX} steps {sh "echo ${params.app_name}" sh "echo ${params.deploy_type}" sh "echo ${params.branch_name}" sh "echo ${params.profile}" } } } }Copy the code

Build the project with parameters

The execution result

Documents management

In the last article, I tried credential configuration, which is used to configure connections to a K8S cluster. Here are some common credential configurations.

  • Username and password– Can be a separate field or a colon-delimited string:username:password
  • Secret File – Encrypted content saved in a file
  • SSH Username with private keySSH Public/private key pair.

Username and password

Jenkins-> System Administration ->Manage Credentials-> Global -> Add Credentials

For example, key_USR=> user name, key_PSW=> password

pipeline {
    agent any
    // Define the environment variable code block here
    environment {
        GITEE_CREDENTIALS = credentials('gitee-credentials')
	}
    stages{
        stage('step') {
            steps{
				sh "echo ${GITEE_CREDENTIALS_USR}"
				sh "echo ${GITEE_CREDENTIALS_PSW}"}}}}Copy the code

In logs, user names and passwords contain asterisks (*)

Secret file

This has been shown in the previous article, so I will not introduce it in screenshots.

SSH Username with private key

Jenkins-> System Administration ->Manage Credentials-> Global -> Add Credentials

ssh-keygen -t rsa -C "[email protected]" -f ~/.ssh/id_rsa
Copy the code

The preceding Private Key corresponds to cat ~/. SSH /id_rsa

Two usage scenarios are demonstrated here

Pull code using public key configuration

Here is the configuration mode of the code cloud: manage -> Public key management -> Add public key -> paste the id_RSA pair generated above to have id_RSA.pub

Assembly line

pipeline {
    agent any
    stages{
        stage('checkout') {
            steps{
            	checkout([$class: 'GitSCM'.branches: [[name: '*/master']], 
            	doGenerateSubmoduleConfigurations: false.            	extensions:[].            	submoduleCfg:[].                userRemoteConfigs: [[
                    credentialsId: 'mldong-gitbash'.                	url: '[email protected]:mldong/mldong.git']]])
                sh "pwd"
                sh "ls"}}}}Copy the code

The execution result

Run remote commands in public key mode

Configure the public key on the server where you want to execute the file remotely, create the file if it does not exist

vi ~/.ssh/authorized_keys
Copy the code

Pipeline – Executes remote commands and SCP

pipeline {
    agent any
    stages{
        stage('remote ssh') {
            steps {
            	withCredentials([
           	 	sshUserPrivateKey(
                    credentialsId: 'mldong-gitbash'.                    keyFileVariable: 'identity'.                    passphraseVariable: ' '.                    usernameVariable: 'userName')
            	]) {
              	sh "ssh -o StrictHostKeyChecking=no -i $identity [email protected] ls /"			  
              	sh "echo 666 > 666.txt"
              	scp -r -i $identity Awesome!txt $userName@www.mldong.com:/}}}}}Copy the code

Confirming the Host public KeyStrictHostKeyChecking

  1. StrictHostKeyChecking=noThe most insecure level, and certainly less annoying prompts, relatively secure IntranettestIs recommended. If the connection isserverIf the key does not exist locally, it is automatically added to the file (known_hosts by default) with a warning.
  2. StrictHostKeyChecking=askThe default level is the prompt that just appeared. If the connection does not match the key, a message is displayed and the login is denied.
  3. StrictHostKeyChecking=yesThe most secure level, if the connection does not match the key, the connection is rejected without prompting for details.

Add -o StrictHostKeyChecking=no. If StrictHostKeyChecking is not added, the following error occurs:

Host key verification failed.

The execution result

Using a script

Pipeline – Make some logical decisions on the script

pipeline {
    agent any
    // Enter the parameter definition
    parameters {
        string(name: 'v'.defaultValue: '3'.description: 'parameters')
    }
    stages {
        stage('step') {
            steps {
                script {
                	def a = "3";
                    def b = "4";
                    if ("${params.v}"= ="${a}"){
                    	sh "echo ${a}"
                    } else {
                        sh "echo ${b}"
                    }
                }
            }
        }
    }
}
Copy the code

The execution result

File stash stash/unstash stash

When we use different runtime environments on the same pipeline, and then need to pass the files or results from the previous runtime to the next runtime, we need to use stash/unstash, that is, temporary files and unstash files. The thing to note is that Stash packs the files into a tar package to urge, So large files consume CPU, and Stash has a file size limit of less than 100M. Such as:

Use maven environment to package springboot project and generate YAML distribution file, then pass yamL file to kubectl client environment to publish service.

Assembly line

pipeline {
    agent any
    // Step definition
    stages {
        stage('step1') {
        	// Specify the Maven runtime environment
        	agent { 
                docker {
                	image 'maven:3-alpine'
                    args '-v /root/.m2:/root/.m2'
                }
            }
            steps {
                sh 'mvn --version'
                sh "echo 666 > k8s.yaml"
                // Save the file temporarily
                stash name: "k8s.yaml".includes: "k8s.yaml"}}/ / in step 2
        stage('step2') {
            // Specify the node runtime environment
            agent {
            	docker {
                    image 'node:10-alpine'
                    args '-p 3000:3000'
            	}
            }
            steps {
                sh 'node -v'
                // Retrieve the file
                unstash("k8s.yaml")
                sh "cat k8s.yaml"}}}}Copy the code

The execution result

Pipeline notification

Assembly line – Success

pipeline{
    agent any
    stages{
        stage("CheckOut"){
            steps{
                script{
                    def branchName= "master"
                    println("${branchName}")
                }
            }
        }
    }
    post {
        always{
            script{
                println("always")
            }
        }
        success{
            script{
                println("success")
            }
        }
        failure{
            script{
                println("failure")
            }
        }
        
        aborted{
            script{
                println("aborted")}}}}Copy the code

The execution result

Pipeline-exception

pipeline{
    agent any
    stages{
        stage("CheckOut"){
            steps{
                script{
                   sh "cd 6666"
                }
            }
        }
    }
    post {
        always{
            script{
                println("always")
            }
        }
        success{
            script{
                println("success")
            }
        }
        failure{
            script{
                println("failure")
            }
        }
        
        aborted{
            script{
                println("aborted")}}}}Copy the code

The execution result

summary

This paper simply lists the examples that may be needed to do pipeline. although it is not complete, most pipelineproblems can be solved by using these and shell.

Related articles

Walk you through K8S – cluster creation and Hello World

Take you through K8S-ConfigMap and persistent storage

Take you hand in hand to play K8S – complete release of an externally accessible service

Docker-compose k8S-docker advanced Dockerfile and docker-compose

K8s – One click deployment of springboot project

Take you through k8S – One-click deployment of VUE projects

Take you hand in hand to play K8S – common object details

Walk you through k8S-Jenkins installation and assembly line