summaryrefslogtreecommitdiff
path: root/Jenkinsfile
blob: f7f3f28c3e7ebab2bdec88e9972212d19ac73e74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
pipeline {
    agent any

    environment {
        REGISTRY = 'registry.example.com/docker-images'
    }

    stages {
        stage('Detect changed images') {
            steps {
                script {
                    def base = env.CHANGE_TARGET ? "origin/${env.CHANGE_TARGET}" : "HEAD~1"
                    def changed = sh(
                        script: "git diff --name-only ${base} HEAD | cut -d/ -f1 | sort -u",
                        returnStdout: true
                    ).trim().split('\n')

                    // keep only dirs containing a Dockerfile
                    env.IMAGES_TO_BUILD = changed.findAll {
                        fileExists("${it}/Dockerfile")
                    }.join(',')
                }
            }
        }

        stage('Build & push') {
            when { expression { env.IMAGES_TO_BUILD } }
            steps {
                script {
                    def shortSha = env.GIT_COMMIT.take(8)
                    env.IMAGES_TO_BUILD.split(',').each { img ->
                        def tag = "${REGISTRY}/${img}"
                        sh """
                            docker build \
                              --label org.opencontainers.image.source=${env.GIT_URL} \
                              --label org.opencontainers.image.revision=${env.GIT_COMMIT} \
                              -t ${tag}:${shortSha} \
                              ${img}/
                        """
                        if (env.BRANCH_NAME == 'main') {
                            sh """
                                docker tag ${tag}:${shortSha} ${tag}:latest
                                docker push ${tag}:${shortSha}
                                docker push ${tag}:latest
                            """
                        }
                    }
                }
            }
        }
    }
}