@@ -133,6 +133,36 @@ jobs:
133133 docker build -t ghcr.io/buffden/tinyurl-api:$IMAGE_TAG tinyurl/
134134 docker push ghcr.io/buffden/tinyurl-api:$IMAGE_TAG
135135
136+ - name : Start EC2 and wait for SSM agent
137+ run : |
138+ STATE=$(aws ec2 describe-instances \
139+ --instance-ids "$EC2_INSTANCE_ID" \
140+ --query "Reservations[0].Instances[0].State.Name" \
141+ --output text)
142+ if [ "$STATE" != "running" ]; then
143+ echo "Instance is $STATE — starting it"
144+ aws ec2 start-instances --instance-ids "$EC2_INSTANCE_ID"
145+ aws ec2 wait instance-running --instance-ids "$EC2_INSTANCE_ID"
146+ echo "STARTED_BY_PIPELINE=true" >> $GITHUB_ENV
147+ else
148+ echo "Instance already running — will not stop after deploy"
149+ fi
150+ echo "Waiting for SSM agent to come online..."
151+ for i in {1..20}; do
152+ SSM_STATUS=$(aws ssm describe-instance-information \
153+ --filters "Key=InstanceIds,Values=$EC2_INSTANCE_ID" \
154+ --query "InstanceInformationList[0].PingStatus" \
155+ --output text 2>/dev/null)
156+ echo "SSM agent status: $SSM_STATUS ($i/20)"
157+ if [ "$SSM_STATUS" = "Online" ]; then
158+ echo "SSM agent is online"
159+ exit 0
160+ fi
161+ sleep 15
162+ done
163+ echo "SSM agent did not come online in time"
164+ exit 1
165+
136166 - name : Deploy via SSM RunCommand
137167 env :
138168 IMAGE_TAG : ${{ github.sha }}
@@ -145,9 +175,7 @@ jobs:
145175 \"export RDS_ENDPOINT=$RDS_ENDPOINT\",
146176 \"cd /app\",
147177 \"docker compose -f docker-compose.prod.yml pull\",
148- \"docker compose -f docker-compose.prod.yml up -d\",
149- \"sleep 20\",
150- \"curl -sf http://localhost/actuator/health || exit 1\"
178+ \"docker compose -f docker-compose.prod.yml up -d\"
151179 ]" \
152180 --output text \
153181 --query "Command.CommandId")
@@ -177,3 +205,9 @@ jobs:
177205 done
178206 echo "Deploy timed out waiting for SSM"
179207 exit 1
208+
209+ - name : Stop EC2 instance
210+ if : always() && env.STARTED_BY_PIPELINE == 'true'
211+ run : |
212+ aws ec2 stop-instances --instance-ids "$EC2_INSTANCE_ID"
213+ echo "EC2 instance stopped"
0 commit comments