5

这里的情况是,我们有一个应用程序当前正在构建在 Jenkins 从站上,并在其上安装了某个版本的节点。我们想要标准化构建环境,因此想要在 docker 容器中构建。

通过我的研究,这绝对是可能的。然而,我们面临的挑战是我们想要使用我们自己管理并存储在 ECR 中的自定义图像。我们不想使用 docker hub 上的那些。考虑到这一限制,我正在努力在我的 Jenkinsfile 中对我们的 ECR 进行身份验证。理想情况下,我可以做这样的事情:

pipeline {
    agent {
        docker {
            image 'node:7'
            registryUrl 'ecr_url.amazonaws.com'
            registryCredentialsId 'ecr:us-east-1:iam_role'
        }
    }
    stages {
        stage('Build') {
            steps {
                sh 'command goes here'
            }
        }
    }
}

但这里的问题是我们的 ECR 登录依赖于在 Jenkins 工作人员(安装了 aws cli)上运行 shell 命令来登录和访问映像。到目前为止,我没有运气在 Jenkinsfile 中进行身份验证,因此我可以提取图像来运行构建。有谁知道这是否可行,如果可以,如何编辑 Jenkinsfile 来做到这一点?

4

2 回答 2

2

在从 ECR 提取图像之前,您需要授权令牌,这意味着您还需要在 Jenkins 服务器上安装 AWS-CLI。最好的方法是分配角色并在管道中的某处运行以下命令以获取授权令牌,如果这对您来说似乎很复杂,您可以使用下面的 ECR 插件。

您的 Docker 客户端必须以 AWS 用户身份向 Amazon ECR 注册表进行身份验证,然后才能推送和拉取映像。AWS CLI get-login 命令为您提供身份验证凭证以传递给 Docker。有关详细信息,请参阅注册表身份验证。

AmazonECR-registry_auth

所以你可以使用JENKINS/Amazon+ECR 在此处输入图像描述

Amazon ECR 插件实现了一个 Docker 令牌生成器,以将 Amazon 凭证转换为(大部分)所有 Docker 相关插件使用的 Jenkins 的 API。感谢这个制作人,您可以为 Jenkins 中的各种 Docker 操作选择您现有的已注册 Amazon 凭证,以使用 CloudBees Docker Build and Publish 插件进行示例:

通常我们使用这个命令来获取token。

$(aws ecr get-login --no-include-email --region us-west-2)

在管道中,您可以尝试

pipeline
{
    options
    {
        buildDiscarder(logRotator(numToKeepStr: '3'))
    }

    agent any
    environment 
    {
        PROJECT = 'tap_sample'
        ECRURL = 'http://999999999999.dkr.ecr.eu-central-1.amazonaws.com'
        ECRCRED = 'ecr:eu-central-1:tap_ecr'
    }
    stages
    {
        stage('Docker image pull')
        {
            steps
            {
                script
                {
                    sh("eval \$(aws ecr get-login --no-include-email | sed 's|https://||')")
                    docker.withRegistry(ECRURL, ECRCRED)
                    {
                        docker.image(PROJECT).pull()
                    }
                }
            }
        }
    }
}
于 2019-10-30T07:47:09.030 回答
1

You almost had it working. The trick to using it as an agent on the declarative pipeline is to create an AWS credential with empty Access_key and Secret but setting an IAM role on it. Jenkins credential

pipeline {
    agent {
        docker { 
          image '<account-id>.dkr.ecr.eu-west-1.amazonaws.com/image/my-image:v1'
          args '--entrypoint= '
          registryCredentialsId "ecr:eu-west-1:aws-instance-role"
          registryUrl "https://<account-id>.dkr.ecr.eu-west-1.amazonaws.com"
        }
    }
    stages {
        stage('Test') {
            steps {
                sh "I'm on an ECR agent"
            }
        }
    }
}

Make sure that you can assume this role, you can an instance role that allows assuming itself. I've created a medium post describing this process on a cross-account ECR How to run Jenkins agents with cross-account ECR images using instance roles on EKS.

于 2020-05-21T11:43:39.223 回答