我想将映像推送到 ECR,并获取扫描结果,如果发现严重漏洞则构建失败

问题描述 投票:0回答:1

最近,AWS 做出了一项更改,将 ECR 扫描结果委托给 AWS Inspector。这一变化破坏了我们构建 docker 镜像的 CI/CD 管道。

amazon-web-services jenkins-pipeline amazon-ecr
1个回答
0
投票

在经历了巨大的痛苦之后,我得到了这个脚本,希望它能起作用并且可以帮助其他人。 这个想法是让 CI/CD 推送新的 docker 镜像(存储库名称 + 标签)。 然后,代码使用 aws ecr describe-image-scan-findings 检查扫描状态,这可能会提前失败,因为扫描尚未开始,并且在检查器中找不到图像。 awsspector2 list-findings 将给出结果列表或空结果数组。在非空情况下,返回一个小的 json 结构,指示结果中列出的每种严重性类型的计数。

String scanFindings(String repositoryName, String imageTag) {
  withCredentials([[$class         : 'AmazonWebServicesCredentialsBinding',
                    credentialsId    : 'aws-nca',
                    accessKeyVariable: 'AWS_ACCESS_KEY_ID',
                    secretKeyVariable: 'AWS_SECRET_ACCESS_KEY']]) {
    def findingsSummary = sh(script: """
      REGION="us-east-2"
      while true; do
          SCAN_STATUS=\$(aws ecr describe-image-scan-findings \\
                        --repository-name ${repositoryName} \\
                        --region \$REGION \\
                        --query 'imageScanStatus.status' \\
                        --output text \\
                        --image-id imageTag=${imageTag} || echo "ERROR")
          if [ "\$SCAN_STATUS" = "ERROR" ] || [ -z "\$SCAN_STATUS" ] || [ "\$SCAN_STATUS" = "PENDING" ]; then
              sleep 10
              continue
          elif [ "\$SCAN_STATUS" = "COMPLETE" ]; then
              break
          elif [ "\$SCAN_STATUS" = "FAILED" ]; then
              echo "Scan has failed."
              exit 1
          fi
      done

      FINDINGS=\$(aws inspector2 list-findings --region \$REGION \\
          --filter '{
              "ecrImageTags": [
                  {
                      "comparison": "EQUALS",
                      "value": "'${imageTag}'"
                  }
              ],
              "ecrImageRepositoryName": [
                  {
                      "comparison": "EQUALS",
                      "value": "'${repositoryName}'"
                  }
              ]
          }' \\
          --output json)
      FINDINGS_COUNT=\$(echo \$FINDINGS | jq -r '.findings | length')
      if [ "\$FINDINGS_COUNT" -ne 0 ]; then
        echo "\$FINDINGS" | jq -Rs '. | fromjson | reduce .findings[] as \$item ({}; .[\$item.severity] += 1) | .'
      else
        echo "{}"
      fi
    """, returnStdout: true).trim()
    return findingsSummary
  } // with credentials
}
© www.soinside.com 2019 - 2024. All rights reserved.