freeleaps-ops/first-class-pipeline/src/com/freeleaps/devops/ImageBuilder.groovy

76 lines
3.1 KiB
Groovy
Raw Normal View History

package com.freeleaps.devops
import com.freeleaps.devops.enums.ImageBuilderTypes
class ImageBuilder {
def steps
def workspace
def contextRoot
def dockerfile
def builderType
ImageBuilder(steps, workspace, contextRoot, dockerfile, builderType) {
this.steps = steps
this.workspace = workspace
this.contextRoot = contextRoot
this.dockerfile = dockerfile
this.builderType = builderType
}
def build(name, repository, registry, architectures, version, registryCredentialsId) {
steps.log.info("ImageBuilder", "Building image with ${builderType.builder}")
steps.log.info("ImageBuilder", "Workspace sets to: ${workspace}")
steps.log.info("ImageBuilder", "Using dockerfile at: ${dockerfile}, context root sets to: ${contextRoot}")
if (architectures == null || architectures.isEmpty()) {
steps.log.warn("ImageBuilder", "No architectures specified, using default amd64")
architectures = ['linux/amd64']
}
steps.withCredentials([usernamePassword(credentialsId: registryCredentialsId, passwordVariable: 'DOCKER_PASSWORD', usernameVariable: 'DOCKER_USERNAME')]) {
steps.log.info("ImageBuilder", "Authentication to ${registry}")
switch(builderType) {
case ImageBuilderTypes.DOCKER_IN_DOCKER:
steps.sh "docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD} ${registry}"
break
case ImageBuilderTypes.KANIKO:
def auth = "${DOCKER_USERNAME}:${DOCKER_PASSWORD}".bytes.encodeBase64().toString()
steps.writeFile file: '/kaniko/.docker/config.json', text: """{
"auths": {
"${registry}": {
"auth": "${auth}"
}
}
}"""
break
default:
steps.error("Unsupported builder type: ${builderType.builder}")
}
}
switch(builderType) {
case ImageBuilderTypes.DOCKER_IN_DOCKER:
steps.dir(workspace) {
architectures.each { architecture ->
def archTag = architecture.split("/")[1]
steps.log.info("ImageBuilder", "Building image ${registry}/${repository}/${name} with architectures: ${architectures}, tag sets to ${version}-${archTag}")
steps.sh "docker build -t ${registry}/${repository}/${name}:${version}-${archTag} --platform ${architecture} -f ${dockerfile} ${contextRoot}"
steps.sh "docker push ${registry}/${repository}/${name}:${version}-${archTag}"
}
}
break
case ImageBuilderTypes.KANIKO:
steps.dir(workspace) {
architectures.each { architecture ->
def archTag = architecture.split("/")[1]
steps.log.info("ImageBuilder", "Building image ${registry}/${repository}/${name} with architectures: ${architectures}, tag sets to ${version}-${archTag}")
steps.sh "/kaniko/executor --log-format text --context ${contextRoot} --dockerfile ${dockerfile} --destination ${registry}/${repository}/${name}:${version}-${archTag} --custom-platform ${architecture}"
}
}
break
default:
steps.error("Unsupported builder type: ${builderType.builder}")
}
}
}