在Jenkins中构建Docker映像时如何传递AWS凭据?

luaexgnf  于 2023-03-17  发布在  Jenkins
关注(0)|答案(4)|浏览(182)

嗨,我在Jenkins工作,以建立我的AWS CDK项目。我已经创建了我的Docker文件如下。

FROM python:3.7.4-alpine3.10
ENV CDK_VERSION='1.14.0'

RUN mkdir /cdk

COPY ./requirements.txt /cdk/
COPY ./entrypoint.sh /usr/local/bin/
COPY ./aws /cdk/
WORKDIR /cdk

RUN apk -uv add --no-cache groff jq less
RUN apk add --update nodejs npm
RUN apk add --update bash && rm -rf /var/cache/apk/*
RUN npm install -g aws-cdk
RUN pip3 install -r requirements.txt

RUN ls -la
ENTRYPOINT ["entrypoint.sh"]

RUN cdk synth
RUN cdk deploy

在jenkins中,我构建了如下的Docker图像。

stages {
     stage('Dev Code Deploy') {
      when {
        expression {
          return BRANCH_NAME = 'Develop'
        }
      }
      agent {
        dockerfile {
          additionalBuildArgs "--build-arg 'http_proxy=${env.http_proxy}' --build-arg 'https_proxy=${env.https_proxy}'"
          filename 'Dockerfile'
          args '-u root:root'
        }
      }

在上面的代码中,我没有提供AWS凭据,因此当执行cdk synth时,我得到错误Need to perform AWS calls for account 1234567 but no credentials found. Tried: default credentials.
在Jenkins中,我有AWS凭据,可以像这样访问它

steps {
        withCredentials([[$class: 'AmazonWebServicesCredentialsBinding',credentialsId: "${env.PROJECT_ID}-aws-${env.ENVIRONMENT}"]]) {
           sh 'ls -la'
           sh "bash ./scripts/build.sh"
        }
      }

但是在建立 Docker 形象的时候,我怎样才能通过这些认证呢?有人能帮我解决吗?任何帮助都将不胜感激。谢谢

siv3szwd

siv3szwd1#

我可以通过下面这样的凭据。

steps {
        script {
          node {
            checkout scm
              withCredentials([[$class: 'AmazonWebServicesCredentialsBinding',credentialsId: "${env.PROJECT_ID}-aws-${CFN_ENVIRONMENT}"]]) {
                abc = docker.build('cdkimage', "--build-arg http_proxy=${env.http_proxy} --build-arg https_proxy=${env.https_proxy} .")
                abc.inside{
                sh 'ls -la'
                sh "bash ./scripts/build.sh"
              }
        }
        }
      }

我已经在www.example.com中添加了以下代码build.sh

cdk synth
cdk deploy
68de4m5k

68de4m5k2#

您应该安装“Amazon ECR”插件并重新启动Jenkins
用你的凭证完成插件。并在管道中指定
您可以在此处找到所有文档https://wiki.jenkins.io/display/JENKINS/Amazon+ECR

qnakjoqk

qnakjoqk3#

如果您使用Jenkins管道,也许您可以尝试AWS步骤。
这将提供一种访问Jenkins aws凭据的方法,然后在运行Docker容器时将凭据作为Docker环境传递。
参考:
https://github.com/jenkinsci/pipeline-aws-plugin
https://jenkins.io/doc/book/pipeline/docker/

06odsfpq

06odsfpq4#

1.创建您的访问密钥ID
1.添加withCredentials部分以在该环境中创建变量。

stage("Run process on image") {
        steps {
            withCredentials([aws(credentialsId: 'awscredentialId', accessKeyVariable: 'AWS_ACCESS_KEY_ID', secretKeyVarible: 'AWS_SECRET_ACCESS_KEY')]) {
                sh "docker-compose run -e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY " #complete the variables and command to execute and pass to docker
            }
        }
    }

相关问题