

Doc AWSSDK 예제 GitHub 리포지토리에서 더 많은 SDK 예제를 사용할 수 있습니다. [AWS](https://github.com/awsdocs/aws-doc-sdk-examples) 

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

# AWSSDK 또는 CLI와 `RegisterTaskDefinition` 함께 사용
<a name="ecs_example_ecs_RegisterTaskDefinition_section"></a>

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

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
+  [컨테이너 서비스 연결 구성](ecs_example_ecs_ServiceConnect_085_section.md) 
+  [서버리스 시작 유형에 대한 컨테이너 작업 생성](ecs_example_ecs_GettingStarted_086_section.md) 
+  [가상 머신 인스턴스에 대한 컨테이너 서비스 생성](ecs_example_ecs_GettingStarted_018_section.md) 
+  [Amazon ECS 기본 사항 알아보기](ecs_example_ecs_Scenario_section.md) 

------
#### [ 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 개발자 안내서*의 [작업 정의 예시](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/example_task_definitions.html) 섹션을 참조하세요.  
**예시 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 개발자 안내서*의 [작업 정의 생성](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-task-definition.html) 섹션을 참조하세요.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [RegisterTaskDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/register-task-definition.html) 섹션을 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예제 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ecs#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
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
```
+  API 세부 정보는 SDK for Python (Boto3) API 참조의 [RegisterTaskDefinition](https://docs.aws.amazon.com/goto/boto3/ecs-2014-11-13/RegisterTaskDefinition)을 참조하세요. *AWS* 

------