awsdeploy.sh 2.61 KB
#!/bin/bash

source ~/.bash_profile
SERVICE_NAME=$1
REPOSITORY_NAME=$2
REGION=cn-north-1
CLUSTER=web
#FAMILY=$SERVICENAME
#NAME=`sed -n 's/.*"name": "\(.*\)",/\1/p' taskdef.json`
#SERVICE_NAME=$1

templatefile=${WORKSPACE}/Docker-Image-Deplopy/aws/${SERVICE_NAME}-template.json
echo "$templatefile"
#Replace the build number and respository URI placeholders with the constants above
sed -e "s;%IMAGE_VERSION%;${REPOSITORY_NAME};g" $templatefile > ${SERVICE_NAME}-v_${BUILD_NUMBER}.json
#Register the task definition in the repository
aws ecs register-task-definition --family ${SERVICE_NAME} --cli-input-json file://${WORKSPACE}/${SERVICE_NAME}-v_${BUILD_NUMBER}.json --region ${REGION}
SERVICES=`aws ecs describe-services --services ${SERVICE_NAME} --cluster ${CLUSTER} --region ${REGION} | jq .failures[]`
#Get latest revision
REVISION=`aws ecs describe-task-definition --task-definition ${SERVICE_NAME} --region ${REGION} | jq .taskDefinition.revision`

#Create or update service
if [ "$SERVICES" == "" ]; then
  echo "entered existing service"
  DESIRED_COUNT=`aws ecs describe-services --services ${SERVICE_NAME} --cluster ${CLUSTER} --region ${REGION} | jq .services[].desiredCount`
  if [ ${DESIRED_COUNT} = "0" ]; then
    DESIRED_COUNT="1"
  fi
  aws ecs update-service --cluster ${CLUSTER} --region ${REGION} --service ${SERVICE_NAME} --task-definition ${SERVICE_NAME}:${REVISION} --desired-count ${DESIRED_COUNT}
else
  echo "entered new service"
  aws ecs create-service --service-name ${SERVICE_NAME} --desired-count 1 --task-definition ${SERVICE_NAME} --cluster ${CLUSTER} --region ${REGION}
fi

# check service done by events
num=1
while [ $num -le 60 ]
do
    echo "begin check the service is done ,the check number is :$num "
    if [ "$num" == 60 ];then
        echo "over 10 min the service is not down please check the service ,the check number is :$num "
        exit 1
    fi
    let num=num+1
    echo "print the cluster info "

    SERVICEDEPLOYMENTPENDING=`aws ecs describe-services --cluster ${CLUSTER} --services ${SERVICE_NAME} |jq .services[].deployments[0].deployments`
    if [ "$SERVICEDEPLOYMENTPENDING" != 0 ] ;then
      sleep 10
      continue;
    fi

    EVENTMESSAGE=`aws ecs describe-services --cluster ${CLUSTER} --services ${SERVICE_NAME} |jq .services[].events[0].message`
    EVENTMESSAGENORMAL=(service "${SERVICE_NAME}") has reached a steady state
    echo "check event result : aws cli is : $EVENTMESSAGE"
    echo "check event result : EVENTMESSAGENORMAL cli is : $EVENTMESSAGENORMAL"
    if [[ $EVENTMESSAGE =~ $EVENTMESSAGENORMAL ]] ;then
       echo "check aws event is succeed"
       break;
    fi
    sleep 10
done