Skip to content

airflow cdk error

-1

#!/usr/bin/env python3 from aws_cdk import ( Stack, RemovalPolicy, aws_ec2 as ec2, aws_iam as iam, aws_s3 as s3, aws_s3_deployment as s3deploy, aws_mwaa as mwaa, ) from constructs import Construct import os

class AirflowStack(Stack): """ MWAA Airflow Stack """

def __init__(
    self,
    scope: Construct,
    construct_id: str,
    *,
    self_vpc: ec2.Vpc,
    **kwargs,
) -> None:
    super().__init__(scope, construct_id, **kwargs)

    airflow_env_name = construct_id.lower()
    dags_bucket_name = f"{construct_id.lower()}-dags"


 #  S3 Bucket for DAGs
 
    dags_bucket = s3.Bucket(
        self,
        "DagsBucket",
        bucket_name=dags_bucket_name,
        versioned=True,
        encryption=s3.BucketEncryption.S3_MANAGED,
        block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
        enforce_ssl=True,
        removal_policy=RemovalPolicy.RETAIN,
    )

    dags_folder = os.path.join(os.getcwd(), "dags")
    if os.path.isdir(dags_folder):
        s3deploy.BucketDeployment(
            self,
            "DeployDags",
            sources=[s3deploy.Source.asset(dags_folder)],
            destination_bucket=dags_bucket,
            destination_key_prefix="dags",
            prune=False,
        )

 
    # MWAA Execution Role (us-east-1 attachable)

    mwaa_role = iam.Role(
        self,
        "ExecutionRole",
        role_name=f"{airflow_env_name}-exec-role",
        assumed_by=iam.CompositePrincipal(
            iam.ServicePrincipal("airflow.amazonaws.com"),
            iam.ServicePrincipal("airflow-env.amazonaws.com"),
        ),
        path="/service-role/",
    )

    # Attach attachable AWS managed policies
    mwaa_role.add_managed_policy(
        iam.ManagedPolicy.from_aws_managed_policy_name("AmazonS3ReadOnlyAccess")
    )
    # Inline policy for DAG bucket read/write
    mwaa_role.add_to_policy(
        iam.PolicyStatement(
            actions=["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
            resources=[dags_bucket.bucket_arn, f"{dags_bucket.bucket_arn}/*"]
        )
    )
    # CloudWatch Logs permissions
    mwaa_role.add_to_policy(
        iam.PolicyStatement(
            actions=[
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents",
            ],
            resources=["*"]
        )
    )

 
    # Security Group (single SG)

    mwaa_sg = ec2.SecurityGroup(
        self,
        "MwaaSecurityGroup",
        vpc=self_vpc,
        description="MWAA Security Group",
        allow_all_outbound=True,
    )
    # Allow internal MWAA traffic
    mwaa_sg.add_ingress_rule(
        peer=mwaa_sg,
        connection=ec2.Port.all_traffic(),
        description="Allow MWAA self traffic",
    )

 
    #  Network Configuration
 
    private_subnets = self_vpc.select_subnets(
        subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS
    ).subnet_ids[:2]

    if len(private_subnets) < 2:
        raise ValueError("MWAA requires at least 2 PRIVATE_WITH_EGRESS subnets")

    network_config = mwaa.CfnEnvironment.NetworkConfigurationProperty(
        security_group_ids=[mwaa_sg.security_group_id],
        subnet_ids=private_subnets,
    )

    #  Logging Configuration

    logging_config = mwaa.CfnEnvironment.LoggingConfigurationProperty(
        dag_processing_logs=mwaa.CfnEnvironment.ModuleLoggingConfigurationProperty(
            enabled=True, log_level="INFO"
        ),
        scheduler_logs=mwaa.CfnEnvironment.ModuleLoggingConfigurationProperty(
            enabled=True, log_level="INFO"
        ),
        task_logs=mwaa.CfnEnvironment.ModuleLoggingConfigurationProperty(
            enabled=True, log_level="INFO"
        ),
        webserver_logs=mwaa.CfnEnvironment.ModuleLoggingConfigurationProperty(
            enabled=True, log_level="INFO"
        ),
        worker_logs=mwaa.CfnEnvironment.ModuleLoggingConfigurationProperty(
            enabled=True, log_level="INFO"
        ),
    )

    
    #  MWAA Environment

    mwaa_env = mwaa.CfnEnvironment(
        self,
        "AirflowEnvironment",
        name=airflow_env_name,
        airflow_version="3.0.6",
        environment_class="mw1.micro",
        execution_role_arn=mwaa_role.role_arn,
        source_bucket_arn=dags_bucket.bucket_arn,
        dag_s3_path="dags",
        network_configuration=network_config,
        logging_configuration=logging_config,
        webserver_access_mode="PRIVATE_ONLY",
        min_workers=1,
        max_workers=1,
    )


    #  Airflow Config Options
 
    mwaa_env.add_override(
        "Properties.AirflowConfigurationOptions",
        {
            "core.load_default_connections": "False",
            "core.load_examples": "False",
            "core.default_timezone": "utc",
        },
    )

    mwaa_env.node.add_dependency(dags_bucket)
    mwaa_env.node.add_dependency(mwaa_role)

used above cdk to deploy airflow got below error | CREATE_FAILED | AWS::MWAA::Environment | AirflowEnvironment Resource handler returned message: "Creation failed" (RequestToken: d84adf33-f484-831e-8b13-7155bbc1f7b7, HandlerErrorCode: NotStabilized)

suggest for cdk code

1 Answer
0

Based on the error you're encountering with your MWAA (Managed Workflows for Apache Airflow) CDK deployment, there are several potential issues that could be causing the "Creation failed" error with the "NotStabilized" handler error code.

Here are some suggestions to fix your CDK code:

  1. Region-specific subnet configuration: Make sure your VPC has at least two private subnets in different Availability Zones. MWAA requires subnets in at least two AZs for high availability.

  2. S3 bucket configuration: Your S3 bucket for DAGs might need additional configuration. Ensure the bucket is in the same region as your MWAA environment.

  3. IAM permissions: The execution role might need additional permissions. Consider adding the following managed policies:

  • AmazonMWAAFullConsoleAccess
  • AmazonMWAASvcRolePolicy
  1. Security Group configuration: Your security group allows all outbound traffic, but MWAA might need specific inbound rules for its components to communicate.

  2. Airflow version: You're using version 3.0.6, which is valid, but consider using the latest supported version (2.5.1 or 2.6.3) if you continue to have issues.

  3. Requirements file: Add a requirements.txt file in your S3 bucket to specify Python dependencies.

Here's a modified version of your code that addresses these potential issues:

# MWAA Execution Role with enhanced permissions
mwaa_role = iam.Role(
self,
"ExecutionRole",
role_name=f"{airflow_env_name}-exec-role",
assumed_by=iam.CompositePrincipal(
iam.ServicePrincipal("airflow.amazonaws.com"),
iam.ServicePrincipal("airflow-env.amazonaws.com"),
),
path="/service-role/",
)

# Add more comprehensive permissions
mwaa_role.add_managed_policy(
iam.ManagedPolicy.from_aws_managed_policy_name("AmazonMWAASvcRolePolicy")
)
mwaa_role.add_managed_policy(
iam.ManagedPolicy.from_aws_managed_policy_name("AmazonS3FullAccess")
)

# Ensure your VPC has the required endpoints or NAT gateways for MWAA to access AWS services
# MWAA Environment with updated configuration
mwaa_env = mwaa.CfnEnvironment(
self,
"AirflowEnvironment",
name=airflow_env_name,
airflow_version="2.5.1",  # Consider using a well-established version
environment_class="mw1.small",  # Consider using a larger instance for stability
execution_role_arn=mwaa_role.role_arn,
source_bucket_arn=dags_bucket.bucket_arn,
dag_s3_path="dags",
network_configuration=network_config,
logging_configuration=logging_config,
webserver_access_mode="PRIVATE_ONLY",
min_workers=1,
max_workers=2,
)

Additionally, check your CloudWatch logs for more specific error messages that might help identify the exact cause of the failure. The "NotStabilized" error typically means that the resource creation process started but couldn't complete successfully, which could be due to networking issues, permissions problems, or resource constraints.
Sources
Community | How to host a Plotly Dash app on AWS ECS

answered a year ago

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.