#!/bin/bash # Check if AWS CLI is installed if ! command -v aws &> /dev/null then echo "AWS CLI not found. Please install and configure the AWS CLI." exit 1 fi # Assign arguments to variables PROJECT_NAME=$CODEBUILD_PROJECT_NAME BUCKET_NAME=$S3_BUCKET_NAME REPOSITORY_NAME=$ECR_REPO_NAME DOCKER_USERNAME=$DOCKER_USERNAME DOCKER_PASSWORD=$DOCKER_PASSWORD STACK_NAME="${PROJECT_NAME}-stack" BUILDSPEC_FILE="buildspec.yaml" ZIP_FILE="buildspec.zip" S3_BUILDSPEC_KEY="buildspecs/$ZIP_FILE" # Check if the buildspec.yaml file exists if [ ! -f $BUILDSPEC_FILE ]; then echo "buildspec.yaml file not found!" exit 1 fi # Create a ZIP file containing the buildspec.yaml zip -j $ZIP_FILE $BUILDSPEC_FILE if [ $? -ne 0 ]; then echo "Failed to create ZIP file" exit 1 fi # Upload the ZIP file to the specified S3 bucket aws s3 cp $ZIP_FILE s3://$BUCKET_NAME/$S3_BUILDSPEC_KEY if [ $? -ne 0 ]; then echo "Failed to upload ZIP file to S3" exit 1 fi # Check if the project.yaml file exists if [ ! -f project.yaml ]; then echo "project.yaml file not found!" exit 1 fi # Check if the stack exists stack_exists=$(aws cloudformation describe-stacks --stack-name "$STACK_NAME" 2>&1) if [[ $stack_exists == *"does not exist"* ]]; then # Create the CloudFormation stack echo "Creating CloudFormation stack '$STACK_NAME'..." aws cloudformation create-stack \ --stack-name "$STACK_NAME" \ --template-body file://project.yaml \ --parameters \ ParameterKey=ProjectName,ParameterValue="$PROJECT_NAME" \ ParameterKey=S3BucketName,ParameterValue="$BUCKET_NAME" \ ParameterKey=RepositoryName,ParameterValue="$REPOSITORY_NAME" \ ParameterKey=S3BuildSpecKey,ParameterValue="$S3_BUILDSPEC_KEY" \ ParameterKey=DockerUsername,ParameterValue="$DOCKER_USERNAME" \ ParameterKey=DockerPassword,ParameterValue="$DOCKER_PASSWORD" \ --capabilities CAPABILITY_NAMED_IAM # Check if the stack creation was successful if [ $? -eq 0 ]; then echo "CloudFormation stack '$STACK_NAME' has been created successfully." else echo "Failed to create CloudFormation stack '$STACK_NAME'." exit 1 fi else # Update the CloudFormation stack echo "Updating CloudFormation stack '$STACK_NAME'..." aws cloudformation update-stack \ --stack-name "$STACK_NAME" \ --template-body file://project.yaml \ --parameters \ ParameterKey=ProjectName,ParameterValue="$PROJECT_NAME" \ ParameterKey=S3BucketName,ParameterValue="$BUCKET_NAME" \ ParameterKey=RepositoryName,ParameterValue="$REPOSITORY_NAME" \ ParameterKey=S3BuildSpecKey,ParameterValue="$S3_BUILDSPEC_KEY" \ ParameterKey=DockerUsername,ParameterValue="$DOCKER_USERNAME" \ ParameterKey=DockerPassword,ParameterValue="$DOCKER_PASSWORD" \ --capabilities CAPABILITY_NAMED_IAM # Check if the stack update was successful if [ $? -eq 0 ]; then echo "CloudFormation stack '$STACK_NAME' has been updated successfully." else echo "Failed to update CloudFormation stack '$STACK_NAME'." exit 1 fi fi # Clean up the ZIP file rm $ZIP_FILE