Amazon Elastic Container Service (ECS)

Amazon Elastic Container Service (Amazon ECS) is a fully managed container orchestration service that makes it easy for you to deploy, manage, and scale containerized applications.

Airflow provides operators to run Task Definitions on an ECS cluster.

Prerequisite Tasks

To use these operators, you must do a few things:

Operators

Create an AWS ECS Cluster

To create an Amazon ECS cluster you can use EcsCreateClusterOperator.

All optional parameters to be passed to the Create Cluster API should be passed in the ‘create_cluster_kwargs’ dict.

airflow/providers/amazon/aws/example_dags/example_ecs.py[source]

create_cluster = EcsCreateClusterOperator(
    task_id='create_cluster',
    cluster_name=cluster_name,
    wait_for_completion=False,
)

Delete an AWS ECS Cluster

To delete an Amazon ECS cluster you can use EcsDeleteClusterOperator.

airflow/providers/amazon/aws/example_dags/example_ecs.py[source]

delete_cluster = EcsDeleteClusterOperator(
    task_id='delete_cluster',
    trigger_rule=TriggerRule.ALL_DONE,
    cluster_name=cluster_name,
    wait_for_completion=False,
)

Register a Task Definition

To register a task definition you can use EcsRegisterTaskDefinitionOperator.

All optional parameters to be passed to the Register Task Definition API should be passed in the ‘register_task_kwargs’ dict.

airflow/providers/amazon/aws/example_dags/example_ecs.py[source]

register_task = EcsRegisterTaskDefinitionOperator(
    task_id='register_task',
    family=family_name,
    container_definitions=[
        {
            'name': container_name,
            'image': 'ubuntu',
            'workingDirectory': '/usr/bin',
            'entryPoint': ['sh', '-c'],
            'command': ['ls'],
        }
    ],
    register_task_kwargs={
        'cpu': '256',
        'memory': '512',
        'networkMode': 'awsvpc',
    },
)

Deregister a Task Definition

To deregister a task definition you can use EcsDeregisterTaskDefinitionOperator.

airflow/providers/amazon/aws/example_dags/example_ecs.py[source]

deregister_task = EcsDeregisterTaskDefinitionOperator(
    task_id='deregister_task',
    trigger_rule=TriggerRule.ALL_DONE,
    task_definition=register_task.output,
)

Run a Task Definition

To run a Task Definition defined in an Amazon ECS cluster you can use EcsRunTaskOperator.

You need to have created your ECS Cluster, and have created a Task Definition before you can use this Operator. The Task Definition contains details of the containerized application you want to run.

This Operator support running your containers in ECS Clusters that are either Serverless (FARGATE), via EC2, or via external resources (EXTERNAL). The parameters you need to configure for this Operator will depend upon which launch_type you want to use.

launch_type="EC2|FARGATE|EXTERNAL"
  • If you are using AWS Fargate as your compute resource in your ECS Cluster, set the parameter launch_type to FARGATE. When using a launch type of FARGATE you will need to provide network_configuration parameters.

  • If you are using EC2 as the compute resources in your ECS Cluster, set the parameter to EC2.

  • If you have integrated external resources in your ECS Cluster, for example using ECS Anywhere, and want to run your containers on those external resources, set the parameter to EXTERNAL.

airflow/providers/amazon/aws/example_dags/example_ecs.py[source]

run_task = EcsRunTaskOperator(
    task_id="run_task",
    cluster=EXISTING_CLUSTER_NAME,
    task_definition=register_task.output,
    launch_type="EC2",
    overrides={
        "containerOverrides": [
            {
                "name": container_name,
                "command": ["echo", "hello", "world"],
            },
        ],
    },
    network_configuration={'awsvpcConfiguration': {'subnets': SUBNETS}},
    tags={
        "Customer": "X",
        "Project": "Y",
        "Application": "Z",
        "Version": "0.0.1",
        "Environment": "Development",
    },
    awslogs_group="/ecs/hello-world",
    awslogs_region='us-east-1',
    awslogs_stream_prefix="ecs/hello-world-container",
    # NOTE: You must set `reattach=True` in order to get ecs_task_arn if you plan to use a Sensor.
    reattach=True,
)

tests/system/providers/amazon/aws/example_ecs_fargate.py[source]

hello_world = EcsOperator(
    task_id='hello_world',
    cluster=cluster_name,
    task_definition=task_definition_name,
    launch_type='FARGATE',
    overrides={
        'containerOverrides': [
            {
                'name': container_name,
                'command': ['echo', 'hello', 'world'],
            },
        ],
    },
    network_configuration={
        'awsvpcConfiguration': {
            'subnets': test_context[SUBNETS_KEY],
            'securityGroups': test_context[SECURITY_GROUPS_KEY],
        },
    },
)

Stream logs to AWS CloudWatch

To stream logs to AWS CloudWatch, you need to define the parameters below. Using the example above, we would add these additional parameters to enable logging to CloudWatch. You need to ensure that you have the appropriate level of permissions (see next section).

airflow/providers/amazon/aws/example_dags/example_ecs.py[source]

    awslogs_group="/ecs/hello-world",
    awslogs_region='us-east-1',
    awslogs_stream_prefix="ecs/hello-world-container",

IAM Permissions

You need to ensure you have the following IAM permissions to run tasks via this operator. In this example, the operator will have permissions to run tasks on an ECS Cluster called “cluster a” in a specific AWS region and account.

{
    "Effect": "Allow",
    "Action": [
        "ecs:RunTask",
        "ecs:DescribeTasks"
    ],
    "Resource": : [ "arn:aws:ecs:{aws region}:{aws account number}:cluster/{custer a}"
}

If you use the “reattach=True” (the default is False), you need to add further permissions. You need to add the following additional Actions to the IAM policy.

"ecs:DescribeTaskDefinition",
"ecs:ListTasks"

CloudWatch Permissions

If you plan on streaming Apache Airflow logs into AWS CloudWatch, you need to ensure that you have configured the appropriate permissions set.

iam.PolicyStatement(
    actions=[
        "logs:CreateLogStream",
        "logs:CreateLogGroup",
        "logs:PutLogEvents",
        "logs:GetLogEvents",
        "logs:GetLogRecord",
        "logs:GetLogGroupFields",
        "logs:GetQueryResults"
    ],
    effect=iam.Effect.ALLOW,
    resources=[
        "arn:aws:logs:{aws region}:{aws account number}:log-group:{aws-log-group-name}:log-stream:{aws-log-stream-name}/\*"
        ]
)

Sensors

AWS ECS Cluster State Sensor

To poll the cluster state until it reaches a terminal state you can use EcsClusterStateSensor.

Defaults to EcsClusterStates.ACTIVE as a success state and no failure state, both can be overridden with provided values. Raises an AirflowException with the failure reason if a failed state is provided and that state is reached before the target state.

airflow/providers/amazon/aws/example_dags/example_ecs.py[source]

await_cluster = EcsClusterStateSensor(
    task_id='await_cluster',
    cluster_name=cluster_name,
)

AWS ECS Task Definition State Sensor

To poll the task definition state until it reaches a terminal state you can use EcsTaskDefinitionStateSensor.

Valid states are either EcsTaskDefinitionStates.ACTIVE or EcsTaskDefinitionStates.INACTIVE. Defaults to EcsTaskDefinitionStates.ACTIVE as the success state, but accepts a parameter to change that. Raises an AirflowException with the failure reason if the failed state is reached before the target state.

airflow/providers/amazon/aws/example_dags/example_ecs.py[source]

await_task_definition = EcsTaskDefinitionStateSensor(
    task_id='await_task_definition',
    task_definition=register_task.output,
)

AWS ECS Task State Sensor

To poll the task state until it reaches a terminal state you can use EcsTaskStateSensor.

Defaults to EcsTaskStates.RUNNING as the success state and no failure state, both can be overridden with provided values. Raises an AirflowException with the failure reason if a failed state is provided and that state is reached before the target state.

airflow/providers/amazon/aws/example_dags/example_ecs.py[source]

# By default, EcsTaskStateSensor waits until the task has started, but the
# demo task runs so fast that the sensor misses it.  This sensor instead
# demonstrates how to wait until the ECS Task has completed by providing
# the target_state and failure_states parameters.
await_task_finish = EcsTaskStateSensor(
    task_id='await_task_finish',
    cluster=EXISTING_CLUSTER_NAME,
    task='{{ ti.xcom_pull(key="ecs_task_arn") }}',
    target_state=EcsTaskStates.STOPPED,
    failure_states={EcsTaskStates.NONE},
)

Was this entry helpful?