Search code examples
pythonamazon-web-servicesboto3amazon-iamamazon-ecs

How to set value for executionRoleArn in boto3?


I am new to AWS and I cannot figure out how to successfully run a task in Fargate using an image from ECR using Python boto3. Here's what I do:

create the client

ecs_cli = boto3.client(
    'ecs',
    aws_access_key_id=access_key,
    aws_secret_access_key=secret_key,
    region_name=region
)

register a task definition

response = ecs_cli.register_task_definition(
    family='what_is_family_06_06', #i dont get what's a family
    networkMode='awsvpc',
    containerDefinitions=[
    {
        "name": "rand_name_06_06",
        "image": image_name,
    }
    ],
    cpu = "256",
    memory = "512",
    requiresCompatibilities=['FARGATE']

)

and run the task

response = ecs_cli.run_task(
cluster='default',
launchType='FARGATE',
networkConfiguration={
    'awsvpcConfiguration': {
        'subnets': [
            'subnet-03fc922da97e2d95e',
            'subnet-08a73abb757cf2fab'
        ],
        'securityGroups': [
            'sg-04a3379a63a69cb74',
        ],
    }
},
taskDefinition='arn:aws:ecs:us-east-1:420295140958:task-definition/what_is_family_06_06:1',                  
)

I get this error:

"Fargate requires task definition to have execution role ARN to support ECR images."

That means I have to add executionRoleArn='something' to register_task_definition()

However in e.g., this tutorial, there is no mention of executionRoleARN in Task Definition and in the boto3 docs for creating a task definition it doesn't say what specifically the value of executionRoleARN should be.

I've looked at Optional IAM Permissions for Fargate Tasks Pulling Amazon ECR Images but that did not help me.

I have created the IAM Admin User following this tutorial.


Solution

  • The reason that executionRoleArn is required, is because the image in the container definition(s) is from ECR which is a private repository.

    ECS include the base execution task role policy here.

    You can either modify this and create a new policy or attach the managed policy of AmazonECSTaskExecutionRolePolicy to your IAM role.

    It is important when you create it, that it is created with a trust relationship for ecs-tasks.amazonaws.com.

    Once you've created the role get its Arn, this is accessible from either the console or via the list-roles command on the CLI.

    Take this arn and add to register_task_definition as shown below

    response = ecs_cli.register_task_definition(
        family='what_is_family_06_06', #i dont get what's a family
        networkMode='awsvpc',
        containerDefinitions=[
        {
            "name": "rand_name_06_06",
            "image": image_name,
        }
        ],
        cpu = "256",
        memory = "512",
        requiresCompatibilities=['FARGATE'],
        executionRoleArn='ARN'
    )