文件AWS開發套件範例 GitHub 儲存庫中有更多可用的 AWSSDK 範例
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
RegisterTaskDefinition 搭配 AWSSDK 或 CLI 使用
下列程式碼範例示範如何使用 RegisterTaskDefinition。
動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:
- CLI
-
- AWS CLI
-
範例 1:使用 JSON 檔案註冊任務定義
下列
register-task-definition範例會將任務定義註冊到指定的系列。容器定義會以 JSON 格式儲存在指定的檔案位置。aws ecs register-task-definition \ --cli-input-jsonfile://<path_to_json_file>/sleep360.jsonsleep360.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 \ --familysleep360\ --container-definitions "[{\"name\":\"sleep\",\"image\":\"busybox\",\"cpu\":10,\"command\":[\"sleep\",\"360\"],\"memory\":10,\"essential\":true}]"輸出與上一個範例相同。
如需詳細資訊,請參閱《Amazon ECS 開發人員指南》中的建立任務定義。
-
如需 API 詳細資訊,請參閱《AWS CLI 命令參考》中的 RegisterTaskDefinition
。
-
- Python
-
- 適用於 Python 的 SDK (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-
如需 API 詳細資訊,請參閱《適用於 AWSPython (Boto3) 的 SDK API 參考》中的 RegisterTaskDefinition。
-
ListTasks
RunTask