View a markdown version of this page

AWSSDK 또는 CLI와 RegisterTaskDefinition 함께 사용 - AWSSDK 코드 예제

Doc AWSSDK 예제 GitHub 리포지토리에서 더 많은 SDK 예제를 사용할 수 있습니다. AWS

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

AWSSDK 또는 CLI와 RegisterTaskDefinition 함께 사용

다음 코드 예제는 RegisterTaskDefinition의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

CLI
AWS CLI

예시 1: JSON 파일에 작업 정의를 등록하려면

다음 register-task-definition 예시에서는 지정된 패밀리에 작업 정의를 등록합니다. 컨테이너 정의는 지정된 파일 위치에 JSON 형식으로 저장됩니다.

aws ecs register-task-definition \ --cli-input-json file://<path_to_json_file>/sleep360.json

sleep360.json의 콘텐츠:

{ "containerDefinitions": [ { "name": "sleep", "image": "busybox", "cpu": 10, "command": [ "sleep", "360" ], "memory": 10, "essential": true } ], "family": "sleep360" }

출력:

{ "taskDefinition": { "status": "ACTIVE", "family": "sleep360", "placementConstraints": [], "compatibilities": [ "EXTERNAL", "EC2" ], "volumes": [], "taskDefinitionArn": "arn:aws:ecs:us-east-1:123456789012:task-definition/sleep360:1", "containerDefinitions": [ { "environment": [], "name": "sleep", "mountPoints": [], "image": "busybox", "cpu": 10, "portMappings": [], "command": [ "sleep", "360" ], "memory": 10, "essential": true, "volumesFrom": [] } ], "revision": 1 } }

자세한 내용은 Amazon ECS 개발자 안내서의 작업 정의 예시 섹션을 참조하세요.

예시 2: JSON 문자열 파라미터로 작업 정의 등록

다음 register-task-definition 예시에서는 이스케이프된 큰따옴표로 묶인 JSON 문자열 파라미터로 제공된 컨테이너 정의를 사용하여 작업 정의를 등록합니다.

aws ecs register-task-definition \ --family sleep360 \ --container-definitions "[{\"name\":\"sleep\",\"image\":\"busybox\",\"cpu\":10,\"command\":[\"sleep\",\"360\"],\"memory\":10,\"essential\":true}]"

출력은 이전 예시와 동일합니다.

자세한 내용은 Amazon ECS 개발자 안내서의 작업 정의 생성 섹션을 참조하세요.

Python
SDK for Python(Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

class EcsWrapper: """Encapsulates Amazon ECS operations.""" def __init__(self, ecs_client: BaseClient): """ Initializes the EcsWrapper with an ECS client. :param ecs_client: A Boto3 Amazon ECS client. Boto3 clients are created by the ``boto3.client`` factory function and are instances of ``botocore.client.BaseClient``, which is the correct type to annotate here (``boto3.client`` itself is a function, not a type). """ self.ecs_client = ecs_client @classmethod def from_client(cls) -> "EcsWrapper": """Creates an EcsWrapper using a default Boto3 ECS client.""" ecs_client = boto3.client("ecs") return cls(ecs_client) def register_task_definition( self, family: str, execution_role_arn: str, container_definitions: Optional[List[Dict[str, Any]]] = None, cpu: str = "256", memory: str = "512", ) -> Dict[str, Any]: """ Registers a new task definition for Fargate. :param family: The family name for the task definition. :param execution_role_arn: The ARN of the task execution IAM role. :param container_definitions: List of container definitions. If None, a default httpd container is used. :param cpu: The task-level CPU units (e.g., '256'). :param memory: The task-level memory in MiB (e.g., '512'). :return: The task definition details from the response. :raises ClientError: If the request fails (e.g., InvalidParameterException). """ if container_definitions is None: container_definitions = [ { "name": "sample-app", "image": "public.ecr.aws/docker/library/httpd:2.4", "essential": True, "portMappings": [ { "containerPort": 80, "hostPort": 80, "protocol": "tcp", } ], "cpu": 256, "memory": 512, } ] try: response = self.ecs_client.register_task_definition( family=family, networkMode="awsvpc", requiresCompatibilities=["FARGATE"], cpu=cpu, memory=memory, executionRoleArn=execution_role_arn, containerDefinitions=container_definitions, ) task_def = response["taskDefinition"] logger.info( "Registered task definition '%s' revision %s, ARN: %s", task_def["family"], task_def["revision"], task_def["taskDefinitionArn"], ) return task_def except ClientError as err: if err.response["Error"]["Code"] == "InvalidParameterException": logger.error( "Invalid parameter when registering task definition '%s': %s", family, err.response["Error"]["Message"], ) raise