로컬 환경과 상용 서버에서 Kubernetes 클러스터에 접근하는 방법을 구분할 수 있어. 각각의 경우에 맞는 설정 방법을 정리해줄게.
로컬 환경에서 Docker Desktop의 Kubernetes 클러스터에 접근하려면 kubeconfig
파일을 사용해야 해. Jenkins 파이프라인에서 withCredentials
블록을 사용하여 kubeconfig
파일을 참조하도록 설정해.
pipeline {
agent any
stages {
stage('Checkout') {
steps {
git '<https://your-repository-url.git>'
}
}
stage('Build and Push Image') {
steps {
script {
sh './gradlew jib'
}
}
}
stage('Deploy to Kubernetes') {
steps {
script {
withCredentials([file(credentialsId: 'k8s-kubeconfig', variable: 'KUBECONFIG')]) {
sh 'kubectl apply -f k8s/spring-app-deployment.yaml'
}
}
}
}
}
post {
always {
cleanWs()
}
}
}
withCredentials
블록에서 설정한 KUBECONFIG
환경 변수는 Jenkins 파이프라인 내에서 해당 자격 증명 파일(kubeconfig
파일)의 경로를 가리키게 돼. kubectl
명령어는 이 환경 변수를 사용하여 Kubernetes 클러스터에 접근할 수 있어.
실제로 KUBECONFIG
변수 사용
KUBECONFIG
환경 변수는 kubectl
명령어가 Kubernetes 클러스터에 접근할 때 사용할 설정 파일을 지정하는 표준 방법이다. withCredentials
블록 안에서 KUBECONFIG
변수를 설정하면, 그 블록 내의 모든 명령어는 이 환경 변수를 참조하게 된다.stage('Deploy to Kubernetes') {
steps {
script {
withCredentials([file(credentialsId: 'k8s-kubeconfig', variable: 'KUBECONFIG')]) {
sh 'kubectl apply -f k8s/spring-app-deployment.yaml'
}
}
}
}
kubectl
명령어가 KUBECONFIG
를 사용하는 방법
withCredentials
블록 안에서 KUBECONFIG
환경 변수를 설정하면, 이 블록 내에서 실행되는 모든 명령어는 자동으로 이 환경 변수를 참조하게 된다.