Introdução
Este guia explica como usar o GitHub Actions para criar um aplicativo conteinerizado, efetuar push dele para o Amazon ECR (Elastic Container Registry) e implantá-lo no Amazon ECS (Elastic Container Service) quando houver um push para o branch main
.
Em cada novo push para main
no repositório do GitHub, o fluxo de trabalho do GitHub Actions compila uma nova imagem de contêiner e efetua push para o Amazon ECR e implanta uma nova definição de tarefa no Amazon ECS.
Observação: Se os seus fluxos de trabalho de GitHub Actions tiverem de acessar recursos de um provedor de nuvem compatível com o OpenID Connect (OIDC), você poderá configurar seus fluxos de trabalho para efetuar a autenticção diretamente no provedor de nuvem. Isso permitirá que você pare de armazenar essas credenciais como segredos de longa duração e proporcione outros benefícios de segurança. Para obter mais informações, confira "Sobre o enrijecimento de segurança com o OpenID Connect". e "Configurando o OpenID Connect no Amazon Web Services".
Pré-requisitos
Antes de criar seu fluxo de trabalho de GitHub Actions, primeiro você precisa concluir as etapas a seguir para o Amazon ECR e ECS:
-
Crie um repositório Amazon ECR para armazenar suas imagens.
Por exemplo, usando a CLI da AWS:
Bash --repository-name MY_ECR_REPOSITORY \ --region MY_AWS_REGION
--repository-name MY_ECR_REPOSITORY \ --region MY_AWS_REGION
Ensure that you use the same Amazon ECR repository name (represented here by
MY_ECR_REPOSITORY
) for theECR_REPOSITORY
variable in the workflow below.Ensure that you use the same AWS region value for the
AWS_REGION
(represented here byMY_AWS_REGION
) variable in the workflow below. -
Create an Amazon ECS task definition, cluster, and service.
For details, follow the Getting started wizard on the Amazon ECS console, or the Getting started guide in the Amazon ECS documentation.
Ensure that you note the names you set for the Amazon ECS service and cluster, and use them for the
ECS_SERVICE
andECS_CLUSTER
variables in the workflow below. -
Store your Amazon ECS task definition as a JSON file in your GitHub repository.
The format of the file should be the same as the output generated by:
Bash aws ecs register-task-definition --generate-cli-skeleton
aws ecs register-task-definition --generate-cli-skeleton
Ensure that you set the
ECS_TASK_DEFINITION
variable in the workflow below as the path to the JSON file.Ensure that you set the
CONTAINER_NAME
variable in the workflow below as the container name in thecontainerDefinitions
section of the task definition. -
Create GitHub Actions secrets named
AWS_ACCESS_KEY_ID
andAWS_SECRET_ACCESS_KEY
to store the values for your Amazon IAM access key.For more information on creating secrets for GitHub Actions, see "Usar segredos em ações do GitHub."
See the documentation for each action used below for the recommended IAM policies for the IAM user, and methods for handling the access key credentials.
-
Optionally, configure a deployment environment. Os ambientes são usados para descrever um destino de implantação geral, como
production
,staging
oudevelopment
. Quando um fluxo de trabalho de GitHub Actions é implantado em um ambiente, o ambiente é exibido na página principal do repositório. Você pode usar ambientes para exigir aprovação para um trabalho prosseguir, restringir quais ramificações podem acionar um fluxo de trabalho , bloquear implantações com regras de proteção de implantação personalizadas ou limitar o acesso a segredos. Para saber mais sobre como criar ambientes, confira "Usando ambientes para implantação".
Creating the workflow
Once you've completed the prerequisites, you can proceed with creating the workflow.
The following example workflow demonstrates how to build a container image and push it to Amazon ECR. It then updates the task definition with the new image ID, and deploys the task definition to Amazon ECS.
Ensure that you provide your own values for all the variables in the env
key of the workflow.
Se você configurou um ambiente de implantação, altere o valor de environment
para que ele seja o nome do seu ambiente. Se você não tiver configurado um ambiente ou se o fluxo de trabalho estiver em um repositório privado e você não usar o GitHub Enterprise Cloud, exclua a chave environment
.
# Esse fluxo de trabalho usa ações que não são certificadas pelo GitHub. # São fornecidas por terceiros e regidas por # termos de serviço, política de privacidade e suporte separados # online. # O GitHub recomenda fixar ações em um SHA de commit. # Para obter uma versão mais recente, você precisará atualizar o SHA. # Você também pode fazer referência a uma marca ou branch, mas a ação pode ser alterada sem aviso. name: Deploy to Amazon ECS on: push: branches: - main env: AWS_REGION: MY_AWS_REGION # set this to your preferred AWS region, e.g. us-west-1 ECR_REPOSITORY: MY_ECR_REPOSITORY # set this to your Amazon ECR repository name ECS_SERVICE: MY_ECS_SERVICE # set this to your Amazon ECS service name ECS_CLUSTER: MY_ECS_CLUSTER # set this to your Amazon ECS cluster name ECS_TASK_DEFINITION: MY_ECS_TASK_DEFINITION # set this to the path to your Amazon ECS task definition # file, e.g. .aws/task-definition.json CONTAINER_NAME: MY_CONTAINER_NAME # set this to the name of the container in the # containerDefinitions section of your task definition jobs: deploy: name: Deploy runs-on: ubuntu-latest environment: production steps: - name: Checkout uses: actions/checkout@v4 - name: Configure AWS credentials uses: aws-actions/configure-aws-credentials@0e613a0980cbf65ed5b322eb7a1e075d28913a83 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: ${{ env.AWS_REGION }} - name: Login to Amazon ECR id: login-ecr uses: aws-actions/amazon-ecr-login@62f4f872db3836360b72999f4b87f1ff13310f3a - name: Build, tag, and push image to Amazon ECR id: build-image env: ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} IMAGE_TAG: ${{ github.sha }} run: | # Build a docker container and # push it to ECR so that it can # be deployed to ECS. docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG . docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" >> $GITHUB_OUTPUT - name: Fill in the new image ID in the Amazon ECS task definition id: task-def uses: aws-actions/amazon-ecs-render-task-definition@c804dfbdd57f713b6c079302a4c01db7017a36fc with: task-definition: ${{ env.ECS_TASK_DEFINITION }} container-name: ${{ env.CONTAINER_NAME }} image: ${{ steps.build-image.outputs.image }} - name: Deploy Amazon ECS task definition uses: aws-actions/amazon-ecs-deploy-task-definition@df9643053eda01f169e64a0e60233aacca83799a with: task-definition: ${{ steps.task-def.outputs.task-definition }} service: ${{ env.ECS_SERVICE }} cluster: ${{ env.ECS_CLUSTER }} wait-for-service-stability: true
# Esse fluxo de trabalho usa ações que não são certificadas pelo GitHub.
# São fornecidas por terceiros e regidas por
# termos de serviço, política de privacidade e suporte separados
# online.
# O GitHub recomenda fixar ações em um SHA de commit.
# Para obter uma versão mais recente, você precisará atualizar o SHA.
# Você também pode fazer referência a uma marca ou branch, mas a ação pode ser alterada sem aviso.
name: Deploy to Amazon ECS
on:
push:
branches:
- main
env:
AWS_REGION: MY_AWS_REGION # set this to your preferred AWS region, e.g. us-west-1
ECR_REPOSITORY: MY_ECR_REPOSITORY # set this to your Amazon ECR repository name
ECS_SERVICE: MY_ECS_SERVICE # set this to your Amazon ECS service name
ECS_CLUSTER: MY_ECS_CLUSTER # set this to your Amazon ECS cluster name
ECS_TASK_DEFINITION: MY_ECS_TASK_DEFINITION # set this to the path to your Amazon ECS task definition
# file, e.g. .aws/task-definition.json
CONTAINER_NAME: MY_CONTAINER_NAME # set this to the name of the container in the
# containerDefinitions section of your task definition
jobs:
deploy:
name: Deploy
runs-on: ubuntu-latest
environment: production
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@0e613a0980cbf65ed5b322eb7a1e075d28913a83
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ env.AWS_REGION }}
- name: Login to Amazon ECR
id: login-ecr
uses: aws-actions/amazon-ecr-login@62f4f872db3836360b72999f4b87f1ff13310f3a
- name: Build, tag, and push image to Amazon ECR
id: build-image
env:
ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
IMAGE_TAG: ${{ github.sha }}
run: |
# Build a docker container and
# push it to ECR so that it can
# be deployed to ECS.
docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" >> $GITHUB_OUTPUT
- name: Fill in the new image ID in the Amazon ECS task definition
id: task-def
uses: aws-actions/amazon-ecs-render-task-definition@c804dfbdd57f713b6c079302a4c01db7017a36fc
with:
task-definition: ${{ env.ECS_TASK_DEFINITION }}
container-name: ${{ env.CONTAINER_NAME }}
image: ${{ steps.build-image.outputs.image }}
- name: Deploy Amazon ECS task definition
uses: aws-actions/amazon-ecs-deploy-task-definition@df9643053eda01f169e64a0e60233aacca83799a
with:
task-definition: ${{ steps.task-def.outputs.task-definition }}
service: ${{ env.ECS_SERVICE }}
cluster: ${{ env.ECS_CLUSTER }}
wait-for-service-stability: true
Recursos adicionais
Para o fluxo de trabalho inicial original, confira aws.yml
no repositório starter-workflows
do GitHub Actions.
Para mais informações sobre os serviços utilizados nestes exemplos, veja a seguinte documentação:
- "Melhores práticas de segurança no IAM" na documentação da Amazon AWS.
- Ação oficial "Configurar credenciais da AWS" da AWS.
- Ação oficial "Logon" no Amazon ECR da AWS.
- Ação oficial "Renderizar Definição de Tarefa" do Amazon ECS da AWS.
- Ação oficial "Implantar Definição de Tarefa" do Amazon ECS da AWS.