使用 AWS ECS TaskDefinition 中的 ExecutionRoleArn 字段来启用 ECS 自动缩放服务,然后编写适当的 Lambda 函数以便自动缩放 ECS 服务。
示例代码:
首先,定义 ECS 服务的 ExecutionRoleArn 字段:
{ "containerDefinitions": [ { "name": "myContainer", "image": "myImage", "cpu": "256", "memory": "512", "portMappings": [ { "containerPort": "80", "protocol": "HTTP" } ] } ], "executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole", "family": "myTaskDefinition" }
其次,创建 Lambda 函数并编写代码以获取服务的 CPU 利用率、缩放策略和最大容量,然后更新服务:
import boto3 import os
client = boto3.client('ecs')
def lambda_handler(event, context): response = client.describe_services( cluster=os.environ['ECS_CLUSTER_NAME'], services=[os.environ['ECS_SERVICE_NAME']] ) service = response['services'][0] cpu_utilization = service['cpuUtilization'] scaling_policies = service['scalingPolicies'] maximum_capacity = service['maximumPercent'] if cpu_utilization < 30 and maximum_capacity > 50 and scaling_policies: response = client.update_service( cluster=os.environ['ECS_CLUSTER_NAME'], service=os.environ['ECS_SERVICE_NAME'], desiredCount=max(int(service['desiredCount'] / 2), 1), scalingStrategy=[{ 'policyName': scaling_policies[0]['policyName'], 'adjustmentType': 'CHANGE_IN_CAPACITY', 'scalingAdjustment': -50, 'cooldown': 60 }] )