要解决“AWS ECS服务错误:必须启用任务长ARN格式才能使用ECS托管标签启动服务任务。”错误,您需要将任务ARN格式更改为长ARN格式。以下是一个代码示例,演示如何创建使用长ARN格式的任务定义和服务。
import boto3
# 创建 ECS 客户端
ecs_client = boto3.client('ecs')
# 创建任务定义
response = ecs_client.register_task_definition(
family='my-task-definition',
containerDefinitions=[
{
'name': 'my-container',
'image': 'my-container-image',
'essential': True
},
],
requiresCompatibilities=[
'FARGATE',
],
networkMode='awsvpc',
cpu='256',
memory='512'
)
# 获取任务定义 ARN
task_definition_arn = response['taskDefinition']['taskDefinitionArn']
# 创建服务
response = ecs_client.create_service(
cluster='my-cluster',
serviceName='my-service',
taskDefinition=task_definition_arn,
desiredCount=1,
launchType='FARGATE',
networkConfiguration={
'awsvpcConfiguration': {
'subnets': ['subnet-abc123'],
'securityGroups': ['sg-abc123'],
'assignPublicIp': 'ENABLED'
}
}
)
# 打印服务 ARN
service_arn = response['service']['serviceArn']
print(service_arn)
确保在创建任务定义和服务时使用长ARN格式。此示例中的关键点是使用 register_task_definition
和 create_service
方法,同时使用长ARN格式提供任务定义和服务的ARN。