cicd-java-spring-boot/Jenkinsfile
2023-02-02 12:13:01 +00:00

111 lines
4.1 KiB
Groovy

def label = "worker-${UUID.randomUUID().toString()}"
podTemplate(
label: label,
containers: [
containerTemplate(
name: 'gradle',
image: 'gradle:7.6.0-jdk11',
command: 'sleep',
args: '30d'
),
containerTemplate(
name: 'docker',
image: 'docker:latest',
command: 'cat',
ttyEnabled: true
),
containerTemplate(
name: 'kubectl',
image: 'bitnami/kubectl:latest',
command: 'cat',
ttyEnabled: true
),
containerTemplate(
name: 'helm',
image: 'alpine/helm:latest',
command: 'cat',
ttyEnabled: true
)
],
volumes: [
hostPathVolume(mountPath: '/home/gradle/.gradle', hostPath: '/tmp/jenkins/.gradle'),
hostPathVolume(mountPath: '/var/run/docker.sock', hostPath: '/var/run/docker.sock')
]
)
{
node(label) {
def myRepo = checkout scm
def gitCommit = myRepo.GIT_COMMIT
def gitBranch = myRepo.GIT_BRANCH
def shortGitCommit = "${gitCommit[0..10]}"
def previousGitCommit = sh(script: "git rev-parse ${gitCommit}~", returnStdout: true)
def dockerRegistryUrl = "harbor.loafle.net"
stage('Test') {
try {
container('gradle') {
def projectName = sh(returnStdout: true, script: "gradle -q projectName").trim()
def projectVersion = sh(returnStdout: true, script: "gradle -q projectVersion").trim()
env.PROJECT_NAME = projectName
env.PROJECT_VERSION = projectVersion
sh """
pwd
echo "GIT_BRANCH=${gitBranch}" >> /etc/environment
echo "GIT_COMMIT=${gitCommit}" >> /etc/environment
gradle test
"""
}
}
catch (exc) {
println "Failed to test - ${currentBuild.fullDisplayName}"
throw(exc)
}
}
stage('Build') {
container('gradle') {
sh "gradle build"
}
}
stage('Create Docker images') {
container('docker') {
withCredentials([[$class: 'UsernamePasswordMultiBinding',
credentialsId: 'harbor.loafle.net',
usernameVariable: 'HARBOR_USER',
passwordVariable: 'HARBOR_PASSWORD']]) {
env.CONTAINER_IMAGE_NAME = "prototype/"env.PROJECT_NAME
sh """
docker login -u "${HARBOR_USER}" -p "${HARBOR_PASSWORD}" ${dockerRegistryUrl}
docker build -t ${dockerRegistryUrl}/${env.CONTAINER_IMAGE_NAME}:${env.PROJECT_VERSION} --build-arg PROJECT_NAME=${env.PROJECT_NAME} --build-arg PROJECT_VERSION=${env.PROJECT_VERSION} .
docker push ${dockerRegistryUrl}/${env.CONTAINER_IMAGE_NAME}:${env.PROJECT_VERSION}
"""
}
}
}
stage('Deploy Application on K8s') {
container('kubectl') {
withKubeConfig([
credentialsId: 'microk8s-cluster',
serverUrl: env.K8s_SERVER_URL,
contextName: env.K8s_CONTEXT_NAME,
clusterName: env.K8s_CLUSTER_NAME]) {
println "CONTAINER_IMAGE_NAME - ${env.CONTAINER_IMAGE_NAME}"
// sh """
// DEPLOY_DATE=$(date +"%Y-%m-%d %H:%M:%S")
// sed -i.bak 's#__REGISTRY_URL__#'"${dockerRegistryUrl}"'#' ./.k8s/deployment.yaml
// sed -i.bak 's#__IMAGE_NAME__#'"${env.CONTAINER_IMAGE_NAME}"'#' ./.k8s/deployment.yaml
// sed -i.bak 's#__IMAGE_TAG__#'"${env.PROJECT_VERSION}"'#' ./.k8s/deployment.yaml
// sed -i.bak 's#__DEPLOY_DATE__#'"${DEPLOY_DATE}"'#' ./.k8s/deployment.yaml
// kubectl apply -f ./.k8s/deployment.yaml
// """
}
}
}
}
}