如何在代码构建中将命令的输出分配给变量 [英] How to assign output of a command to a variable in code build

查看:69
本文介绍了如何在代码构建中将命令的输出分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我推送源代码时,我都试图构建一个docker映像,并将该docker映像移至ECR(EC2容器注册表).

I am trying to build a docker image whenever there is push to my source code and move the docker image to the ECR( EC2 Container Registry).

我已经尝试使用以下构建规范文件

I have tried with the following build-spec file

    version: 0.2
env:
  variables:
    IMG: "app"
    REPO: "<<zzzzzzzz>>.dkr.ecr.us-east-1.amazonaws.com/app"      
phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws ecr get-login --region us-east-1
      - TAG=echo $CODEBUILD_RESOLVED_SOURCE_VERSION | head -c 8
  build:
    commands:
      - echo $TAG
      - docker build -t $IMG:$TAG .
      - docker tag $IMG:$TAG $REPO:$TAG 
  post_build:
    commands:
      - docker push $REPO:$TAG
      - printf Image":"%s:%s" $REPO $TAG > build.json
artifacts:
  files: build.json
  discard-paths: yes

构建此文件时,我在docker build -t

when I build this I am receiving the error invalid reference format at docker build -t

我查看了文档,但没有任何帮助.

I looked into the document and found no help.

推荐答案

因此,经过多次重试,我终于发现了自己的错误.

So after of lots of retries, i finally found my mistake.

Env CODEBUILD_RESOLVED_SOURCE_VERSION 应该替换为 CODEBUILD_SOURCE_VERSION 环境变量,因为我正在使用codebuild直接从GitHub的源仓库中构建.

Env CODEBUILD_RESOLVED_SOURCE_VERSION should be replaced with CODEBUILD_SOURCE_VERSION environment variable because I am using codebuild to build directly from source repo in GitHub.

要登录ecr,需要添加-no-include-email 选项,并用$()包裹命令.这将允许您运行docker login.我更新后的buildspec文件与下面类似

To log in to ecr, need to add --no-include-email option and wrap the command with $(). This will allow you to run docker login. My updated buildspec file would be similar below

version: 0.2
env:
  variables:
    REPO: "184665364105.dkr.ecr.us-east-1.amazonaws.com/app" 
phases:
  pre_build:
    commands:
      - echo $CODEBUILD_SOURCE_VERSION
      - TAG=$(echo $CODEBUILD_SOURCE_VERSION | head -c 8)
      - echo Logging in to Amazon ECR...
      - $(aws ecr get-login --no-include-email --region us-east-1)
  build:
    commands:
      - echo $TAG
      - echo $REPO
      - docker build --tag $REPO:$TAG .
  post_build:
    commands:
      - docker push $REPO:$TAG

这篇关于如何在代码构建中将命令的输出分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆