As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.
Tutoriais de início rápido para Amazon Managed Workflows for Apache Airflow
Este tutorial de início rápido usa um AWS CloudFormation modelo que cria a infraestrutura Amazon VPC, um bucket Amazon S3 com uma pasta e dags um ambiente Amazon Managed Workflows for Apache Airflow juntos.
Tópicos
Neste tutorial
Use este tutorial para fazer upload de um DAG para o Amazon S3, executar o DAG no Apache Airflow e acessar os logs usando três () comandos. CloudWatch AWS Command Line Interface AWS CLI Por fim, você aprenderá a criar uma política de IAM para uma equipe de desenvolvimento do Apache Airflow.
nota
O AWS CloudFormation modelo nesta página cria um ambiente Amazon Managed Workflows for Apache Airflow para a versão mais recente do Apache Airflow disponível em. AWS CloudFormation A versão mais recente disponível é o Apache Airflow v3.0.6.
O AWS CloudFormation modelo cria o seguinte:
-
Infraestrutura da VPC. O modelo usa Roteamento público pela Internet. Ele usa o Modo de acesso à rede pública para o servidor web Apache Airflow em.
WebserverAccessMode: PUBLIC_ONLY -
Bucket do Amazon S3. O modelo cria um bucket do Amazon S3 com uma pasta
dags. Ele está configurado para bloquear todo o acesso público, com o Versionamento de bucket habilitado, conforme definido em Criar um bucket do Amazon S3 para o Amazon MWAA. -
Ambiente do Amazon MWAA. O modelo cria um ambiente Amazon MWAA associado à
dagspasta no bucket do Amazon S3, uma função de execução com permissão AWS para serviços usados pelo Amazon MWAA e o padrão para criptografia usando AWS uma chave própria, conforme definido em. Criar um ambiente do Amazon MWAA -
CloudWatch Logs. O modelo ativa o login do Apache Airflow no nível INFO ou superior para o grupo de registros CloudWatch do agendador do Airflow, do grupo de registros do servidor web do Airflow, do grupo de registros de trabalhadores do Airflow, do grupo de registros de processamento do Airflow DAG e do grupo de registros de tarefas do Airflow, conforme definido em. Acessando os registros do Airflow na Amazon CloudWatch
Você concluirá as seguintes etapas neste tutorial:
-
Fazer upload e executar um DAG. Faça o upload do tutorial DAG do Apache Airflow para a versão mais recente do Apache Airflow compatível com o Amazon MWAA para o Amazon S3 e, em seguida, execute na IU do Apache Airflow, conforme definido em Adicionando ou atualizando DAGs.
-
Registros de acesso. Acesse o grupo de registros do servidor web Airflow em CloudWatch Logs, conforme definido em. Acessando os registros do Airflow na Amazon CloudWatch
-
Criar uma política de controle de acesso. Crie uma política de controle de acesso no IAM para sua equipe de desenvolvimento do Apache Airflow, conforme definido em Como acessar um ambiente do Amazon MWAA.
nota
Na VPC que hospeda o ambiente Amazon MWAA, defina como assignIpv6AddressOnCreation true para todas as sub-redes conectadas. Essa configuração garante a atribuição automática de endereços do Protocolo de Internet versão 6 (IPv6) aos recursos dentro dessas sub-redes.
Pré-requisitos
O AWS Command Line Interface (AWS CLI) é uma ferramenta de código aberto que você pode usar para interagir com AWS serviços usando comandos em seu shell de linha de comando. Para concluir as etapas nesta página, é necessário o seguinte:
Etapa 1: salvar o AWS CloudFormation modelo localmente
-
Copie o conteúdo do modelo a seguir e salve localmente como
mwaa-public-network.yml. Também é possível baixar o modelo.AWSTemplateFormatVersion: "2010-09-09" Parameters: EnvironmentName: Description: An environment name that is prefixed to resource names Type: String Default: MWAAEnvironment VpcCIDR: Description: The IP range (CIDR notation) for this VPC Type: String Default: 10.192.0.0/16 PublicSubnet1CIDR: Description: The IP range (CIDR notation) for the public subnet in the first Availability Zone Type: String Default: 10.192.10.0/24 PublicSubnet2CIDR: Description: The IP range (CIDR notation) for the public subnet in the second Availability Zone Type: String Default: 10.192.11.0/24 PrivateSubnet1CIDR: Description: The IP range (CIDR notation) for the private subnet in the first Availability Zone Type: String Default: 10.192.20.0/24 PrivateSubnet2CIDR: Description: The IP range (CIDR notation) for the private subnet in the second Availability Zone Type: String Default: 10.192.21.0/24 MaxWorkerNodes: Description: The maximum number of workers that can run in the environment Type: Number Default: 2 DagProcessingLogs: Description: Log level for DagProcessing Type: String Default: INFO SchedulerLogsLevel: Description: Log level for SchedulerLogs Type: String Default: INFO TaskLogsLevel: Description: Log level for TaskLogs Type: String Default: INFO WorkerLogsLevel: Description: Log level for WorkerLogs Type: String Default: INFO WebserverLogsLevel: Description: Log level for WebserverLogs Type: String Default: INFO Resources: ##################################################################################################################### # CREATE VPC ##################################################################################################################### VPC: Type: AWS::EC2::VPC Properties: CidrBlock: !Ref VpcCIDR EnableDnsSupport: true EnableDnsHostnames: true Tags: - Key: Name Value: MWAAEnvironment InternetGateway: Type: AWS::EC2::InternetGateway Properties: Tags: - Key: Name Value: MWAAEnvironment InternetGatewayAttachment: Type: AWS::EC2::VPCGatewayAttachment Properties: InternetGatewayId: !Ref InternetGateway VpcId: !Ref VPC PublicSubnet1: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC AvailabilityZone: !Select [ 0, !GetAZs '' ] CidrBlock: !Ref PublicSubnet1CIDR MapPublicIpOnLaunch: true Tags: - Key: Name Value: !Sub ${EnvironmentName} Public Subnet (AZ1) PublicSubnet2: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC AvailabilityZone: !Select [ 1, !GetAZs '' ] CidrBlock: !Ref PublicSubnet2CIDR MapPublicIpOnLaunch: true Tags: - Key: Name Value: !Sub ${EnvironmentName} Public Subnet (AZ2) PrivateSubnet1: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC AvailabilityZone: !Select [ 0, !GetAZs '' ] CidrBlock: !Ref PrivateSubnet1CIDR MapPublicIpOnLaunch: false Tags: - Key: Name Value: !Sub ${EnvironmentName} Private Subnet (AZ1) PrivateSubnet2: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC AvailabilityZone: !Select [ 1, !GetAZs '' ] CidrBlock: !Ref PrivateSubnet2CIDR MapPublicIpOnLaunch: false Tags: - Key: Name Value: !Sub ${EnvironmentName} Private Subnet (AZ2) NatGateway1EIP: Type: AWS::EC2::EIP DependsOn: InternetGatewayAttachment Properties: Domain: vpc NatGateway2EIP: Type: AWS::EC2::EIP DependsOn: InternetGatewayAttachment Properties: Domain: vpc NatGateway1: Type: AWS::EC2::NatGateway Properties: AllocationId: !GetAtt NatGateway1EIP.AllocationId SubnetId: !Ref PublicSubnet1 NatGateway2: Type: AWS::EC2::NatGateway Properties: AllocationId: !GetAtt NatGateway2EIP.AllocationId SubnetId: !Ref PublicSubnet2 PublicRouteTable: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref VPC Tags: - Key: Name Value: !Sub ${EnvironmentName} Public Routes DefaultPublicRoute: Type: AWS::EC2::Route DependsOn: InternetGatewayAttachment Properties: RouteTableId: !Ref PublicRouteTable DestinationCidrBlock: 0.0.0.0/0 GatewayId: !Ref InternetGateway PublicSubnet1RouteTableAssociation: Type: AWS::EC2::SubnetRouteTableAssociation Properties: RouteTableId: !Ref PublicRouteTable SubnetId: !Ref PublicSubnet1 PublicSubnet2RouteTableAssociation: Type: AWS::EC2::SubnetRouteTableAssociation Properties: RouteTableId: !Ref PublicRouteTable SubnetId: !Ref PublicSubnet2 PrivateRouteTable1: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref VPC Tags: - Key: Name Value: !Sub ${EnvironmentName} Private Routes (AZ1) DefaultPrivateRoute1: Type: AWS::EC2::Route Properties: RouteTableId: !Ref PrivateRouteTable1 DestinationCidrBlock: 0.0.0.0/0 NatGatewayId: !Ref NatGateway1 PrivateSubnet1RouteTableAssociation: Type: AWS::EC2::SubnetRouteTableAssociation Properties: RouteTableId: !Ref PrivateRouteTable1 SubnetId: !Ref PrivateSubnet1 PrivateRouteTable2: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref VPC Tags: - Key: Name Value: !Sub ${EnvironmentName} Private Routes (AZ2) DefaultPrivateRoute2: Type: AWS::EC2::Route Properties: RouteTableId: !Ref PrivateRouteTable2 DestinationCidrBlock: 0.0.0.0/0 NatGatewayId: !Ref NatGateway2 PrivateSubnet2RouteTableAssociation: Type: AWS::EC2::SubnetRouteTableAssociation Properties: RouteTableId: !Ref PrivateRouteTable2 SubnetId: !Ref PrivateSubnet2 SecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupName: "mwaa-security-group" GroupDescription: "Security group with a self-referencing inbound rule." VpcId: !Ref VPC SecurityGroupIngress: Type: AWS::EC2::SecurityGroupIngress Properties: GroupId: !Ref SecurityGroup IpProtocol: "-1" SourceSecurityGroupId: !Ref SecurityGroup EnvironmentBucket: Type: AWS::S3::Bucket Properties: VersioningConfiguration: Status: Enabled PublicAccessBlockConfiguration: BlockPublicAcls: true BlockPublicPolicy: true IgnorePublicAcls: true RestrictPublicBuckets: true ##################################################################################################################### # CREATE MWAA ##################################################################################################################### MwaaEnvironment: Type: AWS::MWAA::Environment DependsOn: MwaaExecutionPolicy Properties: Name: !Sub "${AWS::StackName}-MwaaEnvironment" SourceBucketArn: !GetAtt EnvironmentBucket.Arn ExecutionRoleArn: !GetAtt MwaaExecutionRole.Arn DagS3Path: dags/ NetworkConfiguration: SecurityGroupIds: - !GetAtt SecurityGroup.GroupId SubnetIds: - !Ref PrivateSubnet1 - !Ref PrivateSubnet2 WebserverAccessMode: PUBLIC_ONLY MaxWorkers: !Ref MaxWorkerNodes LoggingConfiguration: DagProcessingLogs: LogLevel: !Ref DagProcessingLogs Enabled: true SchedulerLogs: LogLevel: !Ref SchedulerLogsLevel Enabled: true TaskLogs: LogLevel: !Ref TaskLogsLevel Enabled: true WorkerLogs: LogLevel: !Ref WorkerLogsLevel Enabled: true WebserverLogs: LogLevel: !Ref WebserverLogsLevel Enabled: true MwaaExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: 2012-10-17&TCX5-2025-waiver; Statement: - Effect: Allow Principal: Service: - airflow-env.amazonaws.com - airflow.amazonaws.com Action: - "sts:AssumeRole" Path: "/service-role/" MwaaExecutionPolicy: DependsOn: EnvironmentBucket Type: AWS::IAM::ManagedPolicy Properties: Roles: - !Ref MwaaExecutionRole PolicyDocument: Version: 2012-10-17&TCX5-2025-waiver; Statement: - Effect: Allow Action: airflow:PublishMetrics Resource: - !Sub "arn:aws:airflow:${AWS::Region}:${AWS::AccountId}:environment/${EnvironmentName}" - Effect: Deny Action: s3:ListAllMyBuckets Resource: - !Sub "${EnvironmentBucket.Arn}" - !Sub "${EnvironmentBucket.Arn}/*" - Effect: Allow Action: - "s3:GetObject*" - "s3:GetBucket*" - "s3:List*" Resource: - !Sub "${EnvironmentBucket.Arn}" - !Sub "${EnvironmentBucket.Arn}/*" - Effect: Allow Action: - logs:DescribeLogGroups Resource: "*" - Effect: Allow Action: - logs:CreateLogStream - logs:CreateLogGroup - logs:PutLogEvents - logs:GetLogEvents - logs:GetLogRecord - logs:GetLogGroupFields - logs:GetQueryResults - logs:DescribeLogGroups Resource: - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:airflow-${AWS::StackName}*" - Effect: Allow Action: cloudwatch:PutMetricData Resource: "*" - Effect: Allow Action: - sqs:ChangeMessageVisibility - sqs:DeleteMessage - sqs:GetQueueAttributes - sqs:GetQueueUrl - sqs:ReceiveMessage - sqs:SendMessage Resource: - !Sub "arn:aws:sqs:${AWS::Region}:*:airflow-celery-*" - Effect: Allow Action: - kms:Decrypt - kms:DescribeKey - "kms:GenerateDataKey*" - kms:Encrypt NotResource: !Sub "arn:aws:kms:*:${AWS::AccountId}:key/*" Condition: StringLike: "kms:ViaService": - !Sub "sqs.${AWS::Region}.amazonaws.com" Outputs: VPC: Description: A reference to the created VPC Value: !Ref VPC PublicSubnets: Description: A list of the public subnets Value: !Join [ ",", [ !Ref PublicSubnet1, !Ref PublicSubnet2 ]] PrivateSubnets: Description: A list of the private subnets Value: !Join [ ",", [ !Ref PrivateSubnet1, !Ref PrivateSubnet2 ]] PublicSubnet1: Description: A reference to the public subnet in the 1st Availability Zone Value: !Ref PublicSubnet1 PublicSubnet2: Description: A reference to the public subnet in the 2nd Availability Zone Value: !Ref PublicSubnet2 PrivateSubnet1: Description: A reference to the private subnet in the 1st Availability Zone Value: !Ref PrivateSubnet1 PrivateSubnet2: Description: A reference to the private subnet in the 2nd Availability Zone Value: !Ref PrivateSubnet2 SecurityGroupIngress: Description: Security group with self-referencing inbound rule Value: !Ref SecurityGroupIngress MwaaApacheAirflowUI: Description: MWAA Environment Value: !Sub "https://${MwaaEnvironment.WebserverUrl}"
Etapa 2: criar a pilha usando o AWS CLI
-
No prompt de comando, navegue até o diretório em que
mwaa-public-network.ymlestá armazenado. Por exemplo:cd mwaaproject -
Use o comando
aws cloudformation create-stackpara criar a pilha usando o AWS CLI.aws cloudformation create-stack --stack-name mwaa-environment-public-network --template-body file://mwaa-public-network.yml --capabilities CAPABILITY_IAMnota
São necessários mais de 30 minutos para criar a infraestrutura Amazon VPC, o bucket Amazon S3 e o ambiente Amazon MWAA.
Etapa 3: faça o upload de um DAG para o Amazon S3 e execute-o na IU do Apache Airflow
-
Copie o conteúdo do arquivo
tutorial.pypara a versão mais recente compatível do Apache Airflowe salve localmente como tutorial.py. -
No prompt de comando, navegue até o diretório em que
tutorial.pyestá armazenado. Por exemplo:cd mwaaproject -
Use o comando a seguir para listar todos os seus buckets do Amazon S3.
aws s3 ls -
Use o seguinte comando para listar os arquivos e pastas no bucket do Amazon S3 para seu ambiente.
aws s3 ls s3://YOUR_S3_BUCKET_NAME -
Use o script a seguir para fazer upload do arquivo
tutorial.pypara sua pastadags. Substitua o valor da amostra emamzn-s3-demo-bucket.aws s3 cp tutorial.py s3://amzn-s3-demo-bucket/dags/ -
Abra a página Ambientes
no console do Amazon MWAA. -
Escolha um ambiente.
-
Escolha Abrir a IU do Airflow.
-
Na interface de usuário do Apache Airflow, na lista de DAGs disponíveis, escolha o tutorial DAG.
-
Na página de detalhes do DAG, escolha o botão Pausar/Reiniciar o DAG ao lado do nome do DAG para retomar o DAG.
-
Escolha Acionar DAG.
Etapa quatro: acessar registros em CloudWatch Logs
Você pode acessar os registros do Apache Airflow no console para todos os registros CloudWatch do Apache Airflow que foram ativados pela pilha. AWS CloudFormation A seção a seguir explica como acessar os registros do grupo de registros do servidor web Airflow.
-
Abra a página Ambientes
no console do Amazon MWAA. -
Escolha um ambiente.
-
Escolha o grupo de log do servidor web Airflow no painel Monitoramento.
-
Escolha o log
webserver_console_ipem Fluxos de logs.
Próximas etapas
-
Saiba mais sobre como fazer upload DAGs, especificar dependências do Python em um
requirements.txte plug-ins personalizados em um in.plugins.zipTrabalhando com o DAGs Amazon MWAA -
Saiba mais sobre as melhores práticas que recomendamos para ajustar o desempenho do seu ambiente em Ajuste de desempenho para o Apache Airflow no Amazon MWAA.
-
Crie um painel de monitoramento para seu ambiente em Painéis de monitoramento e alarmes no Amazon MWAA.
-
Execute alguns exemplos de código do DAG em Exemplos de código para o Amazon Managed Workflows for Apache Airflow.