You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jenkinsfile中添加ECR推送镜像的预部署扫描步骤?

在Jenkins流水线中添加ECR镜像扫描步骤

前置条件

  • Jenkins节点已安装AWS CLI v1.18.100+(旧版本不支持部分ECR扫描命令)
  • Jenkins中已配置具备以下权限的AWS凭证:
    • ecr:InitiateImageScan
    • ecr:DescribeImageScanFindings
    • ecr:GetAuthorizationToken
  • 已完成镜像构建并推送至ECR的流水线阶段(原有逻辑保留)

流水线具体实现步骤

1. 引入AWS凭证并触发扫描

在已有Jenkinsfile中新增扫描触发阶段,确保流水线能调用ECR API:

pipeline {
  agent any
  environment {
    ECR_REPO_NAME = "your-ecr-repo-name" // 替换为你的ECR仓库名
    IMAGE_TAG = "${BUILD_NUMBER}" // 或你实际使用的镜像标签规则
    AWS_REGION = "us-east-1" // 替换为ECR所在区域
  }
  stages {
    // 保留原有构建、推送镜像的阶段...
    
    stage('Trigger ECR Image Scan') {
      steps {
        withCredentials([usernamePassword(
          credentialsId: 'aws-ecr-credentials', // 替换为你的Jenkins凭证ID
          usernameVariable: 'AWS_ACCESS_KEY_ID',
          passwordVariable: 'AWS_SECRET_ACCESS_KEY'
        )]) {
          sh '''
            aws configure set aws_access_key_id ${AWS_ACCESS_KEY_ID}
            aws configure set aws_secret_access_key ${AWS_SECRET_ACCESS_KEY}
            aws configure set region ${AWS_REGION}
            
            // 触发镜像扫描
            aws ecr start-image-scan \
              --repository-name ${ECR_REPO_NAME} \
              --image-id imageTag=${IMAGE_TAG}
          '''
        }
      }
    }

2. 轮询扫描结果并校验漏洞等级

新增阶段等待扫描完成,根据漏洞严重程度决定是否继续部署:

stage('Validate Scan Results') {
      steps {
        withCredentials([usernamePassword(
          credentialsId: 'aws-ecr-credentials',
          usernameVariable: 'AWS_ACCESS_KEY_ID',
          passwordVariable: 'AWS_SECRET_ACCESS_KEY'
        )]) {
          script {
            def scanComplete = false
            def scanAttempts = 0
            def maxAttempts = 10 // 可根据镜像大小调整轮询次数
            def waitInterval = 60 // 每次轮询间隔秒数

            while (!scanComplete && scanAttempts < maxAttempts) {
              scanAttempts++
              sleep(waitInterval)

              // 获取扫描结果
              def scanOutput = sh(
                script: '''
                  aws ecr describe-image-scan-findings \
                    --repository-name ${ECR_REPO_NAME} \
                    --image-id imageTag=${IMAGE_TAG}
                ''',
                returnStdout: true
              ).trim()
              def scanData = readJSON text: scanOutput

              // 检查扫描状态
              if (scanData.imageScanStatus.status == 'COMPLETE') {
                scanComplete = true
                def criticalCount = scanData.imageScanFindings.findingSeverityCounts.CRITICAL ?: 0
                def highCount = scanData.imageScanFindings.findingSeverityCounts.HIGH ?: 0

                // 根据漏洞阈值判断是否终止流水线
                if (criticalCount > 0 || highCount > 0) {
                  error "镜像扫描发现 ${criticalCount} 个CRITICAL、${highCount} 个HIGH级漏洞,终止部署"
                } else {
                  echo "镜像扫描通过:CRITICAL漏洞 ${criticalCount} 个,HIGH漏洞 ${highCount} 个"
                }
              } else {
                echo "扫描进行中,已尝试 ${scanAttempts}/${maxAttempts} 次,等待 ${waitInterval} 秒..."
              }
            }

            if (!scanComplete) {
              error "镜像扫描超时,已尝试 ${maxAttempts} 次"
            }
          }
        }
      }
    }

    // 保留原有部署阶段(仅在扫描通过后执行)...
  }
}

自定义调整建议

  • 根据镜像大小修改maxAttempts和waitInterval,避免扫描超时误判
  • 可根据业务需求调整漏洞阈值(比如允许一定数量的HIGH级漏洞)
  • 若使用Jenkins AWS插件,可替换withCredentials部分为插件提供的awsCredentials步骤,简化配置

内容的提问来源于stack exchange,提问作者Ajmal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 00:10:12