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