如何将docker image从jenkins推送到GCP artifact repo

yyhrrdl8  于 2023-08-03  发布在  Jenkins
关注(0)|答案(1)|浏览(146)

我想将Docker镜像从Jenkins(在同一个GCP项目上运行)推送到GCP Artifact Repo。我正在使用maven-jib插件来构建和推送图像。Maven-jib-plugin支持容器注册表(已弃用),但没有工件注册表的文档。
你能帮助我如何实现这一点吗?

2ledvvac

2ledvvac1#

基于Jenkins community

  • 为Artifact Registry创建一个服务帐户,并授予它Artifact Registry Writer IAM角色(roles/artifactregistry.writer)。
  • 创建服务帐户JSON键。
  • 将JSON密钥上传到Jenkins Manage Credentials as Secret File,并将其用作连接到Artifact Registry的凭据。

下面是一个要推送到Artifact Registry的jenkinsfile示例:

pipeline {
  environment {
    PROJECT = "you-gcp-project"
    APP_NAME = "you-app-name"
    REPO_NAME = "your-repo-name"
    REPO_LOCATION = "your-repo-location"
    IMAGE_NAME = "${REPO_LOCATION}-docker.pkg.dev/${PROJECT}/${REPO_NAME}/${APP_NAME}"
  }

  agent {
    kubernetes {
      yaml '''
        apiVersion: v1
        kind: Pod
        metadata:
          labels:
            app: test
        spec:
          containers:
          - name: docker
            image: gcr.io/cloud-builders/docker
            command:
            - cat
            tty: true
            volumeMounts:
            - mountPath: /var/run/docker.sock
              name: docker-sock
          - name: kubectl
            image: gcr.io/cloud-builders/kubectl
            command:
            - cat
            tty: true
          volumes:
          - name: docker-sock
            hostPath:
              path: /var/run/docker.sock
      '''
    }
  }
  
  stages {
    stage('Pull Git'){
      when { expression { true } }
      steps{
        checkout scm
      }
    }

    stage('Build docker image') {
    when { expression { true } }
      steps{
        container('docker'){
          dir('Backend Net/MyDotnet') {
            echo 'Build docker image Start'
            sh 'pwd'
            sh 'docker build -t ${IMAGE_NAME}:${IMAGE_TAG} .'
            withCredentials([file(credentialsId: "${PROJECT}_artifacts", variable: 'GCR_CRED')]){
              sh 'cat "${GCR_CRED}" | docker login -u _json_key_base64 --password-stdin https://"${REPO_LOCATION}"-docker.pkg.dev'
              sh 'docker push ${IMAGE_NAME}:${IMAGE_TAG}'
              sh 'docker logout https://"${REPO_LOCATION}"-docker.pkg.dev'
            }
            sh 'docker rmi ${IMAGE_NAME}:${IMAGE_TAG}'
            echo 'Build docker image Finish'
          }
        }
      }
    }
  }
}

字符串
您可以参考以下文件:

希望这对你有帮助。

相关问题