lambda から ECS を実行する方法をメモします。
設定
環境変数
キー | 値 | 備考 |
AWSVPC_CONF_SECURITY_GROUPS | sg-xxxxxxxxxxxxx | AWSVPCの設定 |
AWSVPC_CONF_SUBNETS | subnet-xxxxxxxxxxxxx | AWSVPCの設定 |
ECS_CLUSTER | sample-ecs-dev | ECSのクラスター名 |
TASK_DEFINITION_ARN | arn:aws:ecs:ap-northeast-1:xxxxx:task-definition/sample-ecs-dev:5 | ECSのタスク定義のARN |
コード
import boto3 import json import logging import os import sys logger = logging.getLogger() for h in logger.handlers: logger.removeHandler(h) h = logging.StreamHandler(sys.stdout) FORMAT = '%(levelname)s [%(funcName)s] %(message)s' h.setFormatter(logging.Formatter(FORMAT)) logger.addHandler(h) logger.setLevel(logging.INFO) ecs = boto3.client('ecs') def lambda_handler(event, context): for record in event['Records']: payload = record["body"] params = json.loads(payload) logger.info(f"ECS_CLUSTER: {os.environ['ECS_CLUSTER']}") logger.info(f"TASK_DEFINITION_ARN: {os.environ['TASK_DEFINITION_ARN']}") response = ecs.run_task( cluster=os.environ['ECS_CLUSTER'], taskDefinition=os.environ['TASK_DEFINITION_ARN'], launchType='FARGATE', networkConfiguration = { 'awsvpcConfiguration': { 'subnets': os.environ['AWSVPC_CONF_SUBNETS'].split(','), 'securityGroups': os.environ['AWSVPC_CONF_SECURITY_GROUPS'].split(','), 'assignPublicIp': 'ENABLED' } }, overrides={ 'containerOverrides': [ { 'name': "sample-ecr-dev", 'command': ["python", "sample.py"], 'memory': 128, "environment": [ {"name": "PARAMS", "value": json.dumps(params)} ] } ] } ) logger.info(f"response: {response}") failures = response['failures'] if len(failures) != 0: logging.error(failures)