Skip to content

Instantly share code, notes, and snippets.

@trylix
Created August 30, 2024 14:15
Show Gist options
  • Select an option

  • Save trylix/ae29522659c2804564fd498cfc4b70f6 to your computer and use it in GitHub Desktop.

Select an option

Save trylix/ae29522659c2804564fd498cfc4b70f6 to your computer and use it in GitHub Desktop.
name: Deploy to ECS
on:
push:
branches:
- '*'
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v2
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: us-east-1
- name: Login to Amazon ECR
id: ecr-login
uses: aws-actions/amazon-ecr-login@v2
- name: Build and push Docker image to ECR
run: |
IMAGE_TAG=${{ github.sha }}
BRANCH_NAME=${{ github.ref_name }}
REPOSITORY_NAME=my-ecr-repo
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com
docker build -t $REPOSITORY_NAME:$IMAGE_TAG .
docker tag $REPOSITORY_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/$REPOSITORY_NAME:$BRANCH_NAME
docker push $AWS_ACCOUNT_ID.dkr.ecr.us-east-1.amazonaws.com/$REPOSITORY_NAME:$BRANCH_NAME
- name: Create or update ECS service
run: |
BRANCH_NAME=${{ github.ref_name }}
SERVICE_NAME=my-service-${BRANCH_NAME}
# Crie um novo serviço ECS para a branch se ele ainda não existir
EXISTING_SERVICE=$(aws ecs describe-services --cluster my-cluster-name --services $SERVICE_NAME --query "services[0].serviceArn" --output text 2>/dev/null || echo "")
if [ -z "$EXISTING_SERVICE" ]; then
aws ecs create-service \
--cluster my-cluster-name \
--service-name $SERVICE_NAME \
--task-definition my-task-definition \
--desired-count 1 \
--launch-type FARGATE \
--network-configuration "awsvpcConfiguration={subnets=[subnet-xxxxxxxx],securityGroups=[sg-xxxxxxxx],assignPublicIp=ENABLED}" \
--load-balancers "targetGroupArn=arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/my-target-group/6d0ecf831eec9f09,containerName=my-container,containerPort=80"
else
aws ecs update-service --cluster my-cluster-name --service $SERVICE_NAME --force-new-deployment
fi
- name: Update ALB rules
run: |
aws elbv2 create-rule \
--listener-arn arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/7c7a56b0 \
--conditions "Field=path-pattern,Values=/${{ github.ref_name }}/*" \
--actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/my-target-group/6d0ecf831eec9f09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment