Skip to content

Unable to setup MWAA for airflow version 3.0.6 through Cloudformation

0

Hey all,

I have been trying to setup airflow version 3.0.6 (latest available in AWS) but I've been unable to do so. The problem only seems to exist when using cloudformation. When I follow my template but through the UI the environment is working but with cloudformation it fails everytime. Some errors I'm getting in the Webserver loggroup is:

ERROR - Creation of Permission View Error: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "ab_permission_view_permission_id_view_menu_id_uq"

But this error is very inconsistent. When I delete my cloudformation stack and rerun the error sometimes is not in the Webserver loggroup. It then just times out and the environment is not created, the webserver log is then full of 200 status codes for health checks. The biggest difference I see when I create the environment through cloudformation vs UI is that under "Network Details" the "Database VPC endpoint service" and the "Celery executor queue ARN" Are empty. Also during the creating status I'm able to view the Airflow UI and I can see that MetaDatabase is Health while Scheduler, Triggerer and Dag Processor are unhealthy not sure if this is expected since it's during the creation status. This is the cloudformation template im using.

Description: Stack that creates the managed airflow infrastructure
Parameters:
  Environment:
    Default: nonprod
    Description: Define the environment where the stack is created
    Type: String
Resources:
  ManagedAirflowEnvironment:
    Properties:
      AirflowConfigurationOptions:
        celery.sync_parallelism: 1
        celery.worker_autoscale: 20,2
        core.dag_concurrency: 16
        core.dag_run_conf_overrides_params: 'True'
        core.parallelism: 200
        scheduler.scheduler_idle_sleep_time: 1
        scheduler.scheduler_zombie_task_threshold: 7200
        scheduler.task_queued_timeout: 300
        scheduler.task_queued_timeout_check_interval: 60
        webserver.show_trigger_form_if_no_params: 'True'
        webserver.warn_deployment_exposure: 'False'
      AirflowVersion: 3.0.6
      DagS3Path: !Sub 'airflow/dags'
      EnvironmentClass: mw1.large
      ExecutionRoleArn: !GetAtt 'ManagedAirflowServiceRole.Arn'
      LoggingConfiguration:
        DagProcessingLogs:
          Enabled: true
          LogLevel: WARNING
        SchedulerLogs:
          Enabled: true
          LogLevel: WARNING
        TaskLogs:
          Enabled: true
          LogLevel: WARNING
        WebserverLogs:
          Enabled: true
          LogLevel: WARNING
        WorkerLogs:
          Enabled: true
          LogLevel: WARNING
      MaxWorkers: 10
      MinWorkers: 2
      Name: !Sub 'managed-airflow-v3-test-vrt-${Environment}'
      NetworkConfiguration:
        SecurityGroupIds:
          - !GetAtt 'ManagedAirflowSecurityGroupRestricted.GroupId'
        SubnetIds:
          - !ImportValue
            Fn::Sub: vrt-dpc-vpc-restricted-PrivateSubnetB-ref
          - !ImportValue
            Fn::Sub: vrt-dpc-vpc-restricted-PrivateSubnetC-ref
      PluginsS3Path: airflow/vrt_airflow_plugin_v3_latest.zip
      RequirementsS3Path: airflow/requirements.txt
      Schedulers: 2
      SourceBucketArn: !Sub 'arn:aws:s3:::vrt-airflow-v3-bucket-${Environment}'
      Tags:
        afdeling: dpc
        kp: '46015'
        owner: data-intelligence
        process: scheduling
        project: datalake
      WebserverAccessMode: PUBLIC_ONLY
    Type: AWS::MWAA::Environment
  ManagedAirflowSecurityGroupRestricted:
    Properties:
      GroupDescription: !Sub 'VRT managed airflow security group for restricted vpc in ${Environment}'
      GroupName: !Sub 'managed-airflow-v3-test-security-group-restricted-${Environment}'
      VpcId: <vpc-id>
    Type: AWS::EC2::SecurityGroup
  ManagedAirflowServiceRole:
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service:
                - airflow.amazonaws.com
                - airflow-env.amazonaws.com
        Version: '2012-10-17'
      Description: service role for the managed airflow
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AWSLambda_FullAccess
        - arn:aws:iam::aws:policy/AmazonS3FullAccess
        - arn:aws:iam::aws:policy/AmazonElasticMapReduceFullAccess
        - arn:aws:iam::aws:policy/AmazonAthenaFullAccess
        - arn:aws:iam::aws:policy/AmazonSageMakerFullAccess
        - arn:aws:iam::aws:policy/AmazonSQSFullAccess
      Policies:
        - PolicyDocument:
            Statement:
              - Action: airflow:PublishMetrics
                Effect: Allow
                Resource: !Sub 'arn:aws:airflow:<account-region>:<account-id>:environment/managed-airflow-vrt-v3-test-${Environment}'
              - Action: s3:ListAllMyBuckets
                Effect: Deny
                Resource:
                  - !Sub 'arn:aws:s3:::vrt-airflow-v3-bucket-${Environment}'
                  - !Sub 'arn:aws:s3:::vrt-airflow-v3-bucket-${Environment}/*'
              - Action:
                  - s3:GetObject*
                  - s3:GetBucket*
                  - s3:List*
                Effect: Allow
                Resource:
                  - !Sub 'arn:aws:s3:::vrt-airflow-v3-bucket-${Environment}'
                  - !Sub 'arn:aws:s3:::vrt-airflow-v3-bucket-${Environment}/*'
              - Action:
                  - logs:CreateLogStream
                  - logs:CreateLogGroup
                  - logs:PutLogEvents
                  - logs:GetLogEvents
                  - logs:GetLogRecord
                  - logs:GetLogGroupFields
                  - logs:GetQueryResults
                Effect: Allow
                Resource:
                  - !Sub 'arn:aws:logs:<account-region>:<account-id>:log-group:airflow-managed-airflow-vrt-v3-test-${Environment}-*'
              - Action:
                  - logs:DescribeLogGroups
                Effect: Allow
                Resource:
                  - '*'
              - Action: cloudwatch:PutMetricData
                Effect: Allow
                Resource: '*'
              - Action:
                  - sqs:ChangeMessageVisibility
                  - sqs:DeleteMessage
                  - sqs:GetQueueAttributes
                  - sqs:GetQueueUrl
                  - sqs:ReceiveMessage
                  - sqs:SendMessage
                Effect: Allow
                Resource: arn:aws:sqs:<account-region>:*:airflow-celery-*
              - Action:
                  - kms:Decrypt
                  - kms:DescribeKey
                  - kms:GenerateDataKey*
                  - kms:Encrypt
                Condition:
                  StringLike:
                    kms:ViaService:
                      - sqs.<account-region>.amazonaws.com
                Effect: Allow
                NotResource: arn:aws:kms:*:<account-id>:key/*
              - Action:
                  - dms:CreateReplicationTask
                  - dms:DeleteReplicationTask
                  - dms:DescribeReplicationInstances
                  - dms:DescribeSchemas
                  - dms:DescribeReplicationTasks
                  - dms:StartReplicationTask
                  - dms:StopReplicationTask
                  - dms:TestConnection
                  - dms:DescribeReplicationTasks
                Effect: Allow
                Resource: '*'
              - Action:
                  - ecr:BatchCheckLayerAvailability
                  - ecr:BatchGetImage
                  - ecr:GetDownloadUrlForLayer
                  - ecr:GetAuthorizationToken
                  - ecr:DescribeImages
                Effect: Allow
                Resource: arn:aws:ecr:<account-region>:<account-id>:repository/datalake-emr-serverless
              - Action:
                  - ecr:BatchCheckLayerAvailability
                  - ecr:BatchGetImage
                  - ecr:GetDownloadUrlForLayer
                  - ecr:GetAuthorizationToken
                  - ecr:DescribeImages
                Effect: Allow
                Resource: arn:aws:ecr:<account-region>:<account-id>:repository/datalake-emr-serverless-6.10
              - Action:
                  - ecs:*
                Effect: Allow
                Resource: '*'
              - Action: iam:PassRole
                Condition:
                  StringLike:
                    iam:PassedToService: ecs-tasks.amazonaws.com
                Effect: Allow
                Resource:
                  - '*'
              - Action:
                  - secretsmanager:GetSecretValue
                Effect: Allow
                Resource:
                  - '*'
              - Action:
                  - ssm:GetParameter
                  - ssm:GetParameters
                Effect: Allow
                Resource:
                  - arn:aws:ssm:<account-region>:<account-id>:parameter/n8n/*
                  - arn:aws:ssm:<account-region>:<account-id>:parameter/openmetadata/*
              - Action:
                  - secretsmanager:GetSecretValue
                Effect: Allow
                Resource:
                  - arn:aws:secretsmanager:<account-region>:<account-id>:secret:n8n-key-prod-*
              - Action:
                  - ec2:StartInstances
                  - ec2:StopInstances
                  - ec2:DescribeInstanceStatus
                  - ec2:DescribeInstances
                Effect: Allow
                Resource: '*'
              - Action:
                  - glue:CreateTableOptimizer
                  - glue:GetTable
                Effect: Allow
                Resource: '*'
                Sid: tableOptimzer
            Version: '2012-10-17'
          PolicyName: !Sub 'managed-airflow-service-role-policy-${Environment}'
        - PolicyDocument:
            Statement:
              - Action:
                  - ecs:RunTask
                Effect: Allow
                Resource:
                  - !Sub 'arn:aws:ecs:<account-region>:<account-id>:task-definition/vrt-datalake-dbt-task-definition-${Environment}'
              - Action:
                  - iam:PassRole
                Effect: Allow
                Resource:
                  - !Sub 'arn:aws:iam::<account-id>:role/vrt-dbt-role-${Environment}'
              - Action:
                  - ecs:DescribeTasks
                Effect: Allow
                Resource:
                  - !Sub 'arn:aws:ecs:<account-region>:<account-id>:task/datalake-ecs-cluster-${Environment}/*'
            Version: '2012-10-17'
          PolicyName: run_dbt_policy
        - PolicyDocument:
            Statement:
              - Action:
                  - ecs:RunTask
                Effect: Allow
                Resource:
                  - !Sub 'arn:aws:ecs:<account-region>:<account-id>:task-definition/datahub-ingestion-task-${Environment}'
              - Action:
                  - iam:PassRole
                Effect: Allow
                Resource:
                  - !Sub 'arn:aws:iam::<account-id>:role/datahub-ingestion-task-nonprod-${Environment}'
              - Action:
                  - ecs:DescribeTasks
                Effect: Allow
                Resource:
                  - !Sub 'arn:aws:ecs:<account-region>:<account-id>:task/datalake-ecs-cluster-${Environment}/*'
            Version: '2012-10-17'
          PolicyName: datahub_ingestion_policy
        - PolicyDocument:
            Statement:
              - Action: emr-serverless:*
                Effect: Allow
                Resource: '*'
              - Action:
                  - sts:AssumeRole
                Effect: Allow
                Resource: arn:aws:iam::<account-id>:role/*
              - Action:
                  - iam:PassRole
                Effect: Allow
                Resource:
                  - arn:aws:iam::*:role/*
            Version: '2012-10-17'
          PolicyName: emr_serverless_full_access
        - PolicyDocument:
            Statement:
              - Action:
                  - dynamodb:ExportTableToPointInTime
                  - dynamodb:DescribeExport
                Effect: Allow
                Resource:
                  - !Sub 'arn:aws:dynamodb:<account-region>:<account-id>:table/user-data-${Environment}'
                  - !Sub 'arn:aws:dynamodb:<account-region>:<account-id>:table/user-data-${Environment}/*'
            Version: '2012-10-17'
          PolicyName: dynamo_policy
      RoleName: !Sub 'managed-airflow-v3-test-service-role-${Environment}'
    Type: AWS::IAM::Role
  SecurityEgressManagedAirflowRestricted:
    Properties:
      CidrIp: '0.0.0.0/0'
      GroupId: !GetAtt 'ManagedAirflowSecurityGroupRestricted.GroupId'
      IpProtocol: '-1'
    Type: AWS::EC2::SecurityGroupEgress
  SecurityIngressManagedAirflowRestricted:
    Properties:
      GroupId: !GetAtt 'ManagedAirflowSecurityGroupRestricted.GroupId'
      IpProtocol: '-1'
      SourceSecurityGroupId: !GetAtt 'ManagedAirflowSecurityGroupRestricted.GroupId'
    Type: AWS::EC2::SecurityGroupIngress

If someone has been able to get Airflow version 3.0.6 working on MWAA, would be nice to have a view on your CF template. Just to be clear setting up with the UI works it only fails with cloudformation.

1 Answer
0

When creating an Amazon MWAA environment with Apache Airflow v3.0.6 through CloudFormation, there are several issues that could cause the deployment to fail while the same configuration works through the UI.

Based on the error you're seeing (duplicate key value violates unique constraint "ab_permission_view_permission_id_view_menu_id_uq"), this appears to be related to database initialization issues during the environment creation process.

Here are some troubleshooting steps and potential solutions:

  1. Add a DependsOn statement: When creating an MWAA environment and related resources in the same CloudFormation template, there can be timing issues. Add a DependsOn statement to ensure the execution policy is fully created before the MWAA environment tries to use it:
ManagedAirflowEnvironment:
DependsOn: ManagedAirflowServiceRole
Properties:
...
  1. Check execution role permissions: Ensure your execution role has all the necessary permissions for Amazon S3, CloudWatch, Amazon SQS, and Amazon ECR. The empty "Database VPC endpoint service" and "Celery executor queue ARN" fields suggest there might be permission issues.

  2. Verify VPC network setup: Run the "Verify Environment" script from AWS Support Tools on GitHub to check your Amazon VPC network setup and configuration.

  3. Check Apache Airflow logs: Since you've enabled logging, verify if there are any specific errors in the CloudWatch logs that might provide more insight into the issue.

  4. Validate S3 bucket permissions: Make sure your execution role has the correct permissions to access the S3 bucket where your DAGs, plugins, and requirements are stored.

  5. Ensure proper resource naming: Double-check that the resource names in your CloudFormation template match what you're referencing elsewhere. For example, in your IAM policy, you're referencing arn:aws:airflow:<region>:<account-id>:environment/managed-airflow-vrt-v3-test-${Environment} but your environment name is managed-airflow-v3-test-vrt-${Environment}.

The inconsistent errors suggest there might be race conditions or timing issues during the CloudFormation deployment. Adding appropriate DependsOn statements and ensuring all permissions are correctly set up should help resolve these issues.
Sources
Troubleshooting: Creating and updating an Amazon MWAA environment - Amazon Managed Workflows for Apache Airflow
Troubleshooting: CloudWatch Logs and CloudTrail errors - Amazon Managed Workflows for Apache Airflow
Create an Amazon MWAA environment - Amazon Managed Workflows for Apache Airflow

answered a year ago

AWS
SUPPORT ENGINEER

reviewed a year ago

  • When running the AWS support tools The only error im receiving is the postgres one i mentioned above

    {override.py:1270} ERROR - Add Role: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "ab_role_name_uq"
    

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.