Jenkins
02 / 03

Agents, Credentials & Docker

Jenkins: Agents, Credentials & Docker

Agents

// Top-level agent
pipeline {
    agent { label 'linux && docker' }   // run on agent with both labels
}

// Per-stage agent (overrides top-level)
stage('Build') {
    agent { label 'node-20' }
    steps { sh 'npm run build' }
}

// Docker agent — run inside container
stage('Test') {
    agent {
        docker {
            image 'node:20-alpine'
            args '-v /tmp:/tmp'
            reuseNode true            // reuse workspace from outer agent
        }
    }
    steps { sh 'npm test' }
}

// Kubernetes agent (Jenkins Kubernetes plugin)
agent {
    kubernetes {
        yaml """
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: node
    image: node:20
    command: ['cat']
    tty: true
"""
        defaultContainer 'node'
    }
}

// None — agents per stage
pipeline {
    agent none
    stages {
        stage('Build') { agent { label 'builder' }; steps { sh '...' } }
        stage('Test')  { agent { label 'tester'  }; steps { sh '...' } }
    }
}

Credentials

pipeline {
    environment {
        // Bind credential to env var (masked in logs)
        DOCKER_CREDS = credentials('docker-hub-credentials')  // username:password
        AWS_ACCESS_KEY_ID     = credentials('aws-access-key')
        AWS_SECRET_ACCESS_KEY = credentials('aws-secret-key')
    }

    stages {
        stage('Push Image') {
            steps {
                // DOCKER_CREDS_USR and DOCKER_CREDS_PSW are auto-set for username/password creds
                sh 'docker login -u $DOCKER_CREDS_USR -p $DOCKER_CREDS_PSW'
            }
        }

        stage('SSH Deploy') {
            steps {
                // SSH key credential
                sshagent(['my-server-ssh-key']) {
                    sh 'ssh user@server.example.com ./deploy.sh'
                    sh 'scp -r dist/ user@server.example.com:/var/www/app/'
                }
            }
        }

        stage('Use Secret File') {
            steps {
                withCredentials([file(credentialsId: 'gcp-service-account', variable: 'GCP_KEY')]) {
                    sh 'gcloud auth activate-service-account --key-file=$GCP_KEY'
                }
            }
        }
    }
}

Docker in Jenkins

pipeline {
    agent any

    stages {
        stage('Build Docker Image') {
            steps {
                script {
                    def image = docker.build("my-app:${env.BUILD_NUMBER}")

                    docker.withRegistry('https://registry.example.com', 'registry-credentials') {
                        image.push()
                        image.push('latest')
                    }
                }
            }
        }

        stage('Test in Docker') {
            steps {
                script {
                    docker.image('node:20-alpine').inside('-v $PWD:/app -w /app') {
                        sh 'npm ci && npm test'
                    }
                }
            }
        }
    }
}

// Multi-stage Docker build and scan
stage('Security Scan') {
    steps {
        sh 'docker scout cves my-app:${env.BUILD_NUMBER} --exit-code'
        sh 'trivy image --exit-code 1 --severity HIGH,CRITICAL my-app:${env.BUILD_NUMBER}'
    }
}

Parameters & Build Triggers

pipeline {
    parameters {
        string(name: 'VERSION', defaultValue: '', description: 'Version to deploy')
        choice(name: 'ENVIRONMENT', choices: ['staging', 'production'], description: 'Target env')
        booleanParam(name: 'SKIP_TESTS', defaultValue: false, description: 'Skip test suite')
        password(name: 'OVERRIDE_TOKEN', defaultValue: '', description: 'Override token')
    }

    stages {
        stage('Deploy') {
            when { not { expression { params.SKIP_TESTS } } }
            steps {
                echo "Deploying ${params.VERSION} to ${params.ENVIRONMENT}"
                sh "./deploy.sh ${params.ENVIRONMENT} ${params.VERSION}"
            }
        }
    }
}

// Trigger from upstream job
triggers {
    upstream(upstreamProjects: 'my-app/main', threshold: hudson.model.Result.SUCCESS)
}

// Webhook trigger (GitHub plugin)
triggers { githubPush() }

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free