!/bin/bash

!/bin/bash

Build Source!

aws s3 cp --region ap-south-1 s3://jenkins-cicd-sandbox/theodore/sandbox.json ./buildSrc/src/main/resources/

gradlew_output=$(./gradlew clean build createDockerfile -x test); gradlew_return_code=$?

if (( gradlew_return_code != 0 )); then
echo "Grade failed with exit status $gradlew_return_code" >&2
echo "and output: $gradlew_output" >&2
exit 1
fi

ECR_IMAGE=$(./gradlew -q getBasicInfo )

echo -e "ECR_IMAGE=${ECR_IMAGE}\nPROJECT=theodore\nSERVICE_FAMILY=common-apps\nENV=${ENV}" > theodore_version.txt

fargate deployment

rm -rf new_task_definition.json
echo $PROJECT
echo $SERVICE_FAMILY
echo $ECR_IMAGE
echo $ENV

############################

Updating task definition

##############################

TASK_DEFINITION=$(aws ecs describe-task-definition --task-definition $SERVICE_FAMILY-services-$PROJECT --region ap-south-1 )

echo $TASK_DEFINITION | jq --arg IMAGE "$ECR_IMAGE" '.taskDefinition | .containerDefinitions[0].image = $IMAGE | del(.taskDefinitionArn) | del(.revision) | del(.status) | del(.requiresAttributes) | del(.compatibilities)' > new_task_definition.json

NEW_TASK_INFO=$(aws ecs register-task-definition --region ap-south-1 --cli-input-json file://new_task_definition.json )

NEW_REVISION=$(echo $NEW_TASK_INFO | jq '.taskDefinition.revision')

OLD_REVISION=$[NEW_REVISION-1]

echo "new revision is $NEW_REVISION"
echo "old revision is $OLD_REVISION"

aws ecs update-service --cluster $ENV-$SERVICE_FAMILY-services-$PROJECT --service ${ENV}_services-$PROJECT --task-definition $SERVICE_FAMILY-services-$PROJECT:$NEW_REVISION > /dev/null

############################

Rollback Condition

##############################

wait_period=1

FLAG=$(aws ecs describe-services --cluster $ENV-$SERVICE_FAMILY-services-$PROJECT --services ${ENV}_services-$PROJECT | jq '.services[0].events[0].message' | grep "has reached a steady state")

while true
do

echo "Sleeping for 10 seconds"
 echo " Displaying the status of new task-revision update to service"
aws ecs describe-services --cluster $ENV-$SERVICE_FAMILY-services-$PROJECT  --services ${ENV}_services-$PROJECT | jq  '.services[0].events[0].message'
echo "$wait_period" # for my reference

# Here 300 is 300 seconds i.e. 5 minutes * 60 = 300 sec
wait_period=$(($wait_period+10))
if [[ $wait_period -gt 120 && -z $FLAG ]]
then
   echo "rolling back command"
   aws ecs update-service --cluster $ENV-$SERVICE_FAMILY-services-$PROJECT  --service ${ENV}_services-$PROJECT --task-definition $SERVICE_FAMILY-services-$PROJECT:$OLD_REVISION > /dev/null
   echo "$wait_period"
   break
elif [[ $wait_period -gt 120  &&  $FLAG ]] 
then 
   echo "status of new-task-definition revision $FLAG"
   echo "successful"
   break  
else
   sleep 10
fi

done