Skip to content

Instantly share code, notes, and snippets.

@MeirP-3
Last active May 29, 2024 09:04
Show Gist options
  • Save MeirP-3/33b938d6b70232eb58bb7a938e6defc5 to your computer and use it in GitHub Desktop.
Save MeirP-3/33b938d6b70232eb58bb7a938e6defc5 to your computer and use it in GitHub Desktop.
Use kubectl to build and push docker image to ECR
#!/bin/bash
# Build and push a docker image to ECR, with an ad-hoc pod running in kubernetes. no need for local docker installation.
# Prerequisites:
# - tar, gzip, kubectl, aws cli
# - kubectl access to kubernetes cluster
# - aws cli with access to ECR
# Caveats:
# - Files or folders starting with '.' (except for `.dockerignore`) will not be included in the build context to avoid problems with .git, .venv, .env, etc.
# Usage:
# ./build-and-push.sh <registry>/<image>:<tag> <path-to-dockerfile> <path-to-context>
# example:
# ./build-and-push.sh xxxxxxxxxxxx.dkr.ecr.us-east-1.amazonaws.com/my-image:1.2.3 ./Dockerfile .
set -eo pipefail
IMAGE=${1?:"first argument must be in the form of <registry>/<image> or <registry>/<image>:<tag>"}
DOCKERFILE=${2?:"second argument must be the path to the dockerfile"}
CONTEXT=${3?:"third argument must be the path to the context. for example: '.'"}
# extract aws region from registry name
AWS_REGION=$(echo $IMAGE | cut -d'.' -f4)
# extract the registry name from the image name
REGISTRY=$(echo $IMAGE | cut -d'/' -f1)
BUILDER_IMAGE="gcr.io/kaniko-project/executor:v1.23.0-debug"
CRANE_IMAGE="docker.io/meirp3/crane:0.19.1"
ECR_PASS=$(aws ecr get-login-password --region ${AWS_REGION})
TEMP_FOLDER=$(mktemp -d)
cp -r ${CONTEXT}/* ${TEMP_FOLDER} || :
cp -r ${CONTEXT}/.dockerignore ${TEMP_FOLDER} || :
cat "${DOCKERFILE}" > ${TEMP_FOLDER}/Dockerfile
CURRENT_DIR=$(pwd)
cd ${TEMP_FOLDER}
tar -cf - . | gzip --best | kubectl run kaniko-$RANDOM \
--rm --stdin=true \
--image=${BUILDER_IMAGE} --restart=Never \
--overrides="
{
\"apiVersion\": \"v1\",
\"spec\": {
\"initContainers\": [
{
\"name\": \"configure-ecr-auth\",
\"image\": \"${CRANE_IMAGE}\",
\"stdin\": true,
\"stdinOnce\": true,
\"volumeMounts\": [
{
\"name\": \"docker-config\",
\"mountPath\": \"/root/.docker/\"
}
],
\"args\": [
\"auth\",
\"login\",
\"$REGISTRY\",
\"-u\",
\"AWS\",
\"-p\",
\"$ECR_PASS\"
]
}
],
\"containers\": [
{
\"name\": \"kaniko\",
\"image\": \"${BUILDER_IMAGE}\",
\"stdin\": true,
\"stdinOnce\": true,
\"args\": [
\"--cache\",
\"--cache-repo=${IMAGE%:*}\",
\"--dockerfile=Dockerfile\",
\"--context=tar://stdin\",
\"--destination=${IMAGE}\"
],
\"volumeMounts\": [
{
\"name\": \"docker-config\",
\"mountPath\": \"/kaniko/.docker/\"
}
]
}
],
\"volumes\": [
{
\"name\": \"docker-config\",
\"emptyDir\": {}
}
]
}
}
"
cd ${CURRENT_DIR}
rm -rf ${TEMP_FOLDER}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment