Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Build & Cache multi-stage Docker images (with Build Specification for AWS CodeBuild)
# the general idea
ImageTag="git"
FilePath="/Dockerfile"
RepoURI="123456789012.dkr.ecr.eu-west-1.amazonaws.com/repo"
Stages=$(cat $FilePath | grep -oP '^FROM .+ (AS|as) \K(.+)$')
CacheArgs=$(for Stage in $Stages; do echo "--cache-from $RepoURI:cache-$Stage"; done | paste -sd ' ')
BuildArgs="--file $FilePath $CacheArgs"
for Stage in $Stages; do docker pull $RepoURI:cache-$Stage || true; done
for Stage in $Stages; do docker build $BuildArgs --tag $RepoURI:cache-$Stage --target $Stage . || break; done
docker build $BuildArgs --tag $RepoURI:$ImageTag .
docker push $RepoURI:$ImageTag
docker tag $RepoURI:$ImageTag $RepoURI:latest
docker push $RepoURI:latest
for Stage in $Stages; do docker push $RepoURI:cache-$Stage || true; done
version: 0.2
phases:
pre_build:
commands:
- ImageTag=$(echo $CODEBUILD_BUILD_ID | sed 's/[^A-Za-z0-9]/-/g')
- Stages=$(cat $FilePath | grep -oP '^FROM .+ (AS|as) \K(.+)$')
- CacheArgs=$(for Stage in $Stages; do echo "--cache-from $RepoURI:cache-$Stage"; done | paste -sd ' ')
- BuildArgs="--file $FilePath $CacheArgs"
- $(aws ecr get-login --no-include-email)
- for Stage in $Stages; do docker pull $RepoURI:cache-$Stage || true; done
build:
commands:
- for Stage in $Stages; do docker build $BuildArgs --tag $RepoURI:cache-$Stage --target $Stage . || break; done
- docker build $BuildArgs --tag $RepoURI:$ImageTag .
- docker tag $RepoURI:$ImageTag $RepoURI:latest
post_build:
commands:
- |
if [ $CODEBUILD_BUILD_SUCCEEDING = 1 ]; then
docker push $RepoURI:$ImageTag
docker push $RepoURI:latest
for Stage in $Stages; do docker push $RepoURI:cache-$Stage || true; done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.