1+ # docker/build_push_to_ecr.sh
2+
3+ #! /bin/bash
4+
5+ # Set variables
6+ AWS_REGION=" eu-west-2"
7+ ACCOUNT_ID=$( aws sts get-caller-identity --query Account --output text)
8+ REPOSITORY_NAME=" imms-fhir-api-grafana"
9+ IMAGE_TAG=" 11.0.0-22.04_stable"
10+ DOCKERFILE_DIR=" /Users/watess01/Documents/NHS/code/immunisation-fhir-api/grafana/non-prod/docker"
11+ TAGS=" Key=Environment,Value=non-prod Key=Project,Value=immunisation-fhir-api-grafana"
12+
13+ # Change to the directory containing the Dockerfile
14+ cd $DOCKERFILE_DIR
15+
16+ # Check if Dockerfile exists
17+ if [ ! -f Dockerfile ]; then
18+ echo " Dockerfile not found in the current directory."
19+ exit 1
20+ fi
21+
22+ # Create ECR repository if it does not exist
23+ aws ecr describe-repositories --repository-names $REPOSITORY_NAME --region $AWS_REGION > /dev/null 2>&1
24+
25+ if [ $? -ne 0 ]; then
26+ echo " Creating ECR repository: $REPOSITORY_NAME "
27+ aws ecr create-repository --repository-name $REPOSITORY_NAME --region $AWS_REGION
28+ # Add tags to the repository
29+ aws ecr tag-resource --resource-arn arn:aws:ecr:$AWS_REGION :$ACCOUNT_ID :repository/$REPOSITORY_NAME --tags $TAGS
30+ fi
31+
32+ printf " Building and pushing Docker image to ECR...\n"
33+ # Authenticate Docker to ECR
34+ aws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $ACCOUNT_ID .dkr.ecr.$AWS_REGION .amazonaws.com
35+
36+ printf " Building Docker image...\n"
37+ # Build Docker image
38+ # docker build -t $REPOSITORY_NAME:$IMAGE_TAG .
39+ # Build Docker image for linux/amd64 architecture
40+ docker buildx create --use
41+ docker buildx build --platform linux/amd64 -t $ACCOUNT_ID .dkr.ecr.$AWS_REGION .amazonaws.com/$REPOSITORY_NAME :$IMAGE_TAG --push .
42+
43+
44+ # Check if the build was successful
45+ if [ $? -ne 0 ]; then
46+ echo " Docker build failed."
47+ exit 1
48+ fi
49+
50+ printf " Tagging Docker image...\n"
51+ # Tag Docker image
52+ docker tag $REPOSITORY_NAME :$IMAGE_TAG $ACCOUNT_ID .dkr.ecr.$AWS_REGION .amazonaws.com/$REPOSITORY_NAME :$IMAGE_TAG
53+
54+ # Check if the tag was successful
55+ if [ $? -ne 0 ]; then
56+ echo " Docker tag failed."
57+ exit 1
58+ fi
59+
60+ printf " Pushing Docker image to ECR...\n"
61+ # Push Docker image to ECR
62+ docker push $ACCOUNT_ID .dkr.ecr.$AWS_REGION .amazonaws.com/$REPOSITORY_NAME :$IMAGE_TAG
63+
64+ # Check if the push was successful
65+ if [ $? -ne 0 ]; then
66+ echo " Docker push failed."
67+ exit 1
68+ fi
69+
70+ echo " Docker image built and pushed to ECR successfully."
0 commit comments