1+ #! /bin/bash
2+
3+ set -e # Exit on any error
4+
5+ # Check if profile argument is provided
6+ if [ $# -ne 1 ]; then
7+ echo " Usage: $0 <aws-profile>"
8+ echo " Example: $0 mcp-venue-cm"
9+ exit 1
10+ fi
11+
12+ AWS_PROFILE=$1
13+ echo " Using AWS Profile: $AWS_PROFILE "
14+
15+ # Verify the AWS profile exists
16+ if ! aws configure list-profiles | grep -q " ^${AWS_PROFILE} $" ; then
17+ echo " Error: AWS Profile '$AWS_PROFILE ' not found"
18+ exit 1
19+ fi
20+
21+ # Get venue from SSM
22+ VENUE=$( aws --profile " $AWS_PROFILE " ssm get-parameter --name " /unity/account/venue" --query " Parameter.Value" --output text)
23+ echo " Detected venue: $VENUE "
24+
25+ # Create backend configuration
26+ cat > backend.tf << EOF
27+ terraform {
28+ backend "s3" {
29+ bucket = "ucs-shared-services-apache-config-${VENUE} "
30+ key = "terraform/terraform.tfstate"
31+ region = "us-west-2"
32+ profile = "${AWS_PROFILE} "
33+ }
34+ }
35+ EOF
36+
37+ echo " Starting deployment..."
38+
39+ # Apply Terraform configuration
40+ echo " Applying Terraform configuration..."
41+ terraform init
42+ terraform apply -auto-approve
43+
44+ echo " Waiting 120 seconds for EC2 instance to initialize..."
45+ sleep 120
46+
47+ # Get the target group ARN
48+ TARGET_GROUP_ARN=$( aws --profile " $AWS_PROFILE " elbv2 describe-target-groups \
49+ --names ucs-httpd-tg \
50+ --query ' TargetGroups[0].TargetGroupArn' \
51+ --output text)
52+
53+ # Get the instance ID of the old EC2 by its Name tag
54+ OLD_INSTANCE_ID=$( aws --profile " $AWS_PROFILE " ec2 describe-instances \
55+ --filters " Name=tag:Name,Values=shared-services-httpd" " Name=instance-state-name,Values=running" \
56+ --query ' Reservations[0].Instances[0].InstanceId' \
57+ --output text)
58+
59+ if [ -n " $OLD_INSTANCE_ID " ]; then
60+ echo " Deregistering old EC2 instance ($OLD_INSTANCE_ID ) from target group..."
61+ aws --profile " $AWS_PROFILE " elbv2 deregister-targets \
62+ --target-group-arn " $TARGET_GROUP_ARN " \
63+ --targets " Id=$OLD_INSTANCE_ID "
64+
65+ echo " Old instance deregistered successfully"
66+ else
67+ echo " No running instance found with name 'shared-services-httpd'"
68+ fi
69+
70+ # Clean up backend config and Terraform files
71+ rm -f backend.tf
72+ rm -f .terraform.lock.hcl
73+ rm -rf .terraform
74+ echo " Cleaned up Terraform files"
75+
76+ echo " Deployment complete!"
0 commit comments