# This file is automatically generated by botocraft.  Do not edit directly.
# mypy: disable-error-code="index, override, assignment, union-attr, misc"
from botocraft.mixins.tags import TagsDictMixin
from typing import ClassVar, Type, Optional, Literal, Dict, List, Union, Any, cast
from botocraft.mixins.ecs import ecs_task_populate_taskDefinition
from botocraft.mixins.ecs import ecs_container_instances_only
from botocraft.mixins.ecs import ecs_task_definition_delete_all
from botocraft.mixins.ecs import TaskDefinitionManagerMixin
from botocraft.mixins.ecs import ECSServiceModelMixin
from botocraft.services.ec2 import NetworkInterface
from botocraft.mixins.ecs import ecs_clusters_only
from botocraft.services.application_autoscaling import (
    ScalableTarget,
    ScalableTargetManager,
)
from .abstract import (
    Boto3Model,
    ReadonlyBoto3Model,
    PrimaryBoto3Model,
    ReadonlyPrimaryBoto3Model,
    Boto3ModelManager,
    ReadonlyBoto3ModelManager,
)
from botocraft.mixins.ecs import ecs_service_deployments_only
from botocraft.mixins.ecs import ecs_services_only
from botocraft.mixins.ecs import TaskDefinitionModelMixin
from collections import OrderedDict
from botocraft.mixins.ecs import ecs_tasks_only
from botocraft.mixins.ecs import ecs_task_populate_taskDefinitions
from datetime import datetime
from pydantic import Field
from botocraft.mixins.ecs import ECSServiceManagerMixin
from botocraft.mixins.ecs import ECSContainerInstanceModelMixin
from .abstract import PrimaryBoto3ModelQuerySet
from botocraft.mixins.ecs import ecs_task_definition_include_tags
from botocraft.services.ec2 import Instance, InstanceManager
from botocraft.mixins.ecs import ecs_task_definitions_only
from functools import cached_property
from botocraft.services.elbv2 import TargetGroup, TargetGroupManager

# ===============
# Managers
# ===============


class ServiceManager(ECSServiceManagerMixin, Boto3ModelManager):
    service_name: str = "ecs"

    def create(
        self,
        model: "Service",
        clientToken: str | None = None,
        serviceConnectConfiguration: Optional["ServiceConnectConfiguration"] = None,
        volumeConfigurations: List["ServiceVolumeConfiguration"] | None = None,
        vpcLatticeConfigurations: List["VpcLatticeConfiguration"] | None = None,
    ) -> "Service":
        """
        Create an ECS service.

        Args:
            model: The :py:class:`Service` to create.

        Keyword Args:
            clientToken: An identifier that you provide to ensure the idempotency of the request. It must be unique and is case
                sensitive. Up to 36 ASCII characters in the range of 33-126 (inclusive) are allowed.
            serviceConnectConfiguration: The configuration for this service to discover and connect to services, and be
                discovered by, and connected from, other services within a namespace.
            volumeConfigurations: The configuration for a volume specified in the task definition as a volume that is configured
                at launch time. Currently, the only supported volume type is an Amazon EBS volume.
            vpcLatticeConfigurations: The VPC Lattice configuration for the service being created.
        """
        data = model.model_dump(exclude_none=True, by_alias=True)
        args = dict(
            serviceName=data.get("serviceName"),
            cluster=data.get("clusterArn"),
            taskDefinition=data.get("taskDefinition"),
            availabilityZoneRebalancing=data.get("availabilityZoneRebalancing"),
            loadBalancers=data.get("loadBalancers"),
            serviceRegistries=data.get("serviceRegistries"),
            desiredCount=data.get("desiredCount"),
            clientToken=self.serialize(clientToken),
            launchType=data.get("launchType"),
            capacityProviderStrategy=data.get("capacityProviderStrategy"),
            platformVersion=data.get("platformVersion"),
            role=data.get("roleArn"),
            deploymentConfiguration=data.get("deploymentConfiguration"),
            placementConstraints=data.get("placementConstraints"),
            placementStrategy=data.get("placementStrategy"),
            networkConfiguration=data.get("networkConfiguration"),
            healthCheckGracePeriodSeconds=data.get("healthCheckGracePeriodSeconds"),
            schedulingStrategy=data.get("schedulingStrategy"),
            deploymentController=data.get("deploymentController"),
            tags=data.get("tags"),
            enableECSManagedTags=data.get("enableECSManagedTags"),
            propagateTags=data.get("propagateTags"),
            enableExecuteCommand=data.get("enableExecuteCommand"),
            serviceConnectConfiguration=self.serialize(serviceConnectConfiguration),
            volumeConfigurations=self.serialize(volumeConfigurations),
            vpcLatticeConfigurations=self.serialize(vpcLatticeConfigurations),
        )
        _response = self.client.create_service(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = CreateServiceResponse(**_response)

        self.sessionize(response.service)
        return cast("Service", response.service)

    def delete(
        self, service: str, *, cluster: str | None = None, force: bool = False
    ) -> "Service":
        """
        Delete an ECS service.

        Args:
            service: The name of the service to delete.

        Keyword Args:
            cluster: The short name or full Amazon Resource Name (ARN) of the cluster that hosts the service to delete. If you
                do not specify a cluster, the default cluster is assumed.
            force: If ``true``, allows you to delete a service even if it wasn't scaled down to zero tasks. It's only necessary
                to use this if the service uses the ``REPLICA`` scheduling strategy.
        """
        args: Dict[str, Any] = dict(
            service=self.serialize(service),
            cluster=self.serialize(cluster),
            force=self.serialize(force),
        )
        _response = self.client.delete_service(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DeleteServiceResponse(**_response)
        return cast("Service", response.service)

    def get(
        self,
        service: str,
        *,
        cluster: str | None = None,
        include: List[Literal["TAGS"]] | None = None,
    ) -> Optional["Service"]:
        """
        Describes the specified services running in your cluster.

        Args:
            service: The name or full Amazon Resource Name (ARN) of the service to describe.

        Keyword Args:
            cluster: The short name or full Amazon Resource Name (ARN)the cluster that hosts the service to describe. If you do
                not specify a cluster, the default cluster is assumed. This parameter is required if the service or services you are
                describing were launched in any cluster other than the default cluster.
            include: Determines whether you want to see the resource tags for the service. If ``TAGS`` is specified, the tags
                are included in the response. If this field is omitted, tags aren't included in the response.
        """
        args: Dict[str, Any] = dict(
            services=self.serialize([service]),
            cluster=self.serialize(cluster),
            include=self.serialize(include),
        )
        _response = self.client.describe_services(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DescribeServicesResponse(**_response)

        if response and response.services:
            self.sessionize(response.services[0])
            return response.services[0]
        return None

    def get_many(
        self,
        services: List[str],
        *,
        cluster: str = "default",
        include: List[Literal["TAGS"]] | None = None,
    ) -> Union[PrimaryBoto3ModelQuerySet, "DescribeServicesResponse"] | None:
        """
        Describes the specified services running in your cluster.

        Args:
            services: A list of services to describe. You may specify up to 10 services to describe in a single operation.

        Keyword Args:
            cluster: The short name or full Amazon Resource Name (ARN)the cluster that hosts the service to describe. If you do
                not specify a cluster, the default cluster is assumed. This parameter is required if the service or services you are
                describing were launched in any cluster other than the default cluster.
            include: Determines whether you want to see the resource tags for the service. If ``TAGS`` is specified, the tags
                are included in the response. If this field is omitted, tags aren't included in the response.
        """
        args: Dict[str, Any] = dict(
            services=self.serialize(services),
            cluster=self.serialize(cluster),
            include=self.serialize(include),
        )
        _response = self.client.describe_services(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DescribeServicesResponse(**_response)

        if response.services:
            self.sessionize(response.services)
            return PrimaryBoto3ModelQuerySet(response.services)
        return PrimaryBoto3ModelQuerySet([])

    @ecs_services_only
    def list(
        self,
        *,
        cluster: str | None = None,
        launchType: Literal["EC2", "FARGATE", "EXTERNAL", "MANAGED_INSTANCES"] | None = None,
        schedulingStrategy: Literal["REPLICA", "DAEMON"] | None = None,
    ) -> List[str]:
        """
        Returns a list of services. You can filter the results by cluster, launch type,
        and scheduling strategy.

        Keyword Args:
            cluster: The short name or full Amazon Resource Name (ARN) of the cluster to use when filtering the ``ListServices``
                results. If you do not specify a cluster, the default cluster is assumed.
            launchType: The launch type to use when filtering the ``ListServices`` results.
            schedulingStrategy: The scheduling strategy to use when filtering the ``ListServices`` results.
        """
        paginator = self.client.get_paginator("list_services")
        args: Dict[str, Any] = dict(
            cluster=self.serialize(cluster),
            launchType=self.serialize(launchType),
            schedulingStrategy=self.serialize(schedulingStrategy),
        )
        response_iterator = paginator.paginate(
            **{k: v for k, v in args.items() if v is not None}
        )
        results = []
        for _response in response_iterator:
            if list(_response.keys()) == ["ResponseMetadata"]:
                break
            if "ResponseMetadata" in _response:
                del _response["ResponseMetadata"]
            response = ListServicesResponse(**_response)
            if response.serviceArns:
                results.extend(response.serviceArns)
            else:
                if getattr(response, "NextToken", None):
                    continue
                break
        self.sessionize(results)
        if results and isinstance(results[0], Boto3Model):
            return PrimaryBoto3ModelQuerySet(results)
        return results

    def update(
        self,
        model: "Service",
        forceNewDeployment: bool = False,
        serviceConnectConfiguration: Optional["ServiceConnectConfiguration"] = None,
        volumeConfigurations: List["ServiceVolumeConfiguration"] | None = None,
        vpcLatticeConfigurations: List["VpcLatticeConfiguration"] | None = None,
    ) -> "Service":
        """
        Modifies the parameters of a service.

        Args:
            model: The :py:class:`Service` to update.

        Keyword Args:
            forceNewDeployment: Determines whether to force a new deployment of the service. By default, deployments aren't
                forced. You can use this option to start a new deployment with no service definition changes. For example, you can
                update a service's tasks to use a newer Docker image with the same image/tag combination (``my_image:latest``) or to
                roll Fargate tasks onto a newer platform version.
            serviceConnectConfiguration: The configuration for this service to discover and connect to services, and be
                discovered by, and connected from, other services within a namespace.
            volumeConfigurations: The details of the volume that was ``configuredAtLaunch``. You can configure the size,
                volumeType, IOPS, throughput, snapshot and encryption in `ServiceManagedEBSVolumeConfiguration
                <https://docs.aws.amazon.com/AmazonECS/latest/APIRefere nce/API_ServiceManagedEBSVolumeConfiguration.html>`_. The
                ``name`` of the volume must match the ``name`` from the task definition. If set to null, no new deployment is
                triggered. Otherwise, if this configuration differs from the existing one, it triggers a new deployment.
            vpcLatticeConfigurations: An object representing the VPC Lattice configuration for the service being updated.
        """
        data = model.model_dump(exclude_none=True, by_alias=True)
        args = dict(
            service=data.get("serviceName"),
            cluster=data.get("clusterArn"),
            desiredCount=data.get("desiredCount"),
            taskDefinition=data.get("taskDefinition"),
            capacityProviderStrategy=data.get("capacityProviderStrategy"),
            deploymentConfiguration=data.get("deploymentConfiguration"),
            availabilityZoneRebalancing=data.get("availabilityZoneRebalancing"),
            networkConfiguration=data.get("networkConfiguration"),
            placementConstraints=data.get("placementConstraints"),
            placementStrategy=data.get("placementStrategy"),
            platformVersion=data.get("platformVersion"),
            forceNewDeployment=self.serialize(forceNewDeployment),
            healthCheckGracePeriodSeconds=data.get("healthCheckGracePeriodSeconds"),
            deploymentController=data.get("deploymentController"),
            enableExecuteCommand=data.get("enableExecuteCommand"),
            enableECSManagedTags=data.get("enableECSManagedTags"),
            loadBalancers=data.get("loadBalancers"),
            propagateTags=data.get("propagateTags"),
            serviceRegistries=data.get("serviceRegistries"),
            serviceConnectConfiguration=self.serialize(serviceConnectConfiguration),
            volumeConfigurations=self.serialize(volumeConfigurations),
            vpcLatticeConfigurations=self.serialize(vpcLatticeConfigurations),
        )
        _response = self.client.update_service(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = UpdateServiceResponse(**_response)

        self.sessionize(response.service)
        return cast("Service", response.service)

    def partial_update(
        self,
        service: str,
        *,
        cluster: str | None = None,
        desiredCount: int | None = None,
        taskDefinition: str | None = None,
        capacityProviderStrategy: List["CapacityProviderStrategyItem"] | None = None,
        deploymentConfiguration: Optional["DeploymentConfiguration"] = None,
        availabilityZoneRebalancing: Literal["ENABLED", "DISABLED"] | None = None,
        networkConfiguration: Optional["NetworkConfiguration"] = None,
        placementConstraints: List["PlacementConstraint"] | None = None,
        placementStrategy: List["PlacementStrategy"] | None = None,
        platformVersion: str | None = None,
        forceNewDeployment: bool = False,
        healthCheckGracePeriodSeconds: int | None = None,
        deploymentController: Optional["DeploymentController"] = None,
        enableExecuteCommand: bool | None = None,
        enableECSManagedTags: bool | None = None,
        loadBalancers: List["LoadBalancerConfiguration"] | None = None,
        propagateTags: Literal["TASK_DEFINITION", "SERVICE", "NONE"] | None = None,
        serviceRegistries: List["ServiceRegistry"] | None = None,
        serviceConnectConfiguration: Optional["ServiceConnectConfiguration"] = None,
        volumeConfigurations: List["ServiceVolumeConfiguration"] | None = None,
        vpcLatticeConfigurations: List["VpcLatticeConfiguration"] | None = None,
    ) -> "Service":
        """
        Update individual attributes of an ECS service.

        Args:
            service: The name of the service to update.

        Keyword Args:
            cluster: The short name or full Amazon Resource Name (ARN) of the cluster that your service runs on. If you do not
                specify a cluster, the default cluster is assumed.
            desiredCount: The number of instantiations of the task to place and keep running in your service.
            taskDefinition: The ``family`` and ``revision`` (``family:revision``) or full ARN of the task definition to run in
                your service. If a ``revision`` is not specified, the latest ``ACTIVE`` revision is used. If you modify the task
                definition with ``UpdateService``, Amazon ECS spawns a task with the new version of the task definition and then
                stops an old task after the new version is running.
            capacityProviderStrategy: The details of a capacity provider strategy. You can set a capacity provider when you
                create a cluster, run a task, or update a service.
            deploymentConfiguration: Optional deployment parameters that control how many tasks run during the deployment and
                the ordering of stopping and starting tasks.
            availabilityZoneRebalancing: Indicates whether to use Availability Zone rebalancing for the service.
            networkConfiguration: An object representing the network configuration for the service.
            placementConstraints: An array of task placement constraint objects to update the service to use. If no value is
                specified, the existing placement constraints for the service will remain unchanged. If this value is specified, it
                will override any existing placement constraints defined for the service. To remove all existing placement
                constraints, specify an empty array.
            placementStrategy: The task placement strategy objects to update the service to use. If no value is specified, the
                existing placement strategy for the service will remain unchanged. If this value is specified, it will override the
                existing placement strategy defined for the service. To remove an existing placement strategy, specify an empty
                object.
            platformVersion: The platform version that your tasks in the service run on. A platform version is only specified
                for tasks using the Fargate launch type. If a platform version is not specified, the ``LATEST`` platform version is
                used. For more information, see `Fargate Platform Versions
                <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html>`_ in the *Amazon Elastic
                Container Service Developer Guide*.
            forceNewDeployment: Determines whether to force a new deployment of the service. By default, deployments aren't
                forced. You can use this option to start a new deployment with no service definition changes. For example, you can
                update a service's tasks to use a newer Docker image with the same image/tag combination (``my_image:latest``) or to
                roll Fargate tasks onto a newer platform version.
            healthCheckGracePeriodSeconds: The period of time, in seconds, that the Amazon ECS service scheduler ignores
                unhealthy Elastic Load Balancing, VPC Lattice, and container health checks after a task has first started. If you
                don't specify a health check grace period value, the default value of ``0`` is used. If you don't use any of the
                health checks, then ``healthCheckGracePeriodSeconds`` is unused.
            deploymentController: The deployment controller to use for the service.
            enableExecuteCommand: If ``true``, this enables execute command functionality on all task containers.
            enableECSManagedTags: Determines whether to turn on Amazon ECS managed tags for the tasks in the service. For more
                information, see `Tagging Your Amazon ECS Resources
                <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-tags.html>`_ in the *Amazon Elastic Container
                Service Developer Guide*.
            loadBalancers: You must have a service-linked role when you update this property
            propagateTags: Determines whether to propagate the tags from the task definition or the service to the task. If no
                value is specified, the tags aren't propagated.
            serviceRegistries: You must have a service-linked role when you update this property.
            serviceConnectConfiguration: The configuration for this service to discover and connect to services, and be
                discovered by, and connected from, other services within a namespace.
            volumeConfigurations: The details of the volume that was ``configuredAtLaunch``. You can configure the size,
                volumeType, IOPS, throughput, snapshot and encryption in `ServiceManagedEBSVolumeConfiguration
                <https://docs.aws.amazon.com/AmazonECS/latest/APIRefere nce/API_ServiceManagedEBSVolumeConfiguration.html>`_. The
                ``name`` of the volume must match the ``name`` from the task definition. If set to null, no new deployment is
                triggered. Otherwise, if this configuration differs from the existing one, it triggers a new deployment.
            vpcLatticeConfigurations: An object representing the VPC Lattice configuration for the service being updated.
        """
        args: Dict[str, Any] = dict(
            service=self.serialize(service),
            cluster=self.serialize(cluster),
            desiredCount=self.serialize(desiredCount),
            taskDefinition=self.serialize(taskDefinition),
            capacityProviderStrategy=self.serialize(capacityProviderStrategy),
            deploymentConfiguration=self.serialize(deploymentConfiguration),
            availabilityZoneRebalancing=self.serialize(availabilityZoneRebalancing),
            networkConfiguration=self.serialize(networkConfiguration),
            placementConstraints=self.serialize(placementConstraints),
            placementStrategy=self.serialize(placementStrategy),
            platformVersion=self.serialize(platformVersion),
            forceNewDeployment=self.serialize(forceNewDeployment),
            healthCheckGracePeriodSeconds=self.serialize(healthCheckGracePeriodSeconds),
            deploymentController=self.serialize(deploymentController),
            enableExecuteCommand=self.serialize(enableExecuteCommand),
            enableECSManagedTags=self.serialize(enableECSManagedTags),
            loadBalancers=self.serialize(loadBalancers),
            propagateTags=self.serialize(propagateTags),
            serviceRegistries=self.serialize(serviceRegistries),
            serviceConnectConfiguration=self.serialize(serviceConnectConfiguration),
            volumeConfigurations=self.serialize(volumeConfigurations),
            vpcLatticeConfigurations=self.serialize(vpcLatticeConfigurations),
        )
        _response = self.client.update_service(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = UpdateServiceResponse(**_response)

        self.sessionize(response.service)
        return cast("Service", response.service)


class ClusterManager(Boto3ModelManager):
    service_name: str = "ecs"

    def create(self, model: "Cluster") -> "Cluster":
        """
        Create an ECS cluster.

        Args:
            model: The :py:class:`Cluster` to create.
        """
        data = model.model_dump(exclude_none=True, by_alias=True)
        args = dict(
            clusterName=data.get("clusterName"),
            tags=data.get("tags"),
            settings=data.get("settings"),
            configuration=data.get("configuration"),
            capacityProviders=data.get("capacityProviders"),
            defaultCapacityProviderStrategy=data.get("defaultCapacityProviderStrategy"),
            serviceConnectDefaults=data.get("serviceConnectDefaults"),
        )
        _response = self.client.create_cluster(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = CreateClusterResponse(**_response)

        self.sessionize(response.cluster)
        return cast("Cluster", response.cluster)

    def delete(self, cluster: str) -> "Cluster":
        """
        Delete an ECS cluster.

        Args:
            cluster: The short name or full Amazon Resource Name (ARN) of the cluster to delete.
        """
        args: Dict[str, Any] = dict(cluster=self.serialize(cluster))
        _response = self.client.delete_cluster(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DeleteClusterResponse(**_response)
        return cast("Cluster", response.cluster)

    def get(
        self,
        cluster: str,
        *,
        include: List[
            Literal["ATTACHMENTS", "CONFIGURATIONS", "SETTINGS", "STATISTICS", "TAGS"]
        ] = ["ATTACHMENTS", "CONFIGURATIONS", "SETTINGS", "STATISTICS", "TAGS"],
    ) -> Optional["Cluster"]:
        """
        Describes one or more of your clusters.

        Args:
            cluster: The name or full Amazon Resource Name (ARN) of the cluster to describe.

        Keyword Args:
            include: Determines whether to include additional information about the clusters in the response. If this field is
                omitted, this information isn't included.
        """
        args: Dict[str, Any] = dict(
            clusters=self.serialize([cluster]), include=self.serialize(include)
        )
        _response = self.client.describe_clusters(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DescribeClustersResponse(**_response)

        if response and response.clusters:
            self.sessionize(response.clusters[0])
            return response.clusters[0]
        return None

    def get_many(
        self,
        *,
        clusters: List[str] | None = None,
        include: List[
            Literal["ATTACHMENTS", "CONFIGURATIONS", "SETTINGS", "STATISTICS", "TAGS"]
        ] = ["ATTACHMENTS", "CONFIGURATIONS", "SETTINGS", "STATISTICS", "TAGS"],
    ) -> Union[PrimaryBoto3ModelQuerySet, "DescribeClustersResponse"] | None:
        """
        Describes one or more of your clusters.

        Keyword Args:
            clusters: A list of up to 100 cluster names or full cluster Amazon Resource Name (ARN) entries. If you do not
                specify a cluster, the default cluster is assumed.
            include: Determines whether to include additional information about the clusters in the response. If this field is
                omitted, this information isn't included.
        """
        args: Dict[str, Any] = dict(
            clusters=self.serialize(clusters), include=self.serialize(include)
        )
        _response = self.client.describe_clusters(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DescribeClustersResponse(**_response)

        if response.clusters:
            self.sessionize(response.clusters)
            return PrimaryBoto3ModelQuerySet(response.clusters)
        return PrimaryBoto3ModelQuerySet([])

    @ecs_clusters_only
    def list(
        self,
    ) -> List[str]:
        """
        Returns a list of existing clusters.
        """
        paginator = self.client.get_paginator("list_clusters")
        args: Dict[str, Any] = dict()
        response_iterator = paginator.paginate(
            **{k: v for k, v in args.items() if v is not None}
        )
        results = []
        for _response in response_iterator:
            if list(_response.keys()) == ["ResponseMetadata"]:
                break
            if "ResponseMetadata" in _response:
                del _response["ResponseMetadata"]
            response = ListClustersResponse(**_response)
            if response.clusterArns:
                results.extend(response.clusterArns)
            else:
                if getattr(response, "NextToken", None):
                    continue
                break
        self.sessionize(results)
        if results and isinstance(results[0], Boto3Model):
            return PrimaryBoto3ModelQuerySet(results)
        return results

    def update(self, model: "Cluster") -> "Cluster":
        """
        Update an ECS cluster.

        Args:
            model: The :py:class:`Cluster` to update.
        """
        data = model.model_dump(exclude_none=True, by_alias=True)
        args = dict(
            cluster=data.get("clusterName"),
            settings=data.get("settings"),
            configuration=data.get("configuration"),
            serviceConnectDefaults=data.get("serviceConnectDefaults"),
        )
        _response = self.client.update_cluster(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = UpdateClusterResponse(**_response)

        self.sessionize(response.cluster)
        return cast("Cluster", response.cluster)

    def partial_update(
        self,
        cluster: str,
        *,
        settings: List["ClusterSetting"] | None = None,
        configuration: Optional["ClusterConfiguration"] = None,
        serviceConnectDefaults: Optional["ClusterServiceConnectDefaultsRequest"] = None,
    ) -> "Cluster":
        """
        Update individual attributes of an ECS cluster.

        Args:
            cluster: The name of the cluster to modify the settings for.

        Keyword Args:
            settings: The cluster settings for your cluster.
            configuration: The execute command configuration for the cluster.
            serviceConnectDefaults: Use this parameter to set a default Service Connect namespace. After you set a default
                Service Connect namespace, any new services with Service Connect turned on that are created in the cluster are added
                as client services in the namespace. This setting only applies to new services that set the ``enabled`` parameter to
                ``true`` in the ``ServiceConnectConfiguration``. You can set the namespace of each service individually in the
                ``ServiceConnectConfiguration`` to override this default parameter.
        """
        args: Dict[str, Any] = dict(
            cluster=self.serialize(cluster),
            settings=self.serialize(settings),
            configuration=self.serialize(configuration),
            serviceConnectDefaults=self.serialize(serviceConnectDefaults),
        )
        _response = self.client.update_cluster(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = UpdateClusterResponse(**_response)

        self.sessionize(response.cluster)
        return cast("Cluster", response.cluster)


class TaskDefinitionManager(TaskDefinitionManagerMixin, Boto3ModelManager):
    service_name: str = "ecs"

    def create(
        self, model: "TaskDefinition", tags: List["ECSTag"] | None = None
    ) -> "TaskDefinition":
        """
        Registers a new task definition from the supplied ``family`` and ``containerDefinitions``. Optionally, you can add data
        volumes to your containers with the ``volumes`` parameter. For more information about task definition parameters and
        defaults, see `Amazon ECS Task
        Definitions <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_defintions.html>`_ in the *Amazon Elastic
        Container Service Developer Guide*.

        Args:
            model: The :py:class:`TaskDefinition` to create.

        Keyword Args:
            tags: The metadata that you apply to the task definition to help you categorize and organize them. Each tag consists
                of a key and an optional value. You define both of them.

        """
        data = model.model_dump(exclude_none=True, by_alias=True)
        args = dict(
            family=data.get("family"),
            containerDefinitions=data.get("containerDefinitions"),
            taskRoleArn=data.get("taskRoleArn"),
            executionRoleArn=data.get("executionRoleArn"),
            networkMode=data.get("networkMode"),
            volumes=data.get("volumes"),
            placementConstraints=data.get("placementConstraints"),
            requiresCompatibilities=data.get("requiresCompatibilities"),
            cpu=data.get("cpu"),
            memory=data.get("memory"),
            tags=self.serialize(tags),
            pidMode=data.get("pidMode"),
            ipcMode=data.get("ipcMode"),
            proxyConfiguration=data.get("proxyConfiguration"),
            inferenceAccelerators=data.get("inferenceAccelerators"),
            ephemeralStorage=data.get("ephemeralStorage"),
            runtimePlatform=data.get("runtimePlatform"),
            enableFaultInjection=data.get("enableFaultInjection"),
        )
        _response = self.client.register_task_definition(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = RegisterTaskDefinitionResponse(**_response)

        self.sessionize(response.taskDefinition)
        return cast("TaskDefinition", response.taskDefinition)

    @ecs_task_definition_delete_all
    def delete(self, taskDefinitions: List[str]) -> "TaskDefinition":
        """
        Deletes one or more task definitions.

        Args:
            taskDefinitions: The ``family`` and ``revision`` (``family:revision``) or full Amazon Resource Name (ARN) of the
                task definition to delete. You must specify a ``revision``.
        """
        args: Dict[str, Any] = dict(taskDefinitions=self.serialize(taskDefinitions))
        _response = self.client.delete_task_definitions(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DeleteTaskDefinitionsResponse(**_response)
        return response

    @ecs_task_definition_include_tags
    def get(
        self, taskDefinition: str, *, include: List[Literal["TAGS"]] = ["TAGS"]
    ) -> Optional["TaskDefinition"]:
        """
        Describes a task definition. You can specify a ``family`` and ``revision`` to
        find information about a specific task definition, or you can simply specify the
        family to find the latest ``ACTIVE`` revision in that family.

        Args:
            taskDefinition: The ``family`` for the latest ``ACTIVE`` revision, ``family`` and ``revision`` (``family:revision``)
                for a specific revision in the family, or full Amazon Resource Name (ARN) of the task definition to describe.

        Keyword Args:
            include: Determines whether to see the resource tags for the task definition. If ``TAGS`` is specified, the tags are
                included in the response. If this field is omitted, tags aren't included in the response.
        """
        args: Dict[str, Any] = dict(
            taskDefinition=self.serialize(taskDefinition),
            include=self.serialize(include),
        )
        _response = self.client.describe_task_definition(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DescribeTaskDefinitionResponse(**_response)

        if response:
            self.sessionize(response)
            return response
        return None

    @ecs_task_definitions_only
    def list(
        self,
        *,
        familyPrefix: str | None = None,
        status: Literal["ACTIVE", "INACTIVE", "DELETE_IN_PROGRESS"] | None = None,
        sort: Literal["ASC", "DESC"] | None = None,
    ) -> List[str]:
        """
        Returns a list of task definitions that are registered to your account. You can
        filter the results by family name with the ``familyPrefix`` parameter or by
        status with the ``status`` parameter.

        Keyword Args:
            familyPrefix: The full family name to filter the ``ListTaskDefinitions`` results with. Specifying a ``familyPrefix``
                limits the listed task definitions to task definition revisions that belong to that family.
            status: The task definition status to filter the ``ListTaskDefinitions`` results with. By default, only ``ACTIVE``
                task definitions are listed. By setting this parameter to ``INACTIVE``, you can view task definitions that are
                ``INACTIVE`` as long as an active task or service still references them. If you paginate the resulting output, be
                sure to keep the ``status`` value constant in each subsequent request.
            sort: The order to sort the results in. Valid values are ``ASC`` and ``DESC``. By default, (``ASC``) task
                definitions are listed lexicographically by family name and in ascending numerical order by revision so that the
                newest task definitions in a family are listed last. Setting this parameter to ``DESC`` reverses the sort order on
                family name and revision. This is so that the newest task definitions in a family are listed first.
        """
        paginator = self.client.get_paginator("list_task_definitions")
        args: Dict[str, Any] = dict(
            familyPrefix=self.serialize(familyPrefix),
            status=self.serialize(status),
            sort=self.serialize(sort),
        )
        response_iterator = paginator.paginate(
            **{k: v for k, v in args.items() if v is not None}
        )
        results = []
        for _response in response_iterator:
            if list(_response.keys()) == ["ResponseMetadata"]:
                break
            if "ResponseMetadata" in _response:
                del _response["ResponseMetadata"]
            response = ListTaskDefinitionsResponse(**_response)
            if response.taskDefinitionArns:
                results.extend(response.taskDefinitionArns)
            else:
                if getattr(response, "NextToken", None):
                    continue
                break
        self.sessionize(results)
        if results and isinstance(results[0], Boto3Model):
            return PrimaryBoto3ModelQuerySet(results)
        return results

    def update(
        self, model: "TaskDefinition", tags: List["ECSTag"] | None = None
    ) -> "TaskDefinition":
        """
        Registers a new task definition from the supplied ``family`` and ``containerDefinitions``. Optionally, you can add data
        volumes to your containers with the ``volumes`` parameter. For more information about task definition parameters and
        defaults, see `Amazon ECS Task
        Definitions <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_defintions.html>`_ in the *Amazon Elastic
        Container Service Developer Guide*.

        Args:
            model: The :py:class:`TaskDefinition` to update.

        Keyword Args:
            tags: The metadata that you apply to the task definition to help you categorize and organize them. Each tag consists
                of a key and an optional value. You define both of them.

        """
        data = model.model_dump(exclude_none=True, by_alias=True)
        args = dict(
            family=data.get("family"),
            containerDefinitions=data.get("containerDefinitions"),
            taskRoleArn=data.get("taskRoleArn"),
            executionRoleArn=data.get("executionRoleArn"),
            networkMode=data.get("networkMode"),
            volumes=data.get("volumes"),
            placementConstraints=data.get("placementConstraints"),
            requiresCompatibilities=data.get("requiresCompatibilities"),
            cpu=data.get("cpu"),
            memory=data.get("memory"),
            tags=self.serialize(tags),
            pidMode=data.get("pidMode"),
            ipcMode=data.get("ipcMode"),
            proxyConfiguration=data.get("proxyConfiguration"),
            inferenceAccelerators=data.get("inferenceAccelerators"),
            ephemeralStorage=data.get("ephemeralStorage"),
            runtimePlatform=data.get("runtimePlatform"),
            enableFaultInjection=data.get("enableFaultInjection"),
        )
        _response = self.client.register_task_definition(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = RegisterTaskDefinitionResponse(**_response)

        self.sessionize(response.taskDefinition)
        return cast("TaskDefinition", response.taskDefinition)

    def deregister(self, taskDefinition: str) -> "TaskDefinition":
        """
        Deregisters the specified task definition by family and revision. Upon
        deregistration, the task definition is marked as ``INACTIVE``. Existing tasks
        and services that reference an ``INACTIVE`` task definition continue to run
        without disruption. Existing services that reference an ``INACTIVE`` task
        definition can still scale up or down by modifying the service's desired count.
        If you want to delete a task definition revision, you must first deregister the
        task definition revision.

        Args:
            taskDefinition: The ``family`` and ``revision`` (``family:revision``) or full Amazon Resource Name (ARN) of the task
                definition to deregister. You must specify a ``revision``.
        """
        args: Dict[str, Any] = dict(taskDefinition=self.serialize(taskDefinition))
        _response = self.client.deregister_task_definition(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DeregisterTaskDefinitionResponse(**_response)

        results: "TaskDefinition" = None
        if response is not None:
            results = response.taskDefinition

        self.sessionize(results)
        return cast("TaskDefinition", results)

    def families(
        self,
        *,
        familyPrefix: str | None = None,
        status: Literal["ACTIVE", "INACTIVE", "ALL"] | None = None,
    ) -> List[str]:
        """
        Returns a list of task definition families that are registered to your account.
        This list includes task definition families that no longer have any ``ACTIVE``
        task definition revisions.

        Keyword Args:
            familyPrefix: The ``familyPrefix`` is a string that's used to filter the results of ``ListTaskDefinitionFamilies``.
                If you specify a ``familyPrefix``, only task definition family names that begin with the ``familyPrefix`` string are
                returned.
            status: The task definition family status to filter the ``ListTaskDefinitionFamilies`` results with. By default,
                both ``ACTIVE`` and ``INACTIVE`` task definition families are listed. If this parameter is set to ``ACTIVE``, only
                task definition families that have an ``ACTIVE`` task definition revision are returned. If this parameter is set to
                ``INACTIVE``, only task definition families that do not have any ``ACTIVE`` task definition revisions are returned.
                If you paginate the resulting output, be sure to keep the ``status`` value constant in each subsequent request.
        """
        paginator = self.client.get_paginator("list_task_definition_families")
        args: Dict[str, Any] = dict(
            familyPrefix=self.serialize(familyPrefix), status=self.serialize(status)
        )
        response_iterator = paginator.paginate(
            **{k: v for k, v in args.items() if v is not None}
        )

        results: List[str] = []

        for _response in response_iterator:
            response = ListTaskDefinitionFamiliesResponse(**_response)
            if response.families is not None:
                results.extend(response.families)
            else:
                break

        self.sessionize(results)
        return cast("List[str]", results)


class ContainerInstanceManager(ReadonlyBoto3ModelManager):
    service_name: str = "ecs"

    def get(
        self,
        containerInstance: str,
        *,
        cluster: str = "default",
        include: List[Literal["TAGS", "CONTAINER_INSTANCE_HEALTH"]] = [
            "TAGS",
            "CONTAINER_INSTANCE_HEALTH",
        ],
    ) -> Optional["ContainerInstance"]:
        """
        Describes one or more container instances. Returns metadata about each container
        instance requested.

        Args:
            containerInstance: The container instance ID or full Amazon Resource Name (ARN) entry for the container instance you
                want to describe.

        Keyword Args:
            cluster: The short name or full Amazon Resource Name (ARN) of the cluster that hosts the container instances to
                describe. If you do not specify a cluster, the default cluster is assumed. This parameter is required if the
                container instance or container instances you are describing were launched in any cluster other than the default
                cluster.
            include: Specifies whether you want to see the resource tags for the container instance. If ``TAGS`` is specified,
                the tags are included in the response. If ``CONTAINER_INSTANCE_HEALTH`` is specified, the container instance health
                is included in the response. If this field is omitted, tags and container instance health status aren't included in
                the response.
        """
        args: Dict[str, Any] = dict(
            containerInstances=self.serialize([containerInstance]),
            cluster=self.serialize(cluster),
            include=self.serialize(include),
        )
        _response = self.client.describe_container_instances(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DescribeContainerInstancesResponse(**_response)

        if response and response.containerInstances:
            self.sessionize(response.containerInstances[0])
            return response.containerInstances[0]
        return None

    def get_many(
        self,
        containerInstances: List[str],
        *,
        cluster: str = "default",
        include: List[Literal["TAGS", "CONTAINER_INSTANCE_HEALTH"]] = [
            "TAGS",
            "CONTAINER_INSTANCE_HEALTH",
        ],
    ) -> Union[PrimaryBoto3ModelQuerySet, "DescribeContainerInstancesResponse"] | None:
        """
        Describes one or more container instances. Returns metadata about each container
        instance requested.

        Args:
            containerInstances: A list of up to 100 container instance IDs or full Amazon Resource Name (ARN) entries.

        Keyword Args:
            cluster: The short name or full Amazon Resource Name (ARN) of the cluster that hosts the container instances to
                describe. If you do not specify a cluster, the default cluster is assumed. This parameter is required if the
                container instance or container instances you are describing were launched in any cluster other than the default
                cluster.
            include: Specifies whether you want to see the resource tags for the container instance. If ``TAGS`` is specified,
                the tags are included in the response. If ``CONTAINER_INSTANCE_HEALTH`` is specified, the container instance health
                is included in the response. If this field is omitted, tags and container instance health status aren't included in
                the response.
        """
        args: Dict[str, Any] = dict(
            containerInstances=self.serialize(containerInstances),
            cluster=self.serialize(cluster),
            include=self.serialize(include),
        )
        _response = self.client.describe_container_instances(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DescribeContainerInstancesResponse(**_response)

        if response.containerInstances:
            self.sessionize(response.containerInstances)
            return PrimaryBoto3ModelQuerySet(response.containerInstances)
        return PrimaryBoto3ModelQuerySet([])

    @ecs_container_instances_only
    def list(
        self,
        *,
        cluster: str = "default",
        filter: str | None = None,
        status: Literal["ACTIVE", "DRAINING", "REGISTERING", "DEREGISTERING", "REGISTRATION_FAILED"] | None = None,
    ) -> List[str]:
        """
        Returns a list of container instances in a specified cluster. You can filter the results of a ``ListContainerInstances``
        operation with cluster query language statements inside the ``filter`` parameter. For more information, see `Cluster
        Query Language <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-query-language.html>`_ in the *Amazon
        Elastic Container Service Developer Guide*.

        Keyword Args:
            cluster: The short name or full Amazon Resource Name (ARN) of the cluster that hosts the container instances to
                list. If you do not specify a cluster, the default cluster is assumed.
            filter: You can filter the results of a ``ListContainerInstances`` operation with cluster query language statements.
                For more information, see `Cluster Query Language
                <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-query- language.html>`_ in the *Amazon Elastic
                Container Service Developer Guide*.
            status: Filters the container instances by status. For example, if you specify the ``DRAINING`` status, the results
                include only container instances that have been set to ``DRAINING`` using `UpdateContainerInstancesState
                <https://docs.aws.amazon.com /AmazonECS/latest/APIReference/API_UpdateContainerInstancesState.html>`_. If you don't
                specify this parameter, the default is to include container instances set to all states other than ``INACTIVE``.

        """
        paginator = self.client.get_paginator("list_container_instances")
        args: Dict[str, Any] = dict(
            cluster=self.serialize(cluster),
            filter=self.serialize(filter),
            status=self.serialize(status),
        )
        response_iterator = paginator.paginate(
            **{k: v for k, v in args.items() if v is not None}
        )
        results = []
        for _response in response_iterator:
            if list(_response.keys()) == ["ResponseMetadata"]:
                break
            if "ResponseMetadata" in _response:
                del _response["ResponseMetadata"]
            response = ListContainerInstancesResponse(**_response)
            if response.containerInstanceArns:
                results.extend(response.containerInstanceArns)
            else:
                if getattr(response, "NextToken", None):
                    continue
                break
        self.sessionize(results)
        if results and isinstance(results[0], Boto3Model):
            return PrimaryBoto3ModelQuerySet(results)
        return results

    def list_tasks(
        self,
        containerInstance: str,
        *,
        cluster: str | None = None,
        family: str | None = None,
        startedBy: str | None = None,
        serviceName: str | None = None,
        desiredStatus: Literal["RUNNING", "PENDING", "STOPPED"] | None = None,
        launchType: Literal["EC2", "FARGATE", "EXTERNAL", "MANAGED_INSTANCES"] | None = None,
    ) -> List[str]:
        """
        Returns a list of tasks. You can filter the results by cluster, task definition
        family, container instance, launch type, what IAM principal started the task, or
        by the desired status of the task.

        Args:
            containerInstance: The container instance ID or full ARN of the container instance to use when filtering the
                ``ListTasks`` results. Specifying a ``containerInstance`` limits the results to tasks that belong to that container
                instance.

        Keyword Args:
            cluster: The short name or full Amazon Resource Name (ARN) of the cluster to use when filtering the ``ListTasks``
                results. If you do not specify a cluster, the default cluster is assumed.
            family: The name of the task definition family to use when filtering the ``ListTasks`` results. Specifying a
                ``family`` limits the results to tasks that belong to that family.
            startedBy: The ``startedBy`` value to filter the task results with. Specifying a ``startedBy`` value limits the
                results to tasks that were started with that value.
            serviceName: The name of the service to use when filtering the ``ListTasks`` results. Specifying a ``serviceName``
                limits the results to tasks that belong to that service.
            desiredStatus: The task desired status to use when filtering the ``ListTasks`` results. Specifying a
                ``desiredStatus`` of ``STOPPED`` limits the results to tasks that Amazon ECS has set the desired status to
                ``STOPPED``. This can be useful for debugging tasks that aren't starting properly or have died or finished. The
                default status filter is ``RUNNING``, which shows tasks that Amazon ECS has set the desired status to ``RUNNING``.
            launchType: The launch type to use when filtering the ``ListTasks`` results.
        """
        paginator = self.client.get_paginator("list_tasks")
        args: Dict[str, Any] = dict(
            cluster=self.serialize(cluster),
            containerInstance=self.serialize([containerInstance]),
            family=self.serialize(family),
            startedBy=self.serialize(startedBy),
            serviceName=self.serialize(serviceName),
            desiredStatus=self.serialize(desiredStatus),
            launchType=self.serialize(launchType),
        )
        response_iterator = paginator.paginate(
            **{k: v for k, v in args.items() if v is not None}
        )

        results: List[str] = []

        for _response in response_iterator:
            response = ListTasksResponse(**_response)
            if response.taskArns is not None:
                results.extend(response.taskArns)
            else:
                break

        self.sessionize(results)
        return cast("List[str]", results)


class TaskManager(Boto3ModelManager):
    service_name: str = "ecs"

    @ecs_task_populate_taskDefinition
    def get(
        self,
        task: str,
        *,
        cluster: str = "default",
        include: List[Literal["TAGS"]] = ["TAGS"],
    ) -> Optional["Task"]:
        """
        Describes a specified task or tasks.

        Args:
            task: The task ID or full Amazon Resource Name (ARN) entry of the task that you want to describe.

        Keyword Args:
            cluster: The short name or full Amazon Resource Name (ARN) of the cluster that hosts the task or tasks to describe.
                If you do not specify a cluster, the default cluster is assumed.
            include: Specifies whether you want to see the resource tags for the task. If ``TAGS`` is specified, the tags are
                included in the response. If this field is omitted, tags aren't included in the response.
        """
        args: Dict[str, Any] = dict(
            tasks=self.serialize([task]),
            cluster=self.serialize(cluster),
            include=self.serialize(include),
        )
        _response = self.client.describe_tasks(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DescribeTasksResponse(**_response)

        if response and response.tasks:
            self.sessionize(response.tasks[0])
            return response.tasks[0]
        return None

    @ecs_task_populate_taskDefinitions
    def get_many(
        self,
        tasks: List[str],
        *,
        cluster: str = "default",
        include: List[Literal["TAGS"]] = ["TAGS"],
    ) -> Union[PrimaryBoto3ModelQuerySet, "DescribeTasksResponse"] | None:
        """
        Describes a specified task or tasks.

        Args:
            tasks: A list of up to 100 task IDs or full ARN entries.

        Keyword Args:
            cluster: The short name or full Amazon Resource Name (ARN) of the cluster that hosts the task or tasks to describe.
                If you do not specify a cluster, the default cluster is assumed.
            include: Specifies whether you want to see the resource tags for the task. If ``TAGS`` is specified, the tags are
                included in the response. If this field is omitted, tags aren't included in the response.
        """
        args: Dict[str, Any] = dict(
            tasks=self.serialize(tasks),
            cluster=self.serialize(cluster),
            include=self.serialize(include),
        )
        _response = self.client.describe_tasks(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DescribeTasksResponse(**_response)

        if response.tasks:
            self.sessionize(response.tasks)
            return PrimaryBoto3ModelQuerySet(response.tasks)
        return PrimaryBoto3ModelQuerySet([])

    @ecs_tasks_only
    def list(
        self,
        *,
        cluster: str = "default",
        containerInstance: str | None = None,
        family: str | None = None,
        startedBy: str | None = None,
        serviceName: str | None = None,
        desiredStatus: Literal["RUNNING", "PENDING", "STOPPED"] | None = None,
        launchType: Literal["EC2", "FARGATE", "EXTERNAL", "MANAGED_INSTANCES"] | None = None,
    ) -> List[str]:
        """
        Returns a list of tasks. You can filter the results by cluster, task definition
        family, container instance, launch type, what IAM principal started the task, or
        by the desired status of the task.

        Keyword Args:
            cluster: The short name or full Amazon Resource Name (ARN) of the cluster to use when filtering the ``ListTasks``
                results. If you do not specify a cluster, the default cluster is assumed.
            containerInstance: The container instance ID or full ARN of the container instance to use when filtering the
                ``ListTasks`` results. Specifying a ``containerInstance`` limits the results to tasks that belong to that container
                instance.
            family: The name of the task definition family to use when filtering the ``ListTasks`` results. Specifying a
                ``family`` limits the results to tasks that belong to that family.
            startedBy: The ``startedBy`` value to filter the task results with. Specifying a ``startedBy`` value limits the
                results to tasks that were started with that value.
            serviceName: The name of the service to use when filtering the ``ListTasks`` results. Specifying a ``serviceName``
                limits the results to tasks that belong to that service.
            desiredStatus: The task desired status to use when filtering the ``ListTasks`` results. Specifying a
                ``desiredStatus`` of ``STOPPED`` limits the results to tasks that Amazon ECS has set the desired status to
                ``STOPPED``. This can be useful for debugging tasks that aren't starting properly or have died or finished. The
                default status filter is ``RUNNING``, which shows tasks that Amazon ECS has set the desired status to ``RUNNING``.
            launchType: The launch type to use when filtering the ``ListTasks`` results.
        """
        paginator = self.client.get_paginator("list_tasks")
        args: Dict[str, Any] = dict(
            cluster=self.serialize(cluster),
            containerInstance=self.serialize(containerInstance),
            family=self.serialize(family),
            startedBy=self.serialize(startedBy),
            serviceName=self.serialize(serviceName),
            desiredStatus=self.serialize(desiredStatus),
            launchType=self.serialize(launchType),
        )
        response_iterator = paginator.paginate(
            **{k: v for k, v in args.items() if v is not None}
        )
        results = []
        for _response in response_iterator:
            if list(_response.keys()) == ["ResponseMetadata"]:
                break
            if "ResponseMetadata" in _response:
                del _response["ResponseMetadata"]
            response = ListTasksResponse(**_response)
            if response.taskArns:
                results.extend(response.taskArns)
            else:
                if getattr(response, "NextToken", None):
                    continue
                break
        self.sessionize(results)
        if results and isinstance(results[0], Boto3Model):
            return PrimaryBoto3ModelQuerySet(results)
        return results

    def create(
        self,
        model: "Task",
        capacityProviderStrategy: List["CapacityProviderStrategyItem"] | None = None,
        count: int | None = None,
        enableECSManagedTags: bool | None = None,
        networkConfiguration: Optional["NetworkConfiguration"] = None,
        placementConstraints: List["PlacementConstraint"] | None = None,
        placementStrategy: List["PlacementStrategy"] | None = None,
        propagateTags: Literal["TASK_DEFINITION", "SERVICE", "NONE"] | None = None,
        referenceId: str | None = None,
        clientToken: str | None = None,
        volumeConfigurations: List["TaskVolumeConfiguration"] | None = None,
    ) -> "Task":
        """
        Starts a new task using the specified task definition.

        Args:
            model: The :py:class:`Task` to create.

        Keyword Args:
            capacityProviderStrategy: The capacity provider strategy to use for the task.
            count: The number of instantiations of the specified task to place on your cluster. You can specify up to 10 tasks
                for each call.
            enableECSManagedTags: Specifies whether to use Amazon ECS managed tags for the task. For more information, see
                `Tagging Your Amazon ECS Resources <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-
                tags.html>`_ in the *Amazon Elastic Container Service Developer Guide*.
            networkConfiguration: The network configuration for the task. This parameter is required for task definitions that
                use the ``awsvpc`` network mode to receive their own elastic network interface, and it isn't supported for other
                network modes. For more information, see `Task networking
                <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-networking.html>`_ in the *Amazon Elastic
                Container Service Developer Guide*.
            placementConstraints: An array of placement constraint objects to use for the task. You can specify up to 10
                constraints for each task (including constraints in the task definition and those specified at runtime).
            placementStrategy: The placement strategy objects to use for the task. You can specify a maximum of 5 strategy rules
                for each task.
            propagateTags: Specifies whether to propagate the tags from the task definition to the task. If no value is
                specified, the tags aren't propagated. Tags can only be propagated to the task during task creation. To add tags to
                a task after task creation, use the`TagResource
                <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_TagResource.html>`_ API action.
            referenceId: This parameter is only used by Amazon ECS. It is not intended for use by customers.
            clientToken: An identifier that you provide to ensure the idempotency of the request. It must be unique and is case
                sensitive. Up to 64 characters are allowed. The valid characters are characters in the range of 33-126, inclusive.
                For more information, see `Ensuring idempotency
                <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/ECS_Idempotency.html>`_.
            volumeConfigurations: The details of the volume that was ``configuredAtLaunch``. You can configure the size,
                volumeType, IOPS, throughput, snapshot and encryption in `TaskManagedEBSVolumeConfiguration
                <https://docs.aws.amazon.com/AmazonECS/latest/APIReference /API_TaskManagedEBSVolumeConfiguration.html>`_. The
                ``name`` of the volume must match the ``name`` from the task definition.
        """
        data = model.model_dump(exclude_none=True, by_alias=True)
        args = dict(
            taskDefinition=data.get("taskDefinition"),
            capacityProviderStrategy=self.serialize(capacityProviderStrategy),
            cluster=data.get("clusterArn"),
            count=self.serialize(count),
            enableECSManagedTags=self.serialize(enableECSManagedTags),
            enableExecuteCommand=data.get("enableExecuteCommand"),
            group=data.get("group"),
            launchType=data.get("launchType"),
            networkConfiguration=self.serialize(networkConfiguration),
            overrides=data.get("overrides"),
            placementConstraints=self.serialize(placementConstraints),
            placementStrategy=self.serialize(placementStrategy),
            platformVersion=data.get("platformVersion"),
            propagateTags=self.serialize(propagateTags),
            referenceId=self.serialize(referenceId),
            startedBy=data.get("startedBy"),
            tags=data.get("tags"),
            clientToken=self.serialize(clientToken),
            volumeConfigurations=self.serialize(volumeConfigurations),
        )
        _response = self.client.run_task(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = RunTaskResponse(**_response)

        self.sessionize(response.tasks[0])
        return cast("Task", response.tasks[0])

    def delete(
        self, task: str, *, cluster: str | None = None, reason: str | None = None
    ) -> "Task":
        """
        Stops a running task. Any tags associated with the task will be deleted.

        Args:
            task: Thefull Amazon Resource Name (ARN) of the task.

        Keyword Args:
            cluster: The short name or full Amazon Resource Name (ARN) of the cluster that hosts the task to stop. If you do not
                specify a cluster, the default cluster is assumed.
            reason: An optional message specified when a task is stopped. For example, if you're using a custom scheduler, you
                can use this parameter to specify the reason for stopping the task here, and the message appears in subsequent
                `DescribeTasks <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeTasks.html>`_> API operations
                on this task.
        """
        args: Dict[str, Any] = dict(
            task=self.serialize(task),
            cluster=self.serialize(cluster),
            reason=self.serialize(reason),
        )
        _response = self.client.stop_task(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = StopTaskResponse(**_response)
        return cast("Task", response.task)


class ServiceDeploymentManager(ReadonlyBoto3ModelManager):
    service_name: str = "ecs"

    def get(self, serviceDeploymentArn: str) -> Optional["ServiceDeployment"]:
        """
        Describes one or more of your service deployments.

        Args:
            serviceDeploymentArn: The deployment ID or full Amazon Resource Name (ARN) entry of the deployment that you want to
                describe.
        """
        args: Dict[str, Any] = dict(
            serviceDeploymentArns=self.serialize([serviceDeploymentArn])
        )
        _response = self.client.describe_service_deployments(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DescribeServiceDeploymentsResponse(**_response)

        if response and response.serviceDeployments:
            self.sessionize(response.serviceDeployments[0])
            return response.serviceDeployments[0]
        return None

    def get_many(
        self, serviceDeploymentArns: List[str]
    ) -> Union[PrimaryBoto3ModelQuerySet, "DescribeServiceDeploymentsResponse"] | None:
        """
        Describes one or more of your service deployments.

        Args:
            serviceDeploymentArns: The ARN of the service deployment.
        """
        args: Dict[str, Any] = dict(
            serviceDeploymentArns=self.serialize(serviceDeploymentArns)
        )
        _response = self.client.describe_service_deployments(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = DescribeServiceDeploymentsResponse(**_response)

        if response.serviceDeployments:
            self.sessionize(response.serviceDeployments)
            return PrimaryBoto3ModelQuerySet(response.serviceDeployments)
        return PrimaryBoto3ModelQuerySet([])

    @ecs_service_deployments_only
    def list(
        self,
        service: str,
        *,
        cluster: str | None = None,
        status: List[Literal["PENDING", "SUCCESSFUL", "STOPPED", "STOP_REQUESTED", "IN_PROGRESS", "ROLLBACK_REQUESTED", "ROLLBACK_IN_PROGRESS", "ROLLBACK_SUCCESSFUL", "ROLLBACK_FAILED"]] | None = None,
        createdAt: Optional["CreatedAt"] = None,
        nextToken: str | None = None,
        maxResults: int | None = None,
    ) -> PrimaryBoto3ModelQuerySet:
        """
        This operation lists all the service deployments that meet the specified filter
        criteria.

        Args:
            service: The ARN or name of the service

        Keyword Args:
            cluster: The cluster that hosts the service. This can either be the cluster name or ARN. Starting April 15, 2023,
                Amazon Web Services will not onboard new customers to Amazon Elastic Inference (EI), and will help current customers
                migrate their workloads to options that offer better price and performance. If you don't specify a cluster,
                ``default`` is used.
            status: An optional filter you can use to narrow the results. If you do not specify a status, then all status values
                are included in the result.
            createdAt: An optional filter you can use to narrow the results by the service creation date. If you do not specify
                a value, the result includes all services created before the current time. The format is yyyy-MM-dd HH:mm:ss.SSSSSS.
            nextToken: The ``nextToken`` value returned from a ``ListServiceDeployments`` request indicating that more results
                are available to fulfill the request and further calls are needed. If you provided ``maxResults``, it's possible the
                number of results is fewer than ``maxResults``.
            maxResults: The maximum number of service deployment results that ``ListServiceDeployments`` returned in paginated
                output. When this parameter is used, ``ListServiceDeployments`` only returns ``maxResults`` results in a single page
                along with a ``nextToken`` response element. The remaining results of the initial request can be seen by sending
                another ``ListServiceDeployments`` request with the returned ``nextToken`` value. This value can be between 1 and
                100. If this parameter isn't used, then ``ListServiceDeployments`` returns up to 20 results and a ``nextToken``
                value if applicable.
        """
        args: Dict[str, Any] = dict(
            service=self.serialize(service),
            cluster=self.serialize(cluster),
            status=self.serialize(status),
            createdAt=self.serialize(createdAt),
            nextToken=self.serialize(nextToken),
            maxResults=self.serialize(maxResults),
        )
        _response = self.client.list_service_deployments(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = ListServiceDeploymentsResponse(**_response)
        if response and response.serviceDeployments:
            self.sessionize(response.serviceDeployments)
            return PrimaryBoto3ModelQuerySet(response.serviceDeployments)
        return PrimaryBoto3ModelQuerySet([])

    def stop(
        self,
        serviceDeploymentArn: str,
        *,
        stopType: Literal["ABORT", "ROLLBACK"] | None = None,
    ) -> str:
        """
        Stops an ongoing service deployment.

        Args:
            serviceDeploymentArn: The ARN of the service deployment that you want to stop.

        Keyword Args:
            stopType: How you want Amazon ECS to stop the service.
        """
        args: Dict[str, Any] = dict(
            serviceDeploymentArn=self.serialize(serviceDeploymentArn),
            stopType=self.serialize(stopType),
        )
        _response = self.client.stop_service_deployment(
            **{k: v for k, v in args.items() if v is not None}
        )
        response = StopServiceDeploymentResponse(**_response)

        results: str = None
        if response is not None:
            results = response.serviceDeploymentArn

        self.sessionize(results)
        return cast("str", results)


# ==============
# Service Models
# ==============


class ECSTag(Boto3Model):
    """
    The metadata that you apply to a resource to help you categorize and organize them.
    Each tag consists of a key and an optional value. You define them.

    The following basic restrictions apply to tags:

    * Maximum number of tags per resource - 50
    * For each resource, each tag key must be unique, and each tag key can have only one value.
    * Maximum key length - 128 Unicode characters in UTF-8
    * Maximum value length - 256 Unicode characters in UTF-8
    * If your tagging schema is used across multiple services and resources, remember that other services may have
      restrictions on allowed characters. Generally allowed characters are: letters, numbers, and spaces representable in
      UTF-8, and the following characters: + - = . _ : / @.
    * Tag keys and values are case-sensitive.
    * Do not use ``aws:``, ``AWS:``, or any upper or lowercase combination of such as a prefix for either keys or values as
      it is reserved for Amazon Web Services use. You cannot edit or delete tag keys or values with this prefix. Tags with
      this prefix do not count against your tags per resource limit.
    """

    key: str | None = None
    """
    One part of a key-value pair that make up a tag.

    A ``key`` is a general label that acts like a category for more
    specific tag values.
    """
    value: str | None = None
    """
    The optional part of a key-value pair that make up a tag.

    A ``value`` acts as a descriptor within a tag category (key).
    """


class AdvancedConfiguration(Boto3Model):
    """
    The advanced settings for a load balancer used in blue/green deployments.

    Specify the alternate target group, listener
    rules, and IAM role required for traffic shifting during blue/green deployments. For more information, see `Required
    resources for Amazon ECS blue/green deployments <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/blue-green-
    deployment-implementation.html>`_ in the *Amazon Elastic Container Service Developer Guide*.
    """

    alternateTargetGroupArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the alternate target group for Amazon ECS
    blue/green deployments.
    """
    productionListenerRule: str | None = None
    """
    The Amazon Resource Name (ARN) that that identifies the production listener rule (in
    the case of an Application Load Balancer) or listener (in the case for an Network
    Load Balancer) for routing production traffic.
    """
    testListenerRule: str | None = None
    """
    The Amazon Resource Name (ARN) that identifies ) that identifies the test listener
    rule (in the case of an Application Load Balancer) or listener (in the case for an
    Network Load Balancer) for routing test traffic.
    """
    roleArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the IAM role that grants Amazon ECS permission to
    call the Elastic Load Balancing APIs for you.
    """


class LoadBalancerConfiguration(Boto3Model):
    """
    The load balancer configuration to use with a service or task set.

    When you add, update, or remove a load balancer configuration, Amazon ECS starts a new deployment with the updated
    Elastic Load Balancing configuration. This causes tasks to register to and deregister from load balancers.

    We recommend that you verify this on a test environment before you update the Elastic Load Balancing configuration.

    A service-linked role is required for services that use multiple target groups. For more information, see `Using
    service-linked roles <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using-service-linked-roles.html>`_ in
    the *Amazon Elastic Container Service Developer Guide*.
    """

    targetGroupArn: str | None = None
    """
    The full Amazon Resource Name (ARN) of the Elastic Load Balancing target group or
    groups associated with a service or task set.
    """
    loadBalancerName: str | None = None
    """
    The name of the load balancer to associate with the Amazon ECS service or task set.
    """
    containerName: str | None = None
    """
    The name of the container (as it appears in a container definition) to associate
    with the load balancer.
    """
    containerPort: int | None = None
    """
    The port on the container to associate with the load balancer.

    This port must correspond to a ``containerPort`` in the
    task definition the tasks in the service are using. For tasks that use the EC2 launch type, the container instance
    they're launched on must allow ingress traffic on the ``hostPort`` of the port mapping.
    """
    advancedConfiguration: AdvancedConfiguration | None = None
    """
    The advanced settings for the load balancer used in blue/green deployments.

    Specify the alternate target group, listener rules, and IAM role required for
    traffic shifting during blue/green deployments.
    """


class ServiceRegistry(Boto3Model):
    """
    The details for the service registry.

    Each service may be associated with one service registry. Multiple service
    registries for each service are not supported.

    When you add, update, or remove the service registries configuration, Amazon ECS
    starts a new deployment. New tasks are registered and deregistered to the updated
    service registry configuration.
    """

    registryArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the service registry.

    The currently supported service registry is Cloud Map. For more information, see
    `CreateService <https://docs.aws.amazon.com/cloud-map/latest/api/API_CreateService.html>`_.
    """
    port: int | None = None
    """
    The port value used if your service discovery service specified an SRV record.

    This field might be used if both the
    ``awsvpc`` network mode and SRV records are used.
    """
    containerName: str | None = None
    """
    The container name value to be used for your service discovery service.

    It's already specified in the task definition.
    If the task definition that your service task specifies uses the ``bridge`` or ``host`` network mode, you must specify a
    ``containerName`` and ``containerPort`` combination from the task definition. If the task definition that your service
    task specifies uses the ``awsvpc`` network mode and a type SRV DNS record is used, you must specify either a
    ``containerName`` and ``containerPort`` combination or a ``port`` value. However, you can't specify both.
    """
    containerPort: int | None = None
    """
    The port value to be used for your service discovery service.

    It's already specified in the task definition. If the task
    definition your service task specifies uses the ``bridge`` or ``host`` network mode, you must specify a
    ``containerName`` and ``containerPort`` combination from the task definition. If the task definition your service task
    specifies uses the ``awsvpc`` network mode and a type SRV DNS record is used, you must specify either a
    ``containerName`` and ``containerPort`` combination or a ``port`` value. However, you can't specify both.
    """


class CapacityProviderStrategyItem(Boto3Model):
    """The details of a capacity provider strategy. A capacity provider strategy can be set when using the
    `RunTask <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html>`_or
    `CreateCluster <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateCluster.html>`_ APIs or as the default
    capacity provider strategy for a cluster with the ``CreateCluster`` API.

    Only capacity providers that are already associated with a cluster and have an ``ACTIVE`` or ``UPDATING`` status can be
    used in a capacity provider strategy. The `PutClusterCapacityProviders <https://docs.aws.amazon.com/AmazonECS/latest/API
    Reference/API_PutClusterCapacityProviders.html>`_ API is used to associate a capacity provider with a cluster.

    If specifying a capacity provider that uses an Auto Scaling group, the capacity provider must already be created. New
    Auto Scaling group capacity providers can be created with the `CreateClusterCapacityProvider <https://docs.aws.amazon.co
    m/AmazonECS/latest/APIReference/API_CreateClusterCapacityProvider.html>`_ API operation.

    To use a Fargate capacity provider, specify either the ``FARGATE`` or ``FARGATE_SPOT`` capacity providers. The Fargate
    capacity providers are available to all accounts and only need to be associated with a cluster to be used in a capacity
    provider strategy.

    With ``FARGATE_SPOT``, you can run interruption tolerant tasks at a rate that's discounted compared to the ``FARGATE``
    price. ``FARGATE_SPOT`` runs tasks on spare compute capacity. When Amazon Web Services needs the capacity back, your
    tasks are interrupted with a two-minute warning. ``FARGATE_SPOT`` supports Linux tasks with the X86_64 architecture on
    platform version 1.3.0 or later. ``FARGATE_SPOT`` supports Linux tasks with the ARM64 architecture on platform version
    1.4.0 or later.

    A capacity provider strategy can contain a maximum of 20 capacity providers.
    """

    capacityProvider: str
    """
    The short name of the capacity provider.
    """
    weight: int | None = None
    """
    The *weight* value designates the relative percentage of the total number of tasks
    launched that should use the specified capacity provider.

    The ``weight`` value is taken into consideration after the ``base`` value, if defined, is
    satisfied.
    """
    base: int | None = None
    """
    The *base* value designates how many tasks, at a minimum, to run on the specified
    capacity provider for each service.

    Only one capacity provider in a capacity provider strategy can have a *base* defined. If no value is specified, the
    default value of ``0`` is used.
    """


class DeploymentCircuitBreaker(Boto3Model):
    """
    The deployment circuit breaker can only be used for services using the rolling
    update (``ECS``) deployment type.

    The **deployment circuit breaker** determines whether a service deployment will fail
    if the service can't reach a steady state. If it is turned on, a service deployment
    will transition to a failed state and stop launching new tasks. You can also
    configure Amazon ECS to roll back your service to the last completed deployment
    after a failure. For more information, see
    `Rolling update <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-type-ecs.html>`_
     in the *Amazon Elastic Container Service Developer Guide*.

    For more information about API failure reasons, see
    `API failure reasons <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/api_failures_messages.html>`_
    in the *Amazon Elastic
    Container Service Developer Guide*.
    """

    enable: bool
    """
    Determines whether to use the deployment circuit breaker logic for the service.
    """
    rollback: bool
    """
    Determines whether to configure Amazon ECS to roll back the service if a service
    deployment fails.

    If rollback is on, when a service deployment fails, the service is rolled back to
    the last deployment that completed successfully.
    """


class DeploymentAlarms(Boto3Model):
    """
    One of the methods which provide a way for you to quickly identify when a deployment
    has failed, and then to optionally roll back the failure to the last working
    deployment.

    When the alarms are generated, Amazon ECS sets the service deployment to failed. Set the rollback parameter to have
    Amazon ECS to roll back your service to the last completed deployment after a failure.

    You can only use the ``DeploymentAlarms`` method to detect failures when the ``DeploymentController`` is set to ``ECS``.

    For more information, see `Rolling update <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-type-
    ecs.html>`_ in the  **Amazon Elastic Container Service Developer Guide** .
    """

    alarmNames: List[str]
    """
    One or more CloudWatch alarm names.

    Use a "," to separate the alarms.
    """
    rollback: bool
    """
    Determines whether to configure Amazon ECS to roll back the service if a service
    deployment fails.

    If rollback is used, when a service deployment fails, the service is rolled back to
    the last deployment that completed successfully.
    """
    enable: bool
    """
    Determines whether to use the CloudWatch alarm option in the service deployment
    process.
    """


class HookDetails(Boto3Model):
    pass


class DeploymentLifecycleHook(Boto3Model):
    """
    A deployment lifecycle hook runs custom logic at specific stages of the deployment
    process. Currently, you can use Lambda functions as hook targets.

    For more information, see
    `Lifecycle hooks for Amazon ECS service deployments <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-lifecycle-hooks.html>`_
    in the
    *Amazon Elastic Container Service Developer Guide*.
    """

    hookTargetArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the hook target.

    Currently, only Lambda function ARNs are supported.
    """
    roleArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the IAM role that grants Amazon ECS permission to
    call Lambda functions on your behalf.
    """
    lifecycleStages: List[Literal["RECONCILE_SERVICE", "PRE_SCALE_UP", "POST_SCALE_UP", "TEST_TRAFFIC_SHIFT", "POST_TEST_TRAFFIC_SHIFT", "PRODUCTION_TRAFFIC_SHIFT", "POST_PRODUCTION_TRAFFIC_SHIFT"]] | None = None
    """
    The lifecycle stages at which to run the hook.

    Choose from these valid values:
    """
    hookDetails: HookDetails | None = None
    """
    Use this field to specify custom parameters that Amazon ECS will pass to your hook
    target invocations (such as a Lambda function).
    """


class DeploymentConfiguration(Boto3Model):
    """
    Optional deployment parameters that control how many tasks run during a deployment
    and the ordering of stopping and starting tasks.
    """

    deploymentCircuitBreaker: DeploymentCircuitBreaker | None = None
    """
    The deployment circuit breaker can only be used for services using the rolling
    update (``ECS``) deployment type.
    """
    maximumPercent: int | None = None
    """
    If a service is using the rolling update (``ECS``) deployment type, the
    ``maximumPercent`` parameter represents an upper limit on the number of your
    service's tasks that are allowed in the ``RUNNING`` or ``PENDING`` state during a
    deployment, as a percentage of the ``desiredCount`` (rounded down to the nearest
    integer).

    This parameter enables you to
    define the deployment batch size. For example, if your service is using the ``REPLICA`` service scheduler and has a
    ``desiredCount`` of four tasks and a ``maximumPercent`` value of 200%, the scheduler may start four new tasks before
    stopping the four older tasks (provided that the cluster resources required to do this are available). The default
    ``maximumPercent`` value for a service using the ``REPLICA`` service scheduler is 200%.
    """
    minimumHealthyPercent: int | None = None
    """
    If a service is using the rolling update (``ECS``) deployment type, the
    ``minimumHealthyPercent`` represents a lower limit on the number of your service's
    tasks that must remain in the ``RUNNING`` state during a deployment, as a percentage
    of the ``desiredCount`` (rounded up to the nearest integer).

    This parameter enables you to deploy without
    using additional cluster capacity. For example, if your service has a ``desiredCount`` of four tasks and a
    ``minimumHealthyPercent`` of 50%, the service scheduler may stop two existing tasks to free up cluster capacity before
    starting two new tasks.
    """
    alarms: DeploymentAlarms | None = None
    """
    Information about the CloudWatch alarms.
    """
    strategy: Literal["ROLLING", "BLUE_GREEN"] | None = None
    """
    The deployment strategy for the service.

    Choose from these valid values:
    """
    bakeTimeInMinutes: int | None = None
    """
    The time period when both blue and green service revisions are running
    simultaneously after the production traffic has shifted.
    """
    lifecycleHooks: List["DeploymentLifecycleHook"] | None = None
    """
    An array of deployment lifecycle hook objects to run custom logic at specific stages
    of the deployment lifecycle.
    """


class AwsVpcConfiguration(Boto3Model):
    """
    An object representing the networking details for a task or service.

    For example
    ``awsVpcConfiguration={subnets=["subnet-12344321"],securityGroups=["sg-12344321"]}``.
    """

    subnets: List[str]
    """
    The IDs of the subnets associated with the task or service.

    There's a limit of 16 subnets that can be specified.
    """
    securityGroups: List[str] | None = None
    """
    The IDs of the security groups associated with the task or service.

    If you don't specify a security group, the default security group for the VPC is
    used. There's a limit of 5 security groups that can be specified.
    """
    assignPublicIp: Literal["ENABLED", "DISABLED"] | None = None
    """
    Whether the task's elastic network interface receives a public IP address.
    """


class NetworkConfiguration(Boto3Model):
    """
    The network configuration for a task or service.
    """

    awsvpcConfiguration: AwsVpcConfiguration | None = None
    """
    The VPC subnets and security groups that are associated with a task.
    """


class Scale(Boto3Model):
    """
    A floating-point percentage of the desired number of tasks to place and keep running
    in the task set.
    """

    value: float | None = None
    """
    The value, specified as a percent total of a service's ``desiredCount``, to scale
    the task set.

    Accepted values are numbers between 0 and 100.
    """
    unit: Literal["PERCENT"] | None = None
    """
    The unit of measure for the scale value.
    """


class DeploymentEphemeralStorage(Boto3Model):
    """
    The amount of ephemeral storage to allocate for the deployment.
    """

    kmsKeyId: str | None = None
    """
    Specify an Key Management Service key ID to encrypt the ephemeral storage for
    deployment.
    """


class TaskSet(TagsDictMixin, Boto3Model):
    """
    Information about a set of Amazon ECS tasks in either an CodeDeploy or an
    ``EXTERNAL`` deployment.

    An Amazon ECS task set includes details such as the desired number of tasks, how
    many tasks are running, and whether the task set serves production traffic.
    """

    tag_class: ClassVar[Type] = ECSTag
    Tags: List["ECSTag"] = Field(default_factory=list, alias="tags")
    """
    The metadata that you apply to the task set to help you categorize and organize
    them.

    Each tag consists of a key and an optional value. You define both.
    """
    id: str | None = None
    """
    The ID of the task set.
    """
    taskSetArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the task set.
    """
    serviceArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the service the task set exists in.
    """
    clusterArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the cluster that the service that hosts the task
    set exists in.
    """
    startedBy: str | None = None
    """
    The tag specified when a task set is started.

    If an CodeDeploy deployment created the task set, the ``startedBy``
    parameter is ``CODE_DEPLOY``. If an external deployment created the task set, the ``startedBy`` field isn't used.
    """
    externalId: str | None = None
    """
    The external ID associated with the task set.
    """
    status: str | None = None
    """
    The status of the task set.

    The following describes each state.
    """
    taskDefinition: str | None = None
    """
    The task definition that the task set is using.
    """
    computedDesiredCount: int | None = None
    """
    The computed desired count for the task set.

    This is calculated by multiplying the service's ``desiredCount`` by the
    task set's ``scale`` percentage. The result is always rounded up. For example, if the computed desired count is 1.2, it
    rounds up to 2 tasks.
    """
    pendingCount: int | None = None
    """
    The number of tasks in the task set that are in the ``PENDING`` status during a
    deployment.

    A task in the ``PENDING``
    state is preparing to enter the ``RUNNING`` state. A task set enters the ``PENDING`` status when it launches for the
    first time or when it's restarted after being in the ``STOPPED`` state.
    """
    runningCount: int | None = None
    """
    The number of tasks in the task set that are in the ``RUNNING`` status during a
    deployment.

    A task in the ``RUNNING``
    state is running and ready for use.
    """
    createdAt: datetime | None = None
    """
    The Unix timestamp for the time when the task set was created.
    """
    updatedAt: datetime | None = None
    """
    The Unix timestamp for the time when the task set was last updated.
    """
    launchType: Literal["EC2", "FARGATE", "EXTERNAL", "MANAGED_INSTANCES"] | None = (
        None
    )
    """
    The launch type the tasks in the task set are using.

    For more information, see
    `Amazon ECS launch types <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html>`_
    in the *Amazon Elastic Container
    Service Developer Guide*.
    """
    capacityProviderStrategy: List["CapacityProviderStrategyItem"] | None = None
    """
    The capacity provider strategy that are associated with the task set.
    """
    platformVersion: str | None = None
    """
    The Fargate platform version where the tasks in the task set are running.

    A platform version is only specified for tasks run on Fargate. For more information,
    see
    `Fargate platform versions <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html>`_
    in the *Amazon Elastic
    Container Service Developer Guide*.
    """
    platformFamily: str | None = None
    """
    The operating system that your tasks in the set are running on.

    A platform family is specified only for tasks that use the Fargate launch type.
    """
    networkConfiguration: NetworkConfiguration | None = None
    """
    The network configuration for the task set.
    """
    loadBalancers: List["LoadBalancerConfiguration"] | None = None
    """
    Details on a load balancer that are used with a task set.
    """
    serviceRegistries: List["ServiceRegistry"] | None = None
    """
    The details for the service discovery registries to assign to this task set.

    For more information, see
    `Service discovery <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-discovery.html>`_.
    """
    scale: Scale | None = None
    """
    A floating-point percentage of your desired number of tasks to place and keep
    running in the task set.
    """
    stabilityStatus: Literal["STEADY_STATE", "STABILIZING"] | None = None
    """
    The stability status.

    This indicates whether the task set has reached a steady state. If the following conditions are
    met, the task set are in ``STEADY_STATE``:
    """
    stabilityStatusAt: datetime | None = None
    """
    The Unix timestamp for the time when the task set stability status was retrieved.
    """
    fargateEphemeralStorage: DeploymentEphemeralStorage | None = None
    """
    The Fargate ephemeral storage settings for the task set.
    """


class ServiceConnectTestTrafficHeaderMatchRules(Boto3Model):
    """
    The header matching rules for test traffic routing in Amazon ECS blue/green
    deployments.

    These rules determine how incoming requests are matched based on HTTP headers to
    route test traffic to the new service revision.
    """

    exact: str
    """
    The exact value that the HTTP header must match for the test traffic routing rule to
    apply.

    This provides precise control over which requests are routed to the new service
    revision during blue/green deployments.
    """


class ServiceConnectTestTrafficHeaderRules(Boto3Model):
    """
    The HTTP header rules used to identify and route test traffic during Amazon ECS
    blue/green deployments. These rules specify which HTTP headers to examine and what
    values to match for routing decisions.

    For more information, see `Service Connect for Amazon ECS blue/green
    deployments <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-connect-blue-green.html>`_ in the
    *Amazon Elastic Container Service Developer Guide*.
    """

    name: str
    """
    The name of the HTTP header to examine for test traffic routing.

    Common examples include custom headers like ``X-Test-
    Version`` or ``X-Canary-Request`` that can be used to identify test traffic.
    """
    value: ServiceConnectTestTrafficHeaderMatchRules | None = None
    """
    The header value matching configuration that determines how the HTTP header value is
    evaluated for test traffic routing decisions.
    """


class ServiceConnectTestTrafficRules(Boto3Model):
    """
    The test traffic routing configuration for Amazon ECS blue/green deployments. This
    configuration allows you to define rules for routing specific traffic to the new
    service revision during the deployment process, allowing for safe testing before
    full production traffic shift.

    For more information, see `Service Connect for Amazon ECS blue/green
    deployments <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-connect-blue-green.html>`_ in the
    *Amazon Elastic Container Service Developer Guide*.
    """

    header: ServiceConnectTestTrafficHeaderRules
    """
    The HTTP header-based routing rules that determine which requests should be routed
    to the new service version during blue/green deployment testing.

    These rules provide fine-grained control over test traffic routing based on request
    headers.
    """


class ServiceConnectClientAlias(Boto3Model):
    """
    Each alias ("endpoint") is a fully-qualified name and port number that other tasks
    ("clients") can use to connect to this service.

    Each name and port mapping must be unique within the namespace.

    Tasks that run in a namespace can use short names to connect to services in the
    namespace. Tasks can connect to services across all of the clusters in the
    namespace. Tasks connect through a managed proxy container that collects logs and
    metrics for increased visibility. Only the tasks that Amazon ECS services create are
    supported with Service Connect. For more information, see
    `Service Connect <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-
    connect.html>`_ in the *Amazon Elastic Container Service Developer Guide*.
    """

    port: int
    """
    The listening port number for the Service Connect proxy.

    This port is available inside of all of the tasks within the same namespace.
    """
    dnsName: str | None = None
    """
    The ``dnsName`` is the name that you use in the applications of client tasks to
    connect to this service.

    The name must be a valid DNS name but doesn't need to be fully-qualified. The name
    can include up to 127 characters. The name can include lowercase letters, numbers,
    underscores (_), hyphens (-), and periods (.). The name can't start with a hyphen.
    """
    testTrafficRules: ServiceConnectTestTrafficRules | None = None
    """
    The configuration for test traffic routing rules used during blue/green deployments
    with Amazon ECS Service Connect.

    This allows you to route a portion of traffic to the new service revision of your
    service for testing before shifting all production traffic.
    """


class TimeoutConfiguration(Boto3Model):
    """
    An object that represents the timeout configurations for Service Connect.

    If ``idleTimeout`` is set to a time that is less than ``perRequestTimeout``, the connection will close when the
    ``idleTimeout`` is reached and not the ``perRequestTimeout``.
    """

    idleTimeoutSeconds: int | None = None
    """
    The amount of time in seconds a connection will stay active while idle.

    A value of ``0`` can be set to disable
    ``idleTimeout``.
    """
    perRequestTimeoutSeconds: int | None = None
    """
    The amount of time waiting for the upstream to respond with a complete response per
    request.

    A value of ``0`` can be set
    to disable ``perRequestTimeout``. ``perRequestTimeout`` can only be set if Service Connect ``appProtocol`` isn't
    ``TCP``. Only ``idleTimeout`` is allowed for ``TCP`` ``appProtocol``.
    """


class ServiceConnectTlsCertificateAuthority(Boto3Model):
    """
    The certificate root authority that secures your service.
    """

    awsPcaAuthorityArn: str | None = None
    """
    The ARN of the Amazon Web Services Private Certificate Authority certificate.
    """


class ServiceConnectTlsConfiguration(Boto3Model):
    """
    The key that encrypts and decrypts your resources for Service Connect TLS.
    """

    issuerCertificateAuthority: ServiceConnectTlsCertificateAuthority
    """
    The signer certificate authority.
    """
    kmsKey: str | None = None
    """
    The Amazon Web Services Key Management Service key.
    """
    roleArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the IAM role that's associated with the Service
    Connect TLS.
    """


class ServiceConnectService(Boto3Model):
    """
    The Service Connect service object configuration.

    For more information, see
    `Service Connect <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-connect.html>`_
    in the *Amazon Elastic
    Container Service Developer Guide*.
    """

    portName: str
    """
    The ``portName`` must match the name of one of the ``portMappings`` from all the
    containers in the task definition of this Amazon ECS service.
    """
    discoveryName: str | None = None
    """
    The ``discoveryName`` is the name of the new Cloud Map service that Amazon ECS
    creates for this Amazon ECS service.

    This must be unique within the Cloud Map namespace. The name can contain up to 64
    characters. The name can include lowercase letters, numbers, underscores (_), and
    hyphens (-). The name can't start with a hyphen.
    """
    clientAliases: List["ServiceConnectClientAlias"] | None = None
    """
    The list of client aliases for this Service Connect service.

    You use these to assign names that can be used by client applications. The maximum
    number of client aliases that you can have in this list is 1.
    """
    ingressPortOverride: int | None = None
    """
    The port number for the Service Connect proxy to listen on.
    """
    timeout: TimeoutConfiguration | None = None
    """
    A reference to an object that represents the configured timeouts for Service
    Connect.
    """
    tls: ServiceConnectTlsConfiguration | None = None
    """
    A reference to an object that represents a Transport Layer Security (TLS)
    configuration.
    """


class Secret(Boto3Model):
    """An object representing the secret to expose to your container. Secrets can be exposed to a container in the following
    ways:

    * To inject sensitive data into your containers as environment variables, use the ``secrets`` container definition
      parameter.
    * To reference sensitive information in the log configuration of a container, use the ``secretOptions`` container
      definition parameter.

    For more information, see `Specifying sensitive
    data <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/specifying-sensitive-data.html>`_ in the *Amazon Elastic
    Container Service Developer Guide*.
    """

    name: str
    """
    The name of the secret.
    """
    valueFrom: str
    """
    The secret to expose to the container.

    The supported values are either the full ARN of the Secrets Manager secret or the
    full ARN of the parameter in the SSM Parameter Store.
    """


class LogConfiguration(Boto3Model):
    """
    The log configuration for the container. This parameter maps to ``LogConfig`` in the
    docker container create command and the ``--log-driver`` option to docker run.

    By default, containers use the same logging driver that the Docker daemon uses. However, the container might use a
    different logging driver than the Docker daemon by specifying a log driver configuration in the container definition.

    Understand the following when specifying a log configuration for your containers.

    * Amazon ECS currently supports a subset of the logging drivers available to the Docker daemon. Additional log drivers
      may be available in future releases of the Amazon ECS container agent.

    For tasks on Fargate, the supported log drivers are ``awslogs``, ``splunk``, and ``awsfirelens``.

    For tasks hosted on Amazon EC2 instances, the supported log drivers are ``awslogs``, ``fluentd``, ``gelf``, ``json-
    file``, ``journald``,``syslog``, ``splunk``, and ``awsfirelens``.

    * This parameter requires version 1.18 of the Docker Remote API or greater on your container instance.
    * For tasks that are hosted on Amazon EC2 instances, the Amazon ECS container agent must register the available logging
      drivers with the ``ECS_AVAILABLE_LOGGING_DRIVERS`` environment variable before containers placed on that instance can
      use these log configuration options. For more information, see `Amazon ECS container agent
      configuration <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-agent-config.html>`_ in the *Amazon Elastic
      Container Service Developer Guide*.
    * For tasks that are on Fargate, because you don't have access to the underlying infrastructure your tasks are hosted
      on, any additional software needed must be installed outside of the task. For example, the Fluentd output aggregators or
      a remote host running Logstash to send Gelf logs to.
    """

    logDriver: Literal[
        "json-file",
        "syslog",
        "journald",
        "gelf",
        "fluentd",
        "awslogs",
        "splunk",
        "awsfirelens",
    ]
    """
    The log driver to use for the container.
    """
    options: Dict[str, str] | None = None
    """
    The configuration options to send to the log driver.
    """
    secretOptions: List["Secret"] | None = None
    """
    The secrets to pass to the log configuration.

    For more information, see
    `Specifying sensitive data <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/specifying-sensitive-data.html>`_
    in the *Amazon Elastic
    Container Service Developer Guide*.
    """


class ServiceConnectConfiguration(Boto3Model):
    """
    The Service Connect configuration of your Amazon ECS service. The configuration for
    this service to discover and connect to services, and be discovered by, and
    connected from, other services within a namespace.

    Tasks that run in a namespace can use short names to connect to services in the
    namespace. Tasks can connect to services across all of the clusters in the
    namespace. Tasks connect through a managed proxy container that collects logs and
    metrics for increased visibility. Only the tasks that Amazon ECS services create are
    supported with Service Connect. For more information, see
    `Service Connect <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-
    connect.html>`_ in the *Amazon Elastic Container Service Developer Guide*.
    """

    enabled: bool
    """
    Specifies whether to use Service Connect with this service.
    """
    namespace: str | None = None
    """
    The namespace name or full Amazon Resource Name (ARN) of the Cloud Map namespace for
    use with Service Connect.

    The namespace must be in the same Amazon Web Services Region as the Amazon ECS
    service and cluster. The type of namespace doesn't affect Service Connect. For more
    information about Cloud Map, see
    `Working with Services <https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-services.html>`_
    in the *Cloud Map Developer
    Guide*.
    """
    services: List["ServiceConnectService"] | None = None
    """
    The list of Service Connect service objects.

    These are names and aliases (also known as endpoints) that are used by other Amazon
    ECS services to connect to this service.
    """
    logConfiguration: LogConfiguration | None = None
    """
    The log configuration for the container.

    This parameter maps to ``LogConfig`` in the docker container create command and
    the ``--log-driver`` option to docker run.
    """


class ServiceConnectServiceResource(Boto3Model):
    """
    The Service Connect resource. Each configuration maps a discovery name to a Cloud
    Map service name. The data is stored in Cloud Map as part of the Service Connect
    configuration for each discovery name of this Amazon ECS service.

    A task can resolve the ``dnsName`` for each of the ``clientAliases`` of a service. However a task can't resolve the
    discovery names. If you want to connect to a service, refer to the ``ServiceConnectConfiguration`` of that service for
    the list of ``clientAliases`` that you can use.
    """

    discoveryName: str | None = None
    """
    The discovery name of this Service Connect resource.
    """
    discoveryArn: str | None = None
    """
    The Amazon Resource Name (ARN) for the service in Cloud Map that matches the
    discovery name for this Service Connect resource.

    You can use this ARN in other integrations with Cloud Map. However, Service Connect
    can't ensure connectivity outside of Amazon ECS.
    """


class EBSTagSpecification(TagsDictMixin, Boto3Model):
    """
    The tag specifications of an Amazon EBS volume.
    """

    tag_class: ClassVar[Type] = ECSTag
    Tags: List["ECSTag"] = Field(default_factory=list, alias="tags")
    """
    The tags applied to this Amazon EBS volume.

    ``AmazonECSCreated`` and ``AmazonECSManaged`` are reserved tags that can't
    be used.
    """
    resourceType: Literal["volume"]
    """
    The type of volume resource.
    """
    propagateTags: Literal["TASK_DEFINITION", "SERVICE", "NONE"] | None = None
    """
    Determines whether to propagate the tags from the task definition to the Amazon EBS
    volume.

    Tags can only propagate to
    a ``SERVICE`` specified in
    ``ServiceVolumeConfiguration``. If no value is specified, the tags aren't
    propagated.
    """


class ServiceManagedEBSVolumeConfiguration(Boto3Model):
    """The configuration for the Amazon EBS volume that Amazon ECS creates and manages on your behalf. These settings are used
    to create each Amazon EBS volume, with one volume created for each task in the service. For information about the
    supported launch types and operating systems, see `Supported operating systems and launch
    types <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ebs-volumes.html#ebs-volumes-configuration>`_ in the
    *Amazon Elastic Container Service Developer Guide*.

    Many of these parameters map 1:1 with the Amazon EBS ``CreateVolume`` API request parameters.
    """

    encrypted: bool | None = None
    """
    Indicates whether the volume should be encrypted.

    If you turn on Region-level Amazon EBS encryption by default but set
    this value as ``false``, the setting is overridden and the volume is encrypted with the KMS key specified for Amazon EBS
    encryption by default. This parameter maps 1:1 with the ``Encrypted`` parameter of the `CreateVolume
    API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the *Amazon EC2 API Reference*.
    """
    kmsKeyId: str | None = None
    """
    The Amazon Resource Name (ARN) identifier of the Amazon Web Services Key Management
    Service key to use for Amazon EBS encryption.

    When a key is specified using this parameter, it overrides Amazon EBS default encryption or any KMS key that
    you specified for cluster-level managed storage encryption. This parameter maps 1:1 with the ``KmsKeyId`` parameter of
    the `CreateVolume API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the *Amazon EC2
    API Reference*. For more information about encrypting Amazon EBS volumes attached to tasks, see `Encrypt data stored in
    Amazon EBS volumes attached to Amazon ECS tasks <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ebs-kms-
    encryption.html>`_.
    """
    volumeType: str | None = None
    """
    The volume type.

    This parameter maps 1:1 with the ``VolumeType`` parameter of the `CreateVolume
    API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the *Amazon EC2 API Reference*.
    For more information, see `Amazon EBS volume types <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volume-
    types.html>`_ in the *Amazon EC2 User Guide*.
    """
    sizeInGiB: int | None = None
    """
    The size of the volume in GiB.

    You must specify either a volume size or a snapshot ID. If you specify a snapshot ID, the
    snapshot size is used for the volume size by default. You can optionally specify a volume size greater than or equal to
    the snapshot size. This parameter maps 1:1 with the ``Size`` parameter of the `CreateVolume
    API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the *Amazon EC2 API Reference*.
    """
    snapshotId: str | None = None
    """
    The snapshot that Amazon ECS uses to create volumes for attachment to tasks
    maintained by the service.

    You must specify
    either ``snapshotId`` or ``sizeInGiB`` in your volume configuration. This parameter maps 1:1 with the ``SnapshotId``
    parameter of the `CreateVolume API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the
    *Amazon EC2 API Reference*.
    """
    volumeInitializationRate: int | None = None
    """
    The rate, in MiB/s, at which data is fetched from a snapshot of an existing EBS
    volume to create new volumes for attachment to the tasks maintained by the service.

    This property can be specified only if you specify a ``snapshotId``.
    For more information, see `Initialize Amazon EBS volumes <https://docs.aws.amazon.com/ebs/latest/userguide/initalize-
    volume.html>`_ in the *Amazon EBS User Guide*.
    """
    iops: int | None = None
    """
    The number of I/O operations per second (IOPS).

    For ``gp3``, ``io1``, and ``io2`` volumes, this represents the number of
    IOPS that are provisioned for the volume. For ``gp2`` volumes, this represents the baseline performance of the volume
    and the rate at which the volume accumulates I/O credits for bursting.
    """
    throughput: int | None = None
    """
    The throughput to provision for a volume, in MiB/s, with a maximum of 1,000 MiB/s.

    This parameter maps 1:1 with the
    ``Throughput`` parameter of the `CreateVolume
    API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the *Amazon EC2 API Reference*.
    """
    tagSpecifications: List["EBSTagSpecification"] | None = None
    """
    The tags to apply to the volume.

    Amazon ECS applies service-managed tags by default. This parameter maps 1:1 with the
    ``TagSpecifications.N`` parameter of the `CreateVolume
    API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the *Amazon EC2 API Reference*.
    """
    roleArn: str
    """
    The ARN of the IAM role to associate with this volume.

    This is the Amazon ECS infrastructure IAM role that is used to
    manage your Amazon Web Services infrastructure. We recommend using the Amazon ECS-managed
    ``AmazonECSInfrastructureRolePolicyForVolumes`` IAM policy with this role. For more information, see `Amazon ECS
    infrastructure IAM role <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/infrastructure_IAM_role.html>`_ in
    the *Amazon ECS Developer Guide*.
    """
    filesystemType: Literal["ext3", "ext4", "xfs", "ntfs"] | None = None
    """
    The filesystem type for the volume.

    For volumes created from a snapshot, you must specify the same filesystem type that
    the volume was using when the snapshot was created. If there is a filesystem type
    mismatch, the tasks will fail to start.
    """


class ServiceVolumeConfiguration(Boto3Model):
    """
    The configuration for a volume specified in the task definition as a volume that is
    configured at launch time.

    Currently, the only supported volume type is an Amazon EBS volume.
    """

    name: str
    """
    The name of the volume.

    This value must match the volume name from the ``Volume`` object in the task definition.
    """
    managedEBSVolume: ServiceManagedEBSVolumeConfiguration | None = None
    """
    The configuration for the Amazon EBS volume that Amazon ECS creates and manages on
    your behalf.

    These settings are used to create each Amazon EBS volume, with one volume created
    for each task in the service. The Amazon EBS volumes are visible in your account in
    the Amazon EC2 console once they are created.
    """


class VpcLatticeConfiguration(Boto3Model):
    """
    The VPC Lattice configuration for your service that holds the information for the
    target group(s) Amazon ECS tasks will be registered to.
    """

    roleArn: str
    """
    The ARN of the IAM role to associate with this VPC Lattice configuration.

    This is the Amazon ECS  infrastructure IAM role that is used to manage your VPC
    Lattice infrastructure.
    """
    targetGroupArn: str
    """
    The full Amazon Resource Name (ARN) of the target group or groups associated with
    the VPC Lattice configuration that the Amazon ECS tasks will be registered to.
    """
    portName: str
    """
    The name of the port mapping to register in the VPC Lattice target group.

    This is the name of the ``portMapping`` you
    defined in your task definition.
    """


class Deployment(ReadonlyBoto3Model):
    """
    The details of an Amazon ECS service deployment.

    This is used only when a service uses the ``ECS`` deployment controller
    type.
    """

    id: str | None = None
    """
    The ID of the deployment.
    """
    status: str | None = None
    """
    The status of the deployment.

    The following describes each state.
    """
    taskDefinition: str | None = None
    """
    The most recent task definition that was specified for the tasks in the service to
    use.
    """
    desiredCount: int | None = None
    """
    The most recent desired count of tasks that was specified for the service to deploy
    or maintain.
    """
    pendingCount: int | None = None
    """
    The number of tasks in the deployment that are in the ``PENDING`` status.
    """
    runningCount: int | None = None
    """
    The number of tasks in the deployment that are in the ``RUNNING`` status.
    """
    failedTasks: int | None = None
    """
    The number of consecutively failed tasks in the deployment.

    A task is considered a failure if the service scheduler
    can't launch the task, the task doesn't transition to a ``RUNNING`` state, or if it fails any of its defined health
    checks and is stopped.
    """
    createdAt: datetime | None = None
    """
    The Unix timestamp for the time when the service deployment was created.
    """
    updatedAt: datetime | None = None
    """
    The Unix timestamp for the time when the service deployment was last updated.
    """
    capacityProviderStrategy: List["CapacityProviderStrategyItem"] | None = None
    """
    The capacity provider strategy that the deployment is using.
    """
    launchType: Literal["EC2", "FARGATE", "EXTERNAL", "MANAGED_INSTANCES"] | None = (
        None
    )
    """
    The launch type the tasks in the service are using.

    For more information, see
    `Amazon ECS Launch Types <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html>`_
    in the *Amazon Elastic Container
    Service Developer Guide*.
    """
    platformVersion: str | None = None
    """
    The platform version that your tasks in the service run on.

    A platform version is only specified for tasks using the
    Fargate launch type. If one isn't specified, the ``LATEST`` platform version is used. For more information, see `Fargate
    Platform Versions <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html>`_ in the *Amazon
    Elastic Container Service Developer Guide*.
    """
    platformFamily: str | None = None
    """
    The operating system that your tasks in the service, or tasks are running on.

    A platform family is specified only for tasks using the Fargate launch type.
    """
    networkConfiguration: NetworkConfiguration | None = None
    """
    The VPC subnet and security group configuration for tasks that receive their own
    elastic network interface by using the ``awsvpc`` networking mode.
    """
    rolloutState: Literal["COMPLETED", "FAILED", "IN_PROGRESS"] | None = None
    """
    The ``rolloutState`` of a service is only returned for services that use the rolling
    update (``ECS``) deployment type that aren't behind a Classic Load Balancer.
    """
    rolloutStateReason: str | None = None
    """
    A description of the rollout state of a deployment.
    """
    serviceConnectConfiguration: ServiceConnectConfiguration | None = None
    """
    The details of the Service Connect configuration that's used by this deployment.

    Compare the configuration between multiple deployments when troubleshooting issues
    with new deployments.
    """
    serviceConnectResources: List["ServiceConnectServiceResource"] | None = None
    """
    The list of Service Connect resources that are associated with this deployment.

    Each list entry maps a discovery name to a Cloud Map service name.
    """
    volumeConfigurations: List["ServiceVolumeConfiguration"] | None = None
    """
    The details of the volume that was ``configuredAtLaunch``.

    You can configure different settings like the size,
    throughput, volumeType, and ecryption in `ServiceManagedEBSVolumeConfiguration <https://docs.aws.amazon.com/AmazonECS/la
    test/APIReference/API_ServiceManagedEBSVolumeConfiguration.html>`_. The ``name`` of the volume must match the ``name``
    from the task definition.
    """
    fargateEphemeralStorage: DeploymentEphemeralStorage | None = None
    """
    The Fargate ephemeral storage settings for the deployment.
    """
    vpcLatticeConfigurations: List["VpcLatticeConfiguration"] | None = None
    """
    The VPC Lattice configuration for the service deployment.
    """


class ServiceEvent(Boto3Model):
    """
    The details for an event that's associated with a service.
    """

    id: str | None = None
    """
    The ID string for the event.
    """
    createdAt: datetime | None = None
    """
    The Unix timestamp for the time when the event was triggered.
    """
    message: str | None = None
    """
    The event message.
    """


class PlacementConstraint(Boto3Model):
    """An object representing a constraint on task placement. For more information, see `Task placement
    constraints <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-constraints.html>`_ in the *Amazon
    Elastic Container Service Developer Guide*.

    If you're using the Fargate launch type, task placement constraints aren't supported.
    """

    type: Literal["distinctInstance", "memberOf"] | None = None
    """
    The type of constraint.

    Use ``distinctInstance`` to ensure that each task in a particular group is running on a
    different container instance. Use ``memberOf`` to restrict the selection to a group of valid candidates.
    """
    expression: str | None = None
    """
    A cluster query language expression to apply to the constraint.

    The expression can have a maximum length of 2000
    characters. You can't specify an expression if the constraint type is ``distinctInstance``. For more information, see
    `Cluster query language <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-query-language.html>`_ in the
    *Amazon Elastic Container Service Developer Guide*.
    """


class PlacementStrategy(Boto3Model):
    """
    The task placement strategy for a task or service.

    For more information, see
    `Task placement strategies <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-strategies.html>`_
    in the *Amazon
    Elastic Container Service Developer Guide*.
    """

    type: Literal["random", "spread", "binpack"] | None = None
    """
    The type of placement strategy.

    The ``random`` placement strategy randomly places tasks on available candidates. The
    ``spread`` placement strategy spreads placement across available candidates evenly based on the ``field`` parameter. The
    ``binpack`` strategy places tasks on available candidates that have the least available amount of the resource that's
    specified with the ``field`` parameter. For example, if you binpack on memory, a task is placed on the instance with the
    least amount of remaining memory but still enough to run the task.
    """
    field: str | None = None
    """
    The field to apply the placement strategy against.

    For the ``spread`` placement strategy, valid values are
    ``instanceId`` (or ``host``, which has the same effect), or any platform or custom attribute that's applied to a
    container instance, such as ``attribute:ecs.availability-zone``. For the ``binpack`` placement strategy, valid values
    are ``cpu`` and ``memory``. For the ``random`` placement strategy, this field is not used.
    """


class DeploymentController(Boto3Model):
    """
    The deployment controller to use for the service.
    """

    type: Literal["ECS", "CODE_DEPLOY", "EXTERNAL"]
    """
    The deployment controller type to use.
    """


class Service(TagsDictMixin, ECSServiceModelMixin, PrimaryBoto3Model):
    """
    Details on a service within a cluster.
    """

    tag_class: ClassVar[Type] = ECSTag
    manager_class: ClassVar[Type[Boto3ModelManager]] = ServiceManager

    serviceName: str
    """
    The name of your service.

    Up to 255 letters (uppercase and lowercase), numbers, underscores, and hyphens are
    allowed. Service names must be unique within a cluster. However, you can have
    similarly named services in multiple clusters within a Region or across multiple
    Regions.
    """
    taskDefinition: str
    """
    The task definition to use for tasks in the service.

    This value is specified when the service is created with
    `CreateService <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html>`_,
    and it can be    modified with
    `UpdateService <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateService.html>`_.
    """
    clusterArn: str
    """
    The Amazon Resource Name (ARN) of the cluster that hosts the service.
    """
    desiredCount: int
    """
    The desired number of instantiations of the task definition to keep running on the
    service.

    This value is specified when the service is created with
    `CreateService <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html>`_
    , and it can be    modified with
    `UpdateService <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateService.html>`_.
    """
    launchType: Literal["EC2", "FARGATE", "EXTERNAL", "MANAGED_INSTANCES"]
    """
    The launch type the service is using.

    When using the DescribeServices API, this field is omitted if the service was
    created using a capacity provider strategy.
    """
    schedulingStrategy: Literal["REPLICA", "DAEMON"]
    """
    The scheduling strategy to use for the service.

    For more information, see
    `Services <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html>`_.
    """
    Tags: List["ECSTag"] = Field(default_factory=list, alias="tags")
    """
    The metadata that you apply to the service to help you categorize and organize them.

    Each tag consists of a key and an optional value. You define bot the key and value.
    """
    serviceArn: str = Field(default=None, frozen=True)
    """
    The ARN that identifies the service.

    For more information about the ARN format, see `Amazon Resource Name
    (ARN) <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-account-settings.html#ecs-resource-ids>`_ in the
    *Amazon ECS Developer Guide*.
    """
    loadBalancers: List["LoadBalancerConfiguration"] | None = None
    """
    A list of Elastic Load Balancing load balancer objects.

    It contains the load balancer name, the container name, and the container port to
    access from the load balancer. The container name is as it appears in a container
    definition.
    """
    serviceRegistries: List["ServiceRegistry"] | None = None
    """
    The details for the service discovery registries to assign to this service.

    For more information, see
    `Service Discovery <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-discovery.html>`_.
    """
    status: str = Field(default=None, frozen=True)
    """
    The status of the service.

    The valid values are ``ACTIVE``, ``DRAINING``, or ``INACTIVE``.
    """
    runningCount: int = Field(default=None, frozen=True)
    """
    The number of tasks in the cluster that are in the ``RUNNING`` state.
    """
    pendingCount: int = Field(default=None, frozen=True)
    """
    The number of tasks in the cluster that are in the ``PENDING`` state.
    """
    capacityProviderStrategy: List["CapacityProviderStrategyItem"] | None = None
    """
    The capacity provider strategy the service uses.

    When using the DescribeServices API, this field is omitted if the service was
    created using a launch type.
    """
    platformVersion: str | None = None
    """
    The platform version to run your service on.

    A platform version is only specified for tasks that are hosted on Fargate.
    If one isn't specified, the ``LATEST`` platform version is used. For more information, see `Fargate Platform
    Versions <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html>`_ in the *Amazon Elastic
    Container Service Developer Guide*.
    """
    platformFamily: str = Field(default=None, frozen=True)
    """
    The operating system that your tasks in the service run on.

    A platform family is specified only for tasks using the Fargate launch type.
    """
    deploymentConfiguration: DeploymentConfiguration | None = None
    """
    Optional deployment parameters that control how many tasks run during the deployment
    and the ordering of stopping and starting tasks.
    """
    taskSets: List["TaskSet"] = Field(default_factory=list, frozen=True)
    """
    Information about a set of Amazon ECS tasks in either an CodeDeploy or an
    ``EXTERNAL`` deployment.

    An Amazon ECS task set includes details such as the desired number of tasks, how
    many tasks are running, and whether the task set serves production traffic.
    """
    deployments: List["Deployment"] = Field(default_factory=list, frozen=True)
    """
    The current state of deployments for the service.
    """
    roleArn: str = Field(default=None, frozen=True)
    """
    The ARN of the IAM role that's associated with the service.

    It allows the Amazon ECS container agent to register container instances with an
    Elastic Load Balancing load balancer.
    """
    events: List["ServiceEvent"] = Field(default_factory=list, frozen=True)
    """
    The event stream for your service.

    A maximum of 100 of the latest events are displayed.
    """
    createdAt: datetime = Field(default=None, frozen=True)
    """
    The Unix timestamp for the time when the service was created.
    """
    placementConstraints: List["PlacementConstraint"] | None = None
    """
    The placement constraints for the tasks in the service.
    """
    placementStrategy: List["PlacementStrategy"] | None = None
    """
    The placement strategy that determines how tasks for the service are placed.
    """
    networkConfiguration: NetworkConfiguration | None = None
    """
    The VPC subnet and security group configuration for tasks that receive their own
    elastic network interface by using the ``awsvpc`` networking mode.
    """
    healthCheckGracePeriodSeconds: int | None = None
    """
    The period of time, in seconds, that the Amazon ECS service scheduler ignores
    unhealthy Elastic Load Balancing, VPC Lattice, and container health checks after a
    task has first started.
    """
    deploymentController: DeploymentController | None = None
    """
    The deployment controller type the service is using.
    """
    createdBy: str = Field(default=None, frozen=True)
    """
    The principal that created the service.
    """
    enableECSManagedTags: bool | None = None
    """
    Determines whether to use Amazon ECS managed tags for the tasks in the service.

    For more information, see
    `Tagging Your Amazon ECS Resources <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-using-tags.html>`_
    in the *Amazon
    Elastic Container Service Developer Guide*.
    """
    propagateTags: Literal["TASK_DEFINITION", "SERVICE", "NONE"] | None = None
    """
    Determines whether to propagate the tags from the task definition or the service to
    the task.

    If no value is specified, the tags aren't propagated.
    """
    enableExecuteCommand: bool | None = None
    """
    Determines whether the execute command functionality is turned on for the service.

    If ``true``, the execute command
    functionality is turned on for all containers in tasks as part of the service.
    """
    availabilityZoneRebalancing: Literal["ENABLED", "DISABLED"] | None = None
    """
    Indicates whether to use Availability Zone rebalancing for the service.
    """

    @property
    def arn(self) -> str | None:
        """
        Return the ARN of the model.   This is the value of the :py:attr:`serviceArn`
        attribute.

        Returns:
            The ARN of the model instance.
        """
        return self.serviceArn

    @property
    def name(self) -> str | None:
        """
        Return the name of the model.   This is the value of the :py:attr:`serviceName`
        attribute.

        Returns:
            The name of the model instance.
        """
        return self.serviceName

    @property
    def pk(self) -> OrderedDict[str, Any]:
        """
        The primary key of the service.

        This can be used to get the service with the :py:meth:`botocraft.services.ecs.ServiceManager.get` method, or to do :py:meth:`botocraft.services.ecs.ServiceManager.partial_update`.
        """

        return OrderedDict(
            {
                "service": self.serviceName,
                "cluster": self.clusterArn,
            }
        )

    @property
    def cluster_name(self) -> str | None:
        """
        The name of the cluster that houses this service.
        """

        return self.transform("clusterArn", r"^.*:cluster/(.+)$")

    @cached_property
    def cluster(self) -> Optional["Cluster"]:
        """
        Return the :py:class:`Cluster` object that this service belongs to, if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "cluster": self.clusterArn,
                }
            )
        except AttributeError:
            return None
        return Cluster.objects.using(self.session).get(**pk)  # type: ignore[arg-type]

    @cached_property
    def task_definition(self) -> Optional["TaskDefinition"]:
        """
        Return the :py:class:`TaskDefinition` object that this service uses, if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "taskDefinition": self.taskDefinition,
                }
            )
        except AttributeError:
            return None
        return TaskDefinition.objects.using(self.session).get(**pk)  # type: ignore[arg-type]

    @property
    def tasks(self) -> List["Task"] | None:
        """
        Return the ARNs of :py:class:`Task` objects that run in this service, if any.
        """

        try:
            pk = OrderedDict(
                {
                    "serviceName": self.serviceName,
                    "cluster": self.clusterArn,
                }
            )
        except AttributeError:
            return []
        return Task.objects.using(self.session).list(**pk)  # type: ignore[arg-type]

    @cached_property
    def target_groups(self) -> List["TargetGroup"] | None:
        """
        Return the target groups that are associated with this service, if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "TargetGroupArns": [
                        lb.targetGroupArn
                        for lb in self.loadBalancers
                        if lb.targetGroupArn
                    ],
                }
            )
        except AttributeError:
            return []
        return TargetGroup.objects.using(self.session).list(**pk)  # type: ignore[arg-type]

    @cached_property
    def scalable_targets(self) -> List["ScalableTarget"] | None:
        """
        Return the scalable targets that are associated with this service, if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "ServiceNamespace": "ecs",
                    "ResourceIds": f"service/{self.cluster_name}/{self.serviceName}",
                }
            )
        except AttributeError:
            return []
        return ScalableTarget.objects.using(self.session).list(**pk)  # type: ignore[arg-type]

    @cached_property
    def service_deployments(self) -> List["ServiceDeployment"] | None:
        """
        Return the ARNs of :py:class:`ServiceDeployment` objects that run in this
        service, if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "service": self.serviceName,
                    "cluster": self.clusterArn,
                }
            )
        except AttributeError:
            return []
        return ServiceDeployment.objects.using(self.session).list(**pk)  # type: ignore[arg-type]


class ExecuteCommandLogConfiguration(Boto3Model):
    """
    The log configuration for the results of the execute command actions.

    The logs can be sent to CloudWatch Logs or an Amazon S3 bucket.
    """

    cloudWatchLogGroupName: str | None = None
    """
    The name of the CloudWatch log group to send logs to.
    """
    cloudWatchEncryptionEnabled: bool | None = None
    """
    Determines whether to use encryption on the CloudWatch logs.

    If not specified, encryption will be off.
    """
    s3BucketName: str | None = None
    """
    The name of the S3 bucket to send logs to.
    """
    s3EncryptionEnabled: bool | None = None
    """
    Determines whether to use encryption on the S3 logs.

    If not specified, encryption is not used.
    """
    s3KeyPrefix: str | None = None
    """
    An optional folder in the S3 bucket to place logs in.
    """


class ExecuteCommandConfiguration(Boto3Model):
    """
    The details of the execute command configuration.
    """

    kmsKeyId: str | None = None
    """
    Specify an Key Management Service key ID to encrypt the data between the local
    client and the container.
    """
    logging: Literal["NONE", "DEFAULT", "OVERRIDE"] | None = None
    """
    The log setting to use for redirecting logs for your execute command results.

    The following log settings are available.
    """
    logConfiguration: ExecuteCommandLogConfiguration | None = None
    """
    The log configuration for the results of the execute command actions.

    The logs can be sent to CloudWatch Logs or an
    Amazon S3 bucket. When ``logging=OVERRIDE`` is specified, a ``logConfiguration`` must be provided.
    """


class ManagedStorageConfiguration(Boto3Model):
    """
    The managed storage configuration for the cluster.
    """

    kmsKeyId: str | None = None
    """
    Specify a Key Management Service key ID to encrypt Amazon ECS managed storage.
    """
    fargateEphemeralStorageKmsKeyId: str | None = None
    """
    Specify the Key Management Service key ID for Fargate ephemeral storage.
    """


class ClusterConfiguration(Boto3Model):
    """
    The execute command and managed storage configuration for the cluster.
    """

    executeCommandConfiguration: ExecuteCommandConfiguration | None = None
    """
    The details of the execute command configuration.
    """
    managedStorageConfiguration: ManagedStorageConfiguration | None = None
    """
    The details of the managed storage configuration.
    """


class KeyValuePair(Boto3Model):
    """
    A key-value pair object.
    """

    name: str | None = None
    """
    The name of the key-value pair.

    For environment variables, this is the name of the environment variable.
    """
    value: str | None = None
    """
    The value of the key-value pair.

    For environment variables, this is the value of the environment variable.
    """


class ClusterSetting(Boto3Model):
    """
    The settings to use when creating a cluster. This parameter is used to turn on
    CloudWatch Container Insights with enhanced observability or CloudWatch Container
    Insights for a cluster.

    Container Insights with enhanced observability provides all the Container Insights
    metrics, plus additional task and container metrics. This version supports enhanced
    observability for Amazon ECS clusters using the Amazon EC2 and Fargate launch types.
    After you configure Container Insights with enhanced observability on Amazon ECS,
    Container Insights auto- collects detailed infrastructure telemetry from the cluster
    level down to the container level in your environment and displays these critical
    performance data in curated dashboards removing the heavy lifting in observability
    set-up.

    For more information, see
    `Monitor Amazon ECS containers using Container Insights with enhanced observability <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cloudwatch-container-insights.html>`_
    in the
    *Amazon Elastic Container Service Developer Guide*.
    """

    name: Literal["containerInsights"] | None = None
    """
    The name of the cluster setting.

    The value is ``containerInsights``.
    """
    value: str | None = None
    """
    The value to set for the cluster setting.

    The supported values are ``enhanced``, ``enabled``, and ``disabled``.
    """


class Attachment(Boto3Model):
    """
    An object representing a container instance or task attachment.
    """

    id: str | None = None
    """
    The unique identifier for the attachment.
    """
    type: str | None = None
    """
    The type of the attachment, such as ``ElasticNetworkInterface``, ``Service
    Connect``, and ``AmazonElasticBlockStorage``.
    """
    status: str | None = None
    """
    The status of the attachment.

    Valid values are ``PRECREATED``, ``CREATED``, ``ATTACHING``, ``ATTACHED``, ``DETACHING``,
    ``DETACHED``, ``DELETED``, and ``FAILED``.
    """
    details: List["KeyValuePair"] | None = None
    """
    Details of the attachment.
    """


class ClusterServiceConnectDefaults(Boto3Model):
    """
    Use this parameter to set a default Service Connect namespace. After you set a
    default Service Connect namespace, any new services with Service Connect turned on
    that are created in the cluster are added as client services in the namespace. This
    setting only applies to new services that set the ``enabled`` parameter to ``true``
    in the ``ServiceConnectConfiguration``. You can set the namespace of each service
    individually in the ``ServiceConnectConfiguration`` to override this default
    parameter.

    Tasks that run in a namespace can use short names to connect to services in the
    namespace. Tasks can connect to services across all of the clusters in the
    namespace. Tasks connect through a managed proxy container that collects logs and
    metrics for increased visibility. Only the tasks that Amazon ECS services create are
    supported with Service Connect. For more information, see
    `Service Connect <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-
    connect.html>`_ in the *Amazon Elastic Container Service Developer Guide*.
    """

    namespace: str | None = None
    """
    The namespace name or full Amazon Resource Name (ARN) of the Cloud Map namespace.

    When you create a service and don't specify a Service Connect configuration, this
    namespace is used.
    """


class Cluster(TagsDictMixin, PrimaryBoto3Model):
    """
    A regional grouping of one or more container instances where you can run task
    requests.

    Each account receives a default cluster the first time you use the Amazon ECS
    service, but you may also create other clusters. Clusters may contain more than one
    instance type simultaneously.
    """

    tag_class: ClassVar[Type] = ECSTag
    manager_class: ClassVar[Type[Boto3ModelManager]] = ClusterManager

    clusterName: str
    """
    A user-generated string that you use to identify your cluster.
    """
    Tags: List["ECSTag"] = Field(default_factory=list, alias="tags")
    """
    The metadata that you apply to the cluster to help you categorize and organize them.

    Each tag consists of a key and an optional value. You define both.
    """
    clusterArn: str = Field(default=None, frozen=True)
    """
    The Amazon Resource Name (ARN) that identifies the cluster.

    For more information about the ARN format, see `Amazon
    Resource Name (ARN) <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-account-settings.html#ecs-resource-
    ids>`_ in the *Amazon ECS Developer Guide*.
    """
    configuration: ClusterConfiguration | None = None
    """
    The execute command and managed storage configuration for the cluster.
    """
    status: str = Field(default=None, frozen=True)
    """
    The status of the cluster.

    The following are the possible states that are returned.
    """
    registeredContainerInstancesCount: int = Field(default=None, frozen=True)
    """
    The number of container instances registered into the cluster.

    This includes container instances in both ``ACTIVE`` and
    ``DRAINING`` status.
    """
    runningTasksCount: int = Field(default=None, frozen=True)
    """
    The number of tasks in the cluster that are in the ``RUNNING`` state.
    """
    pendingTasksCount: int = Field(default=None, frozen=True)
    """
    The number of tasks in the cluster that are in the ``PENDING`` state.
    """
    activeServicesCount: int = Field(default=None, frozen=True)
    """
    The number of services that are running on the cluster in an ``ACTIVE`` state.

    You can view these services with
    `ListServices <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListServices.html>`_.
    """
    statistics: List["KeyValuePair"] = Field(default_factory=list, frozen=True)
    """
    Additional information about your clusters that are separated by launch type.

    They include the following:
    """
    settings: List["ClusterSetting"] | None = None
    """
    The settings for the cluster.

    This parameter indicates whether CloudWatch Container Insights is on or off for a
    cluster.
    """
    capacityProviders: List[str] | None = None
    """
    The capacity providers associated with the cluster.
    """
    defaultCapacityProviderStrategy: List["CapacityProviderStrategyItem"] | None = (
        None
    )
    """
    The default capacity provider strategy for the cluster.

    When services or tasks are run in the cluster with no launch type or capacity
    provider strategy specified, the default capacity provider strategy is used.
    """
    attachments: List["Attachment"] = Field(default_factory=list, frozen=True)
    """
    The resources attached to a cluster.

    When using a capacity provider with a cluster, the capacity provider and associated
    resources are returned as cluster attachments.
    """
    attachmentsStatus: str = Field(default=None, frozen=True)
    """
    The status of the capacity providers associated with the cluster.

    The following are the states that are returned.
    """
    serviceConnectDefaults: ClusterServiceConnectDefaults | None = None
    """
    Use this parameter to set a default Service Connect namespace.

    After you set a default Service Connect namespace, any
    new services with Service Connect turned on that are created in the cluster are added as client services in the
    namespace. This setting only applies to new services that set the ``enabled`` parameter to ``true`` in the
    ``ServiceConnectConfiguration``. You can set the namespace of each service individually in the
    ``ServiceConnectConfiguration`` to override this default parameter.
    """

    @property
    def pk(self) -> str | None:
        """
        Return the primary key of the model.   This is the value of the
        :py:attr:`clusterArn` attribute.

        Returns:
            The primary key of the model instance.
        """
        return self.clusterArn

    @property
    def arn(self) -> str | None:
        """
        Return the ARN of the model.   This is the value of the :py:attr:`clusterArn`
        attribute.

        Returns:
            The ARN of the model instance.
        """
        return self.clusterArn

    @property
    def name(self) -> str | None:
        """
        Return the name of the model.   This is the value of the :py:attr:`clusterName`
        attribute.

        Returns:
            The name of the model instance.
        """
        return self.clusterName

    def __hash__(self) -> int:
        """
        Return the hash of the model.

        This is the value of the
        :py:attr:`clusterArn` attribute.
        """
        return hash(self.clusterArn)

    @cached_property
    def services(self) -> List["Service"] | None:
        """
        Return the ARNs of :py:class:`Service` objects that run in this cluster, if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "cluster": self.clusterArn,
                }
            )
        except AttributeError:
            return []
        return Service.objects.using(self.session).list(**pk)  # type: ignore[arg-type]

    @cached_property
    def container_instances(self) -> List["ContainerInstance"] | None:
        """
        Return the ARNs of :py:class:`ContainerInstance` objects that run in this
        cluster, if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "cluster": self.clusterArn,
                }
            )
        except AttributeError:
            return []
        return ContainerInstance.objects.using(self.session).list(**pk)  # type: ignore[arg-type]


class RepositoryCredentials(Boto3Model):
    """
    The repository credentials for private registry authentication.
    """

    credentialsParameter: str
    """
    The Amazon Resource Name (ARN) of the secret containing the private repository
    credentials.
    """


class PortMapping(Boto3Model):
    """
    Port mappings allow containers to access ports on the host container instance to
    send or receive traffic. Port mappings are specified as part of the container
    definition.

    If you use containers in a task with the ``awsvpc`` or ``host`` network mode, specify the exposed ports using
    ``containerPort``. The ``hostPort`` can be left blank or it must be the same value as the ``containerPort``.

    Most fields of this parameter (``containerPort``, ``hostPort``, ``protocol``) maps to ``PortBindings`` in the docker
    container create command and the ``--publish`` option to ``docker run``. If the network mode of a task definition is set
    to ``host``, host ports must either be undefined or match the container port in the port mapping.

    You can't expose the same container port for multiple protocols. If you attempt this, an error is returned.

    After a task reaches the ``RUNNING`` status, manual and automatic host and container port assignments are visible in the
    ``networkBindings`` section of
    `DescribeTasks <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeTasks.html>`_ API responses.
    """

    containerPort: int | None = None
    """
    The port number on the container that's bound to the user-specified or automatically
    assigned host port.
    """
    hostPort: int | None = None
    """
    The port number on the container instance to reserve for your container.
    """
    protocol: Literal["tcp", "udp"] | None = None
    """
    The protocol used for the port mapping.

    Valid values are ``tcp`` and ``udp``. The default is ``tcp``. ``protocol`` is
    immutable in a Service Connect service. Updating this field requires a service deletion and redeployment.
    """
    name: str | None = None
    """
    The name that's used for the port mapping.

    This parameter is the name that you use in the
    ``serviceConnectConfiguration`` and the ``vpcLatticeConfigurations`` of a service. The name can include up to 64
    characters. The characters can include lowercase letters, numbers, underscores (_), and hyphens (-). The name can't
    start with a hyphen.
    """
    appProtocol: Literal["http", "http2", "grpc"] | None = None
    """
    The application protocol that's used for the port mapping.

    This parameter only applies to Service Connect. We recommend that you set this
    parameter to be consistent with the protocol that your application uses. If you set
    this parameter, Amazon ECS adds protocol-specific connection handling to the Service
    Connect proxy. If you set this parameter, Amazon ECS adds protocol-specific
    telemetry in the Amazon ECS console and CloudWatch.
    """
    containerPortRange: str | None = None
    """
    The port number range on the container that's bound to the dynamically mapped host
    port range.
    """


class ContainerRestartPolicy(Boto3Model):
    """
    You can enable a restart policy for each container defined in your task definition,
    to overcome transient failures faster and maintain task availability.

    When you enable a restart policy for a container, Amazon ECS can restart the
    container if it exits, without needing to replace the task. For more information,
    see
    `Restart individual containers in Amazon ECS tasks with container restart policies <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/container-
    restart-policy.html>`_ in the *Amazon Elastic Container Service Developer Guide*.
    """

    enabled: bool
    """
    Specifies whether a restart policy is enabled for the container.
    """
    ignoredExitCodes: List[int] | None = None
    """
    A list of exit codes that Amazon ECS will ignore and not attempt a restart on.

    You can specify a maximum of 50 container exit codes. By default, Amazon ECS does
    not ignore any exit codes.
    """
    restartAttemptPeriod: int | None = None
    """
    A period of time (in seconds) that the container must run for before a restart can
    be attempted.

    A container can be
    restarted only once every ``restartAttemptPeriod`` seconds. If a container isn't able to run for this time period and
    exits early, it will not be restarted. You can set a minimum ``restartAttemptPeriod`` of 60 seconds and a maximum
    ``restartAttemptPeriod`` of 1800 seconds. By default, a container must run for 300 seconds before it can be restarted.
    """


class EnvironmentFile(Boto3Model):
    """
    A list of files containing the environment variables to pass to a container. You can
    specify up to ten environment files. The file must have a ``.env`` file extension.
    Each line in an environment file should contain an environment variable in
    ``VARIABLE=VALUE`` format. Lines beginning with ``#`` are treated as comments and
    are ignored.

    If there are environment variables specified using the ``environment`` parameter in a container definition, they take
    precedence over the variables contained within an environment file. If multiple environment files are specified that
    contain the same variable, they're processed from the top down. We recommend that you use unique variable names. For
    more information, see `Use a file to pass environment variables to a
    container <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/use-environment-file.html>`_ in the *Amazon Elastic
    Container Service Developer Guide*.

    Environment variable files are objects in Amazon S3 and all Amazon S3 security considerations apply.

    You must use the following platforms for the Fargate launch type:

    * Linux platform version ``1.4.0`` or later.
    * Windows platform version ``1.0.0`` or later.

    Consider the following when using the Fargate launch type:

    * The file is handled like a native Docker env-file.
    * There is no support for shell escape handling.
    * The container entry point interperts the ``VARIABLE`` values.
    """

    value: str
    """
    The Amazon Resource Name (ARN) of the Amazon S3 object containing the environment
    variable file.
    """
    type: Literal["s3"]
    """
    The file type to use.

    Environment files are objects in Amazon S3. The only supported value is ``s3``.
    """


class MountPoint(Boto3Model):
    """
    The details for a volume mount point that's used in a container definition.
    """

    sourceVolume: str | None = None
    """
    The name of the volume to mount.

    Must be a volume name referenced in the ``name`` parameter of task definition
    ``volume``.
    """
    containerPath: str | None = None
    """
    The path on the container to mount the host volume at.
    """
    readOnly: bool | None = None
    """
    If this value is ``true``, the container has read-only access to the volume.

    If this value is ``false``, then the
    container can write to the volume. The default value is ``false``.
    """


class VolumeFrom(Boto3Model):
    """
    Details on a data volume from another container in the same task definition.
    """

    sourceContainer: str | None = None
    """
    The name of another container within the same task definition to mount volumes from.
    """
    readOnly: bool | None = None
    """
    If this value is ``true``, the container has read-only access to the volume.

    If this value is ``false``, then the
    container can write to the volume. The default value is ``false``.
    """


class KernelCapabilities(Boto3Model):
    """The Linux capabilities to add or remove from the default Docker configuration for a container defined in the task
    definition. For more detailed information about these Linux capabilities, see the
    `capabilities(7) <http://man7.org/linux/man-pages/man7/capabilities.7.html>`_ Linux manual page.

    The following describes how Docker processes the Linux capabilities specified in the ``add`` and ``drop`` request
    parameters. For information about the latest behavior, see `Docker Compose: order of cap_drop and
    cap_add <https://forums.docker.com/t/docker-compose-order-of-cap-drop-and-cap-add/97136/1>`_ in the Docker Community
    Forum.

    * When the container is a privleged container, the container capabilities are all of the default Docker capabilities.
      The capabilities specified in the ``add`` request parameter, and the ``drop`` request parameter are ignored.
    * When the ``add`` request parameter is set to ALL, the container capabilities are all of the default Docker
      capabilities, excluding those specified in the ``drop`` request parameter.
    * When the ``drop`` request parameter is set to ALL, the container capabilities are the capabilities specified in the
      ``add`` request parameter.
    * When the ``add`` request parameter and the ``drop`` request parameter are both empty, the capabilities the container
      capabilities are all of the default Docker capabilities.
    * The default is to first drop the capabilities specified in the ``drop`` request parameter, and then add the
      capabilities specified in the ``add`` request parameter.
    """

    add: List[str] | None = None
    """
    The Linux capabilities for the container that have been added to the default
    configuration provided by Docker.

    This
    parameter maps to ``CapAdd`` in the docker container create command and the ``--cap-add`` option to docker run.
    """
    drop: List[str] | None = None
    """
    The Linux capabilities for the container that have been removed from the default
    configuration provided by Docker.

    This
    parameter maps to ``CapDrop`` in the docker container create command and the ``--cap-drop`` option to docker run.
    """


class Device(Boto3Model):
    """
    An object representing a container instance host device.
    """

    hostPath: str
    """
    The path for the device on the host container instance.
    """
    containerPath: str | None = None
    """
    The path inside the container at which to expose the host device.
    """
    permissions: List[Literal["read", "write", "mknod"]] | None = None
    """
    The explicit permissions to provide to the container for the device.

    By default, the container has permissions for
    ``read``, ``write``, and ``mknod`` for the device.
    """


class Tmpfs(Boto3Model):
    """
    The container path, mount options, and size of the tmpfs mount.
    """

    containerPath: str
    """
    The absolute file path where the tmpfs volume is to be mounted.
    """
    size: int
    """
    The maximum size (in MiB) of the tmpfs volume.
    """
    mountOptions: List[str] | None = None
    """
    The list of tmpfs volume mount options.
    """


class LinuxParameters(Boto3Model):
    """The Linux-specific options that are applied to the container, such as Linux
    `KernelCapabilities <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KernelCapabilities.html>`_.
    """

    capabilities: KernelCapabilities | None = None
    """
    The Linux capabilities for the container that are added to or dropped from the
    default configuration provided by Docker.
    """
    devices: List["Device"] | None = None
    """
    Any host devices to expose to the container.

    This parameter maps to ``Devices`` in the docker container create command
    and the ``--device`` option to docker run.
    """
    initProcessEnabled: bool | None = None
    """
    Run an ``init`` process inside the container that forwards signals and reaps
    processes.

    This parameter maps to the
    ``--init`` option to docker run. This parameter requires version 1.25 of the Docker Remote API or greater on your
    container instance. To check the Docker Remote API version on your container instance, log in to your container instance
    and run the following command: ``sudo docker version --format '{{.Server.APIVersion}}'``
    """
    sharedMemorySize: int | None = None
    """
    The value for the size (in MiB) of the ``/dev/shm`` volume.

    This parameter maps to the ``--shm-size`` option to docker
    run.
    """
    tmpfs: List["Tmpfs"] | None = None
    """
    The container path, mount options, and size (in MiB) of the tmpfs mount.

    This parameter maps to the ``--tmpfs`` option
    to docker run.
    """
    maxSwap: int | None = None
    """
    The total amount of swap memory (in MiB) a container can use.

    This parameter will be translated to the ``--memory-swap``
    option to docker run where the value would be the sum of the container memory plus the ``maxSwap`` value.
    """
    swappiness: int | None = None
    """
    This allows you to tune a container's memory swappiness behavior.

    A ``swappiness`` value of ``0`` will cause swapping to
    not happen unless absolutely necessary. A ``swappiness`` value of ``100`` will cause pages to be swapped very
    aggressively. Accepted values are whole numbers between ``0`` and ``100``. If the ``swappiness`` parameter is not
    specified, a default value of ``60`` is used. If a value is not specified for ``maxSwap`` then this parameter is
    ignored. This parameter maps to the ``--memory-swappiness`` option to docker run.
    """


class ContainerDependency(Boto3Model):
    """
    The dependencies defined for container startup and shutdown. A container can contain
    multiple dependencies. When a dependency is defined for container startup, for
    container shutdown it is reversed.

    Your Amazon ECS container instances require at least version 1.26.0 of the container agent to use container
    dependencies. However, we recommend using the latest container agent version. For information about checking your agent
    version and updating to the latest version, see `Updating the Amazon ECS Container
    Agent <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-agent-update.html>`_ in the *Amazon Elastic
    Container Service Developer Guide*. If you're using an Amazon ECS-optimized Linux AMI, your instance needs at least
    version 1.26.0-1 of the ``ecs-init`` package. If your container instances are launched from version ``20190301`` or
    later, then they contain the required versions of the container agent and ``ecs-init``. For more information, see
    `Amazon ECS-optimized Linux AMI <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-optimized_AMI.html>`_ in
    the *Amazon Elastic Container Service Developer Guide*.

    For tasks that use the Fargate launch type, the task or service requires the following platforms:

    * Linux platform version ``1.3.0`` or later.
    * Windows platform version ``1.0.0`` or later.

    For more information about how to create a container dependency, see `Container dependency <https://docs.aws.amazon.com/
    AmazonECS/latest/developerguide/example_task_definitions.html#example_task_definition-containerdependency>`_ in the
    *Amazon Elastic Container Service Developer Guide*.
    """

    containerName: str
    """
    The name of a container.
    """
    condition: Literal["START", "COMPLETE", "SUCCESS", "HEALTHY"]
    """
    The dependency condition of the container.

    The following are the available conditions and their behavior:
    """


class HostEntry(Boto3Model):
    """Hostnames and IP address entries that are added to the ``/etc/hosts`` file of a container via the ``extraHosts``
    parameter of its
    `ContainerDefinition <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ContainerDefinition.html>`_.
    """

    hostname: str
    """
    The hostname to use in the ``/etc/hosts`` entry.
    """
    ipAddress: str
    """
    The IP address to use in the ``/etc/hosts`` entry.
    """


class Ulimit(Boto3Model):
    """
    The ``ulimit`` settings to pass to the container.

    Amazon ECS tasks hosted on Fargate use the default resource limit values set by the operating system with the exception
    of the ``nofile`` resource limit parameter which Fargate overrides. The ``nofile`` resource limit sets a restriction on
    the number of open files that a container can use. The default ``nofile`` soft limit is  ``65535`` and the default hard
    limit is ``65535``.

    You can specify the ``ulimit`` settings for a container in a task definition.
    """

    name: Literal[
        "core",
        "cpu",
        "data",
        "fsize",
        "locks",
        "memlock",
        "msgqueue",
        "nice",
        "nofile",
        "nproc",
        "rss",
        "rtprio",
        "rttime",
        "sigpending",
        "stack",
    ]
    """
    The ``type`` of the ``ulimit``.
    """
    softLimit: int
    """
    The soft limit for the ``ulimit`` type.

    The value can be specified in bytes, seconds, or as a count, depending on the
    ``type`` of the ``ulimit``.
    """
    hardLimit: int
    """
    The hard limit for the ``ulimit`` type.

    The value can be specified in bytes, seconds, or as a count, depending on the
    ``type`` of the ``ulimit``.
    """


class HealthCheck(Boto3Model):
    """
    An object representing a container health check. Health check parameters that are
    specified in a container definition override any Docker health checks that exist in
    the container image (such as those specified in a parent image or from the image's
    Dockerfile). This configuration maps to the ``HEALTHCHECK`` parameter of docker run.

    The Amazon ECS container agent only monitors and reports on the health checks specified in the task definition. Amazon
    ECS does not monitor Docker health checks that are embedded in a container image and not specified in the container
    definition. Health check parameters that are specified in a container definition override any Docker health checks that
    exist in the container image.

    You can view the health status of both individual containers and a task with the DescribeTasks API operation or when
    viewing the task details in the console.

    The health check is designed to make sure that your containers survive agent restarts, upgrades, or temporary
    unavailability.

    Amazon ECS performs health checks on containers with the default that launched the container instance or the task.

    The following describes the possible ``healthStatus`` values for a container:

    * ``HEALTHY``-The container health check has passed successfully.
    * ``UNHEALTHY``-The container health check has failed.
    * ``UNKNOWN``-The container health check is being evaluated, there's no container health check defined, or Amazon ECS
      doesn't have the health status of the container.

    The following describes the possible ``healthStatus`` values based on the container health checker status of essential
    containers in the task with the following priority order (high to low):

    * ``UNHEALTHY``-One or more essential containers have failed their health check.
    * ``UNKNOWN``-Any essential container running within the task is in an ``UNKNOWN`` state and no other essential
      containers have an ``UNHEALTHY`` state.
    * ``HEALTHY``-All essential containers within the task have passed their health checks.

    Consider the following task health example with 2 containers.

    * If Container1 is ``UNHEALTHY`` and Container2 is ``UNKNOWN``, the task health is ``UNHEALTHY``.
    * If Container1 is ``UNHEALTHY`` and Container2 is ``HEALTHY``, the task health is ``UNHEALTHY``.
    * If Container1 is ``HEALTHY`` and Container2 is ``UNKNOWN``, the task health is ``UNKNOWN``.
    * If Container1 is ``HEALTHY`` and Container2 is ``HEALTHY``, the task health is ``HEALTHY``.

    Consider the following task health example with 3 containers.

    * If Container1 is ``UNHEALTHY`` and Container2 is ``UNKNOWN``, and Container3 is ``UNKNOWN``, the task health is
      ``UNHEALTHY``.
    * If Container1 is ``UNHEALTHY`` and Container2 is ``UNKNOWN``, and Container3 is ``HEALTHY``, the task health is
      ``UNHEALTHY``.
    * If Container1 is ``UNHEALTHY`` and Container2 is ``HEALTHY``, and Container3 is ``HEALTHY``, the task health is
      ``UNHEALTHY``.
    * If Container1 is ``HEALTHY`` and Container2 is ``UNKNOWN``, and Container3 is ``HEALTHY``, the task health is
      ``UNKNOWN``.
    * If Container1 is ``HEALTHY`` and Container2 is ``UNKNOWN``, and Container3 is ``UNKNOWN``, the task health is
      ``UNKNOWN``.
    * If Container1 is ``HEALTHY`` and Container2 is ``HEALTHY``, and Container3 is ``HEALTHY``, the task health is
      ``HEALTHY``.

    If a task is run manually, and not as part of a service, the task will continue its lifecycle regardless of its health
    status. For tasks that are part of a service, if the task reports as unhealthy then the task will be stopped and the
    service scheduler will replace it.

    When a container health check fails for a task that is part of a service, the following process occurs:

    1. The task is marked as ``UNHEALTHY``.
    2. The unhealthy task will be stopped, and during the stopping process, it will go through the following states:

    * ``DEACTIVATING`` - In this state, Amazon ECS performs additional steps before stopping the task. For example, for
      tasks that are part of services configured to use Elastic Load Balancing target groups, target groups will be
      deregistered in this state.
    * ``STOPPING`` - The task is in the process of being stopped.
    * ``DEPROVISIONING`` - Resources associated with the task are being cleaned up.
    * ``STOPPED`` - The task has been completely stopped.
    3. After the old task stops, a new task will be launched to ensure service operation, and the new task will go through
    the following lifecycle:

    * ``PROVISIONING`` - Resources required for the task are being provisioned.
    * ``PENDING`` - The task is waiting to be placed on a container instance.
    * ``ACTIVATING`` - In this state, Amazon ECS pulls container images, creates containers, configures task networking,
      registers load balancer target groups, and configures service discovery status.
    * ``RUNNING`` - The task is running and performing its work.

    For more detailed information about task lifecycle states, see `Task
    lifecycle <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-lifecycle-explanation.html>`_ in the *Amazon
    Elastic Container Service Developer Guide*.

    The following are notes about container health check support:

    * If the Amazon ECS container agent becomes disconnected from the Amazon ECS service, this won't cause a container to
      transition to an ``UNHEALTHY`` status. This is by design, to ensure that containers remain running during agent restarts
      or temporary unavailability. The health check status is the "last heard from" response from the Amazon ECS agent, so if
      the container was considered ``HEALTHY`` prior to the disconnect, that status will remain until the agent reconnects and
      another health check occurs. There are no assumptions made about the status of the container health checks.
    * Container health checks require version ``1.17.0`` or greater of the Amazon ECS container agent. For more information,
      see `Updating the Amazon ECS container agent <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-agent-
    update.html>`_.
    * Container health checks are supported for Fargate tasks if you're using platform version ``1.1.0`` or greater. For
      more information, see `Fargate platform
      versions <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html>`_.
    * Container health checks aren't supported for tasks that are part of a service that's configured to use a Classic Load
      Balancer.

    For an example of how to specify a task definition with multiple containers where container dependency is specified, see
    `Container dependency <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/example_task_definitions.html#example
    _task_definition-containerdependency>`_ in the *Amazon Elastic Container Service Developer Guide*.
    """

    command: List[str]
    """
    A string array representing the command that the container runs to determine if it
    is healthy.

    The string array must
    start with ``CMD`` to run the command arguments directly, or ``CMD-SHELL`` to run the command with the container's
    default shell.
    """
    interval: int | None = None
    """
    The time period in seconds between each health check execution.

    You may specify between 5 and 300 seconds. The default
    value is 30 seconds. This value applies only when you specify a ``command``.
    """
    timeout: int | None = None
    """
    The time period in seconds to wait for a health check to succeed before it is
    considered a failure.

    You may specify
    between 2 and 60 seconds. The default value is 5. This value applies only when you specify a ``command``.
    """
    retries: int | None = None
    """
    The number of times to retry a failed health check before the container is
    considered unhealthy.

    You may specify between
    1 and 10 retries. The default value is 3. This value applies only when you specify a ``command``.
    """
    startPeriod: int | None = None
    """
    The optional grace period to provide containers time to bootstrap before failed
    health checks count towards the maximum number of retries.

    You can specify between 0 and 300 seconds. By default, the ``startPeriod`` is off. This value applies
    only when you specify a ``command``.
    """


class SystemControl(Boto3Model):
    """
    A list of namespaced kernel parameters to set in the container. This parameter maps
    to ``Sysctls`` in the docker container create command and the ``--sysctl`` option to
    docker run. For example, you can configure ``net.ipv4.tcp_keepalive_time`` setting
    to maintain longer lived connections.

    We don't recommend that you specify network-related ``systemControls`` parameters for multiple containers in a single
    task that also uses either the ``awsvpc`` or ``host`` network mode. Doing this has the following disadvantages:

    * For tasks that use the ``awsvpc`` network mode including Fargate, if you set ``systemControls`` for any container, it
      applies to all containers in the task. If you set different ``systemControls`` for multiple containers in a single task,
      the container that's started last determines which ``systemControls`` take effect.
    * For tasks that use the ``host`` network mode, the network namespace ``systemControls`` aren't supported.

    If you're setting an IPC resource namespace to use for the containers in the task, the following conditions apply to
    your system controls. For more information, see `IPC mode <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/t
    ask_definition_parameters.html#task_definition_ipcmode>`_.

    * For tasks that use the ``host`` IPC mode, IPC namespace ``systemControls`` aren't supported.
    * For tasks that use the ``task`` IPC mode, IPC namespace ``systemControls`` values apply to all containers within a
      task.

    This parameter is not supported for Windows containers.



    This parameter is only supported for tasks that are hosted on Fargate if the tasks are using platform version ``1.4.0``
    or later (Linux). This isn't supported for Windows containers on Fargate.
    """

    namespace: str | None = None
    """
    The namespaced kernel parameter to set a ``value`` for.
    """
    value: str | None = None
    """
    The namespaced kernel parameter to set a ``value`` for.
    """


class ResourceRequirement(Boto3Model):
    """
    The type and amount of a resource to assign to a container.

    The supported resource types are GPUs and Elastic Inference accelerators. For more
    information, see
    `Working with GPUs on Amazon ECS <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-gpu.html>`_
    or
    `Working with Amazon Elastic Inference on Amazon ECS <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-inference.html>`_
    in the *Amazon Elastic
    Container Service Developer Guide*
    """

    value: str
    """
    The value for the specified resource type.
    """
    type: Literal["GPU", "InferenceAccelerator"]
    """
    The type of resource to assign to a container.
    """


class FirelensConfiguration(Boto3Model):
    """
    The FireLens configuration for the container.

    This is used to specify and configure a log router for container logs. For more
    information, see
    `Custom log routing <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html>`_
    in the *Amazon Elastic
    Container Service Developer Guide*.
    """

    type: Literal["fluentd", "fluentbit"]
    """
    The log router to use.

    The valid values are ``fluentd`` or ``fluentbit``.
    """
    options: Dict[str, str] | None = None
    """
    The options to use when configuring the log router.

    This field is optional and can be used to specify a custom
    configuration file or to add additional metadata, such as the task, task definition, cluster, and container instance
    details to the log event. If specified, the syntax to use is ``"options":{"enable-ecs-log-
    metadata":"true|false","config-file-type:"s3|file","config-file-value":"arn:aws:s3:::mybucket/fluent.conf|filepath"}``.
    For more information, see `Creating a task definition that uses a FireLens
    configuration <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef>`_ in the
    *Amazon Elastic Container Service Developer Guide*.
    """


class ContainerDefinition(Boto3Model):
    """
    Container definitions are used in task definitions to describe the different
    containers that are launched as part of a task.
    """

    name: str
    """
    The name of a container.

    If you're linking multiple containers together in a task definition, the ``name`` of one
    container can be entered in the ``links`` of another container to connect the containers. Up to 255 letters (uppercase
    and lowercase), numbers, underscores, and hyphens are allowed. This parameter maps to ``name`` in the docker container
    create command and the ``--name`` option to docker run.
    """
    image: str
    """
    The image used to start a container. This string is passed directly to the Docker
    daemon. By default, images in the Docker Hub registry are available. Other
    repositories are specified with either  ``repository-url/image:tag``  or
    ``repository-url/image@digest`` . For images using tags (repository-url/image:tag),
    up to 255 characters total are allowed, including letters (uppercase and lowercase),
    numbers, hyphens, underscores, colons, periods, forward slashes,

    and number signs (#). For images using digests (repository-url/image@digest), the 255 character limit applies only to
    the repository URL and image name (everything before the @ sign). The only supported hash function is sha256, and the
    hash value after sha256: must be exactly 64 characters (only letters A-F, a-f, and numbers 0-9 are allowed). This
    parameter maps to ``Image`` in the docker container create command and the ``IMAGE`` parameter of docker run.
    """
    essential: bool
    """
    If the ``essential`` parameter of a container is marked as ``true``, and that
    container fails or stops for any reason, all other containers that are part of the
    task are stopped.

    If the ``essential`` parameter of a container is marked as
    ``false``, its failure doesn't affect the rest of the containers in a task. If this parameter is omitted, a container is
    assumed to be essential.
    """
    repositoryCredentials: RepositoryCredentials | None = None
    """
    The private repository authentication credentials to use.
    """
    cpu: int | None = None
    """
    The number of ``cpu`` units reserved for the container.

    This parameter maps to ``CpuShares`` in the docker container
    create commandand the ``--cpu-shares`` option to docker run.
    """
    memory: int | None = None
    """
    The amount (in MiB) of memory to present to the container.

    If your container attempts to exceed the memory specified
    here, the container is killed. The total amount of memory reserved for all containers within a task must be lower than
    the task ``memory`` value, if one is specified. This parameter maps to ``Memory`` in the docker container create command
    and the ``--memory`` option to docker run.
    """
    memoryReservation: int | None = None
    """
    The soft limit (in MiB) of memory to reserve for the container.

    When system memory is under heavy contention, Docker
    attempts to keep the container memory to this soft limit. However, your container can consume more memory when it needs
    to, up to either the hard limit specified with the ``memory`` parameter (if applicable), or all of the available memory
    on the container instance, whichever comes first. This parameter maps to ``MemoryReservation`` in the docker container
    create command and the ``--memory-reservation`` option to docker run.
    """
    links: List[str] | None = None
    """
    The ``links`` parameter allows containers to communicate with each other without the
    need for port mappings.

    This
    parameter is only supported if the network mode of a task definition is ``bridge``. The ``name:internalName`` construct
    is analogous to ``name:alias`` in Docker links. Up to 255 letters (uppercase and lowercase), numbers, underscores, and
    hyphens are allowed.. This parameter maps to ``Links`` in the docker container create command and the ``--link`` option
    to docker run.
    """
    portMappings: List["PortMapping"] | None = None
    """
    The list of port mappings for the container.

    Port mappings allow containers to access ports on the host container instance to
    send or receive traffic.
    """
    restartPolicy: ContainerRestartPolicy | None = None
    """
    The restart policy for a container.

    When you set up a restart policy, Amazon ECS can restart the container without
    needing to replace the task. For more information, see
    `Restart individual containers in Amazon ECS tasks with container restart policies <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/container-restart-policy.html>`_
    in the
    *Amazon Elastic Container Service Developer Guide*.
    """
    entryPoint: List[str] | None = None
    """
    Early versions of the Amazon ECS container agent don't properly handle
    ``entryPoint`` parameters.

    If you have problems
    using ``entryPoint``, update your container agent or enter your commands and arguments as ``command`` array items
    instead.
    """
    command: List[str] | None = None
    """
    The command that's passed to the container.

    This parameter maps to ``Cmd`` in the docker container create command and
    the ``COMMAND`` parameter to docker run. If there are multiple arguments, each argument is a separated string in the
    array.
    """
    environment: List["KeyValuePair"] | None = None
    """
    The environment variables to pass to a container.

    This parameter maps to ``Env`` in the docker container create command
    and the ``--env`` option to docker run.
    """
    environmentFiles: List["EnvironmentFile"] | None = None
    """
    A list of files containing the environment variables to pass to a container.

    This parameter maps to the ``--env-file``
    option to docker run.
    """
    mountPoints: List["MountPoint"] | None = None
    """
    The mount points for data volumes in your container.
    """
    volumesFrom: List["VolumeFrom"] | None = None
    """
    Data volumes to mount from another container.

    This parameter maps to ``VolumesFrom`` in the docker container create
    command and the ``--volumes-from`` option to docker run.
    """
    linuxParameters: LinuxParameters | None = None
    """
    Linux-specific modifications that are applied to the default Docker container
    configuration, such as Linux kernel capabilities.

    For more information see
    `KernelCapabilities <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KernelCapabilities.html>`_.
    """
    secrets: List["Secret"] | None = None
    """
    The secrets to pass to the container.

    For more information, see
    `Specifying Sensitive Data <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/specifying-sensitive-data.html>`_
    in the *Amazon Elastic
    Container Service Developer Guide*.
    """
    dependsOn: List["ContainerDependency"] | None = None
    """
    The dependencies defined for container startup and shutdown.

    A container can contain multiple dependencies on other containers in a task
    definition. When a dependency is defined for container startup, for container
    shutdown it is reversed.
    """
    startTimeout: int | None = None
    """
    Time duration (in seconds) to wait before giving up on resolving dependencies for a
    container.

    For example, you specify
    two containers in a task definition with containerA having a dependency on containerB reaching a ``COMPLETE``,
    ``SUCCESS``, or ``HEALTHY`` status. If a ``startTimeout`` value is specified for containerB and it doesn't reach the
    desired status within that time then containerA gives up and not start. This results in the task transitioning to a
    ``STOPPED`` state.
    """
    stopTimeout: int | None = None
    """
    Time duration (in seconds) to wait before the container is forcefully killed if it
    doesn't exit normally on its own.
    """
    versionConsistency: Literal["enabled", "disabled"] | None = None
    """
    Specifies whether Amazon ECS will resolve the container image tag provided in the
    container definition to an image digest.

    By default, the value is ``enabled``. If you set the value for a container as ``disabled``, Amazon ECS will not
    resolve the provided container image tag to a digest and will use the original image URI specified in the container
    definition for deployment. For more information about container image resolution, see `Container image
    resolution <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-type-ecs.html#deployment-container-
    image-stability>`_ in the *Amazon ECS Developer Guide*.
    """
    hostname: str | None = None
    """
    The hostname to use for your container.

    This parameter maps to ``Hostname`` in the docker container create command and
    the ``--hostname`` option to docker run.
    """
    user: str | None = None
    """
    The user to use inside the container.

    This parameter maps to ``User`` in the docker container create command and the
    ``--user`` option to docker run.
    """
    workingDirectory: str | None = None
    """
    The working directory to run commands inside the container in.

    This parameter maps to ``WorkingDir`` in the docker
    container create command and the ``--workdir`` option to docker run.
    """
    disableNetworking: bool | None = None
    """
    When this parameter is true, networking is off within the container.

    This parameter maps to ``NetworkDisabled`` in the
    docker container create command.
    """
    privileged: bool | None = None
    """
    When this parameter is true, the container is given elevated privileges on the host
    container instance (similar to the ``root`` user).

    This parameter maps to ``Privileged`` in the docker container create command and the ``--privileged``
    option to docker run
    """
    readonlyRootFilesystem: bool | None = None
    """
    When this parameter is true, the container is given read-only access to its root
    file system.

    This parameter maps to
    ``ReadonlyRootfs`` in the docker container create command and the ``--read-only`` option to docker run.
    """
    dnsServers: List[str] | None = None
    """
    A list of DNS servers that are presented to the container.

    This parameter maps to ``Dns`` in the docker container create
    command and the ``--dns`` option to docker run.
    """
    dnsSearchDomains: List[str] | None = None
    """
    A list of DNS search domains that are presented to the container.

    This parameter maps to ``DnsSearch`` in the docker
    container create command and the ``--dns-search`` option to docker run.
    """
    extraHosts: List["HostEntry"] | None = None
    """
    A list of hostnames and IP address mappings to append to the ``/etc/hosts`` file on
    the container.

    This parameter maps
    to ``ExtraHosts`` in the docker container create command and the ``--add-host`` option to docker run.
    """
    dockerSecurityOptions: List[str] | None = None
    """
    A list of strings to provide custom configuration for multiple security systems.

    This field isn't valid for containers in tasks using the Fargate launch type.
    """
    interactive: bool | None = None
    """
    When this parameter is ``true``, you can deploy containerized applications that
    require ``stdin`` or a ``tty`` to be allocated.

    This parameter maps to ``OpenStdin`` in the docker container create command and the ``--interactive`` option
    to docker run.
    """
    pseudoTerminal: bool | None = None
    """
    When this parameter is ``true``, a TTY is allocated.

    This parameter maps to ``Tty`` in the docker container create
    command and the ``--tty`` option to docker run.
    """
    dockerLabels: Dict[str, str] | None = None
    """
    A key/value map of labels to add to the container.

    This parameter maps to ``Labels`` in the docker container create
    command and the ``--label`` option to docker run. This parameter requires version 1.18 of the Docker Remote API or
    greater on your container instance. To check the Docker Remote API version on your container instance, log in to your
    container instance and run the following command: ``sudo docker version --format '{{.Server.APIVersion}}'``
    """
    ulimits: List["Ulimit"] | None = None
    """
    A list of ``ulimits`` to set in the container.

    If a ``ulimit`` value is specified in a task definition, it overrides the
    default values set by Docker. This parameter maps to ``Ulimits`` in the docker container create command and the
    ``--ulimit`` option to docker run. Valid naming values are displayed in the
    `Ulimit <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_Ulimit.html>`_ data type.
    """
    logConfiguration: LogConfiguration | None = None
    """
    The log configuration specification for the container.
    """
    healthCheck: HealthCheck | None = None
    """
    The container health check command and associated configuration parameters for the
    container.

    This parameter maps to
    ``HealthCheck`` in the docker container create command and the ``HEALTHCHECK`` parameter of docker run.
    """
    systemControls: List["SystemControl"] | None = None
    """
    A list of namespaced kernel parameters to set in the container.

    This parameter maps to ``Sysctls`` in the docker
    container create command and the ``--sysctl`` option to docker run. For example, you can configure
    ``net.ipv4.tcp_keepalive_time`` setting to maintain longer lived connections.
    """
    resourceRequirements: List["ResourceRequirement"] | None = None
    """
    The type and amount of a resource to assign to a container.

    The only supported resource is a GPU.
    """
    firelensConfiguration: FirelensConfiguration | None = None
    """
    The FireLens configuration for the container.

    This is used to specify and configure a log router for container logs. For more
    information, see
    `Custom Log Routing <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html>`_
    in the *Amazon Elastic
    Container Service Developer Guide*.
    """
    credentialSpecs: List[str] | None = None
    """
    A list of ARNs in SSM or Amazon S3 to a credential spec (``CredSpec``) file that
    configures the container for Active Directory authentication.

    We recommend that you use this parameter instead of the ``dockerSecurityOptions``. The maximum
    number of ARNs is 1.
    """

    @property
    def repository_name(self) -> str | None:
        """
        The name of the repository that houses the image that this container definition
        uses.
        """

        return self.transform("image", r"^(.+):.+$")


class HostVolumeProperties(Boto3Model):
    """
    Details on a container instance bind mount host volume.
    """

    sourcePath: str | None = None
    """
    When the ``host`` parameter is used, specify a ``sourcePath`` to declare the path on
    the host container instance that's presented to the container.

    If this parameter is empty, then the Docker daemon has assigned a host path for you. If the
    ``host`` parameter contains a ``sourcePath`` file location, then the data volume persists at the specified location on
    the host container instance until you delete it manually. If the ``sourcePath`` value doesn't exist on the host
    container instance, the Docker daemon creates it. If the location does exist, the contents of the source path folder are
    exported.
    """


class DockerVolumeConfiguration(Boto3Model):
    """
    This parameter is specified when you're using Docker volumes.

    Docker volumes are only supported when you're using the
    EC2 launch type. Windows containers only support the use of the ``local`` driver. To use bind mounts, specify a ``host``
    instead.
    """

    scope: Literal["task", "shared"] | None = None
    """
    The scope for the Docker volume that determines its lifecycle.

    Docker volumes that are scoped to a ``task`` are
    automatically provisioned when the task starts and destroyed when the task stops. Docker volumes that are scoped as
    ``shared`` persist after the task stops.
    """
    autoprovision: bool | None = None
    """
    If this value is ``true``, the Docker volume is created if it doesn't already exist.
    """
    driver: str | None = None
    """
    The Docker volume driver to use.

    The driver value must match the driver name provided by Docker because it is used for
    task placement. If the driver was installed using the Docker plugin CLI, use ``docker plugin ls`` to retrieve the driver
    name from your container instance. If the driver was installed using another method, use Docker plugin discovery to
    retrieve the driver name. This parameter maps to ``Driver`` in the docker container create command and the ``xxdriver``
    option to docker volume create.
    """
    driverOpts: Dict[str, str] | None = None
    """
    A map of Docker driver-specific options passed through.

    This parameter maps to ``DriverOpts`` in the docker create-
    volume command and the ``xxopt`` option to docker volume create.
    """
    labels: Dict[str, str] | None = None
    """
    Custom metadata to add to your Docker volume.

    This parameter maps to ``Labels`` in the docker container create command
    and the ``xxlabel`` option to docker volume create.
    """


class EFSAuthorizationConfig(Boto3Model):
    """
    The authorization configuration details for the Amazon EFS file system.
    """

    accessPointId: str | None = None
    """
    The Amazon EFS access point ID to use.

    If an access point is specified, the root directory value specified in the
    ``EFSVolumeConfiguration`` must either be omitted or set to ``/`` which will enforce the path set on the EFS access
    point. If an access point is used, transit encryption must be on in the ``EFSVolumeConfiguration``. For more
    information, see `Working with Amazon EFS access points <https://docs.aws.amazon.com/efs/latest/ug/efs-access-
    points.html>`_ in the *Amazon Elastic File System User Guide*.
    """
    iam: Literal["ENABLED", "DISABLED"] | None = None
    """
    Determines whether to use the Amazon ECS task role defined in a task definition when
    mounting the Amazon EFS file system.

    If it is turned on, transit encryption must be turned on in the ``EFSVolumeConfiguration``. If this parameter is
    omitted, the default value of ``DISABLED`` is used. For more information, see `Using Amazon EFS access
    points <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/efs-volumes.html#efs-volume-accesspoints>`_ in the
    *Amazon Elastic Container Service Developer Guide*.
    """


class EFSVolumeConfiguration(Boto3Model):
    """
    This parameter is specified when you're using an Amazon Elastic File System file
    system for task storage.

    For more information, see
    `Amazon EFS volumes <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/efs-volumes.html>`_
    in
    the *Amazon Elastic Container Service Developer Guide*.
    """

    fileSystemId: str
    """
    The Amazon EFS file system ID to use.
    """
    rootDirectory: str | None = None
    """
    The directory within the Amazon EFS file system to mount as the root directory
    inside the host.

    If this parameter is
    omitted, the root of the Amazon EFS volume will be used. Specifying ``/`` will have the same effect as omitting this
    parameter.
    """
    transitEncryption: Literal["ENABLED", "DISABLED"] | None = None
    """
    Determines whether to use encryption for Amazon EFS data in transit between the
    Amazon ECS host and the Amazon EFS server.

    Transit encryption must be turned on if Amazon EFS IAM authorization is used. If this parameter is omitted, the
    default value of ``DISABLED`` is used. For more information, see `Encrypting data in
    transit <https://docs.aws.amazon.com/efs/latest/ug/encryption-in-transit.html>`_ in the *Amazon Elastic File System User
    Guide*.
    """
    transitEncryptionPort: int | None = None
    """
    The port to use when sending encrypted data between the Amazon ECS host and the
    Amazon EFS server.

    If you do not specify a transit encryption port, it will use the port selection
    strategy that the Amazon EFS mount helper uses. For more information, see
    `EFS mount helper <https://docs.aws.amazon.com/efs/latest/ug/efs-mount-helper.html>`_
    in the *Amazon
    Elastic File System User Guide*.
    """
    authorizationConfig: EFSAuthorizationConfig | None = None
    """
    The authorization configuration details for the Amazon EFS file system.
    """


class FSxWindowsFileServerAuthorizationConfig(Boto3Model):
    """The authorization configuration details for Amazon FSx for Windows File Server file system. See `FSxWindowsFileServerVol
    umeConfiguration <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_FSxWindowsFileServerVolumeConfiguration.
    html>`_ in the *Amazon ECS API Reference*.

    For more information and the input format, see `Amazon FSx for Windows File Server
    Volumes <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/wfsx-volumes.html>`_ in the *Amazon Elastic Container
    Service Developer Guide*.
    """

    credentialsParameter: str
    """
    The authorization credential option to use.

    The authorization credential options can be provided using either the Amazon
    Resource Name (ARN) of an Secrets Manager secret or SSM Parameter Store parameter.
    The ARN refers to the stored credentials.
    """
    domain: str
    """
A fully qualified domain name hosted by an `Directory
Service <https://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_microsoft_ad.html>`_ Managed Microsoft
AD (Active Directory) or self-hosted AD on Amazon EC2.
    """


class FSxWindowsFileServerVolumeConfiguration(Boto3Model):
    """This parameter is specified when you're using `Amazon FSx for Windows File
    Server <https://docs.aws.amazon.com/fsx/latest/WindowsGuide/what-is.html>`_ file system for task storage.

    For more information and the input format, see `Amazon FSx for Windows File Server
    volumes <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/wfsx-volumes.html>`_ in the *Amazon Elastic Container
    Service Developer Guide*.
    """

    fileSystemId: str
    """
    The Amazon FSx for Windows File Server file system ID to use.
    """
    rootDirectory: str
    """
    The directory within the Amazon FSx for Windows File Server file system to mount as
    the root directory inside the host.
    """
    authorizationConfig: FSxWindowsFileServerAuthorizationConfig
    """
    The authorization configuration details for the Amazon FSx for Windows File Server
    file system.
    """


class Volume(Boto3Model):
    """
    The data volume configuration for tasks launched using this task definition.

    Specifying a volume configuration in a task
    definition is optional. The volume configuration may contain multiple volumes but only one volume configured at launch
    is supported. Each volume defined in the volume configuration may only specify a ``name`` and one of either
    ``configuredAtLaunch``, ``dockerVolumeConfiguration``, ``efsVolumeConfiguration``,
    ``fsxWindowsFileServerVolumeConfiguration``, or ``host``. If an empty volume configuration is specified, by default
    Amazon ECS uses a host volume. For more information, see `Using data volumes in
    tasks <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_data_volumes.html>`_.
    """

    name: str | None = None
    """
    The name of the volume.

    Up to 255 letters (uppercase and lowercase), numbers, underscores, and hyphens are
    allowed.
    """
    host: HostVolumeProperties | None = None
    """
    This parameter is specified when you use bind mount host volumes.

    The contents of the ``host`` parameter determine
    whether your bind mount host volume persists on the host container instance and where it's stored. If the ``host``
    parameter is empty, then the Docker daemon assigns a host path for your data volume. However, the data isn't guaranteed
    to persist after the containers that are associated with it stop running.
    """
    dockerVolumeConfiguration: DockerVolumeConfiguration | None = None
    """
    This parameter is specified when you use Docker volumes.
    """
    efsVolumeConfiguration: EFSVolumeConfiguration | None = None
    """
    This parameter is specified when you use an Amazon Elastic File System file system
    for task storage.
    """
    fsxWindowsFileServerVolumeConfiguration: FSxWindowsFileServerVolumeConfiguration | None = None
    """
    This parameter is specified when you use Amazon FSx for Windows File Server file
    system for task storage.
    """
    configuredAtLaunch: bool | None = None
    """
    Indicates whether the volume should be configured at launch time.

    This is used to create Amazon EBS volumes for standalone tasks or tasks created as
    part of a service. Each task definition revision may only have one volume configured
    at launch in the volume configuration.
    """


class Attribute(Boto3Model):
    """
    An attribute is a name-value pair that's associated with an Amazon ECS object.

    Use attributes to extend the Amazon ECS data model by adding custom metadata to your
    resources. For more information, see
    `Attributes <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-constraints.html#attributes>`_
    in
    the *Amazon Elastic Container Service Developer Guide*.
    """

    name: str
    """
    The name of the attribute.

    The ``name`` must contain between 1 and 128 characters. The name may contain letters
    (uppercase and lowercase), numbers, hyphens (-), underscores (_), forward slashes (/), back slashes (), or periods
    (.).
    """
    value: str | None = None
    """
    The value of the attribute.

    The ``value`` must contain between 1 and 128 characters. It can contain letters (uppercase
    and lowercase), numbers, hyphens (-), underscores (_), periods (.), at signs (@), forward slashes (/), back slashes
    (), colons (:), or spaces. The value can't start or end with a space.
    """
    targetType: Literal["container-instance"] | None = None
    """
    The type of the target to attach the attribute with.

    This parameter is required if you use the short form ID for a resource instead of
    the full ARN.
    """
    targetId: str | None = None
    """
    The ID of the target.

    You can specify the short form ID for a resource or the full Amazon Resource Name
    (ARN).
    """


class TaskDefinitionPlacementConstraint(Boto3Model):
    """The constraint on task placement in the task definition. For more information, see `Task placement
    constraints <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-constraints.html>`_ in the *Amazon
    Elastic Container Service Developer Guide*.

    Task placement constraints aren't supported for tasks run on Fargate.
    """

    type: Literal["memberOf"] | None = None
    """
    The type of constraint.

    The ``MemberOf`` constraint restricts selection to be from a group of valid candidates.
    """
    expression: str | None = None
    """
    A cluster query language expression to apply to the constraint.

    For more information, see
    `Cluster query language <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-query-language.html>`_
    in the *Amazon
    Elastic Container Service Developer Guide*.
    """


class RuntimePlatform(Boto3Model):
    """
    Information about the platform for the Amazon ECS service or task.

    For more information about ``RuntimePlatform``, see
    `RuntimePlatform <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#runtime-
    platform>`_ in the *Amazon Elastic Container Service Developer Guide*.
    """

    cpuArchitecture: Literal["X86_64", "ARM64"] | None = None
    """
    The CPU architecture.
    """
    operatingSystemFamily: Literal["WINDOWS_SERVER_2019_FULL", "WINDOWS_SERVER_2019_CORE", "WINDOWS_SERVER_2016_FULL", "WINDOWS_SERVER_2004_CORE", "WINDOWS_SERVER_2022_CORE", "WINDOWS_SERVER_2022_FULL", "WINDOWS_SERVER_2025_CORE", "WINDOWS_SERVER_2025_FULL", "WINDOWS_SERVER_20H2_CORE", "LINUX"] | None = None
    """
    The operating system.
    """


class InferenceAccelerator(Boto3Model):
    """
    Details on an Elastic Inference accelerator.

    For more information, see
    `Working with Amazon Elastic Inference on Amazon ECS <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-inference.html>`_
    in the *Amazon Elastic Container
    Service Developer Guide*.
    """

    deviceName: str
    """
    The Elastic Inference accelerator device name.

    The ``deviceName`` must also be referenced in a container definition as a
    `ResourceRequirement <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ResourceRequirement.html>`_.
    """
    deviceType: str
    """
    The Elastic Inference accelerator type to use.
    """


class ProxyConfiguration(Boto3Model):
    """
    The configuration details for the App Mesh proxy.

    For tasks that use the EC2 launch type, the container instances require at least version 1.26.0 of the container agent
    and at least version 1.26.0-1 of the ``ecs-init`` package to use a proxy configuration. If your container instances are
    launched from the Amazon ECS optimized AMI version ``20190301`` or later, then they contain the required versions of the
    container agent and ``ecs-init``. For more information, see `Amazon ECS-optimized Linux
    AMI <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-optimized_AMI.html>`_
    """

    type: Literal["APPMESH"] | None = None
    """
    The proxy type.

    The only supported value is ``APPMESH``.
    """
    containerName: str
    """
    The name of the container that will serve as the App Mesh proxy.
    """
    properties: List["KeyValuePair"] | None = None
    """
    The set of network configuration parameters to provide the Container Network
    Interface (CNI) plugin, specified as key- value pairs.
    """


class EphemeralStorage(Boto3Model):
    """The amount of ephemeral storage to allocate for the task. This parameter is used to expand the total amount of ephemeral
    storage available, beyond the default amount, for tasks hosted on Fargate. For more information, see `Using data volumes
    in tasks <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_data_volumes.html>`_ in the *Amazon ECS
    Developer Guide;*.

    For tasks using the Fargate launch type, the task requires the following platforms:

    * Linux platform version ``1.4.0`` or later.
    * Windows platform version ``1.0.0`` or later.
    """

    sizeInGiB: int
    """
    The total amount, in GiB, of ephemeral storage to set for the task.

    The minimum supported value is ``21`` GiB and the
    maximum supported value is ``200`` GiB.
    """


class TaskDefinition(TagsDictMixin, TaskDefinitionModelMixin, PrimaryBoto3Model):
    """
    The details of a task definition which describes the container and volume
    definitions of an Amazon Elastic Container Service task.

    You can specify which Docker images to use, the required resources, and other
    configurations related to launching the task definition through an Amazon ECS
    service or task.
    """

    tag_class: ClassVar[Type] = ECSTag
    manager_class: ClassVar[Type[Boto3ModelManager]] = TaskDefinitionManager

    family: str
    """
    The name of a family that this task definition is registered to.

    Up to 255 characters are allowed. Letters (both uppercase and lowercase letters),
    numbers, hyphens (-), and underscores (_) are allowed.
    """
    containerDefinitions: List["ContainerDefinition"]
    """
    A list of container definitions in JSON format that describe the different
    containers that make up your task.

    For more information about container definition parameters and defaults, see
    `Amazon ECS Task Definitions <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_defintions.html>`_
    in the *Amazon Elastic
    Container Service Developer Guide*.
    """
    networkMode: Literal["bridge", "host", "awsvpc", "none"] | None = "awsvpc"
    """
    The Docker networking mode to use for the containers in the task.

    The valid values are ``none``, ``bridge``, ``awsvpc``,
    and ``host``. If no network mode is specified, the default is ``bridge``.
    """
    taskDefinitionArn: str = Field(default=None, frozen=True)
    """
    The full Amazon Resource Name (ARN) of the task definition.
    """
    taskRoleArn: str | None = None
    """
    The short name or full Amazon Resource Name (ARN) of the Identity and Access
    Management role that grants containers in the task permission to call Amazon Web
    Services APIs on your behalf.

    For informationabout the required IAM roles for Amazon ECS, see
    `IAM roles for Amazon ECS <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-ecs-iam-
    role-overview.html>`_ in the *Amazon Elastic Container Service Developer Guide*.
    """
    executionRoleArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the task execution role that grants the Amazon ECS
    container agent permission to make Amazon Web Services API calls on your behalf.

    For informationabout the required IAM roles for Amazon ECS, see
    `IAM roles for Amazon ECS <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/security-ecs-iam-role-overview.html>`_
    in the
    *Amazon Elastic Container Service Developer Guide*.
    """
    revision: int = Field(default=None, frozen=True)
    """
    The revision of the task in a particular family.

    The revision is a version number of a task definition in a family. When
    you register a task definition for the first time, the revision is ``1``. Each time that you register a new revision of
    a task definition in the same family, the revision value always increases by one. This is even if you deregistered
    previous revisions in this family.
    """
    volumes: List["Volume"] | None = None
    """
    The list of data volume definitions for the task.

    For more information, see
    `Using data volumes in tasks <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_data_volumes.html>`_
    in the *Amazon Elastic
    Container Service Developer Guide*.
    """
    status: Literal["ACTIVE", "INACTIVE", "DELETE_IN_PROGRESS"] = Field(
        default=None, frozen=True
    )
    """
    The status of the task definition.
    """
    requiresAttributes: List["Attribute"] = Field(default_factory=list, frozen=True)
    """
    The container instance attributes required by your task.

    When an Amazon EC2 instance is registered to your cluster, the Amazon ECS container
    agent assigns some standard attributes to the instance. You can apply custom
    attributes. These are specified as key-value pairs using the Amazon ECS console or
    the
    `PutAttributes <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_PutAttributes.html>`_
    API. These attributes    are used when determining task placement for tasks hosted
    on Amazon EC2 instances. For more information, see
    `Attributes <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-placement-constraints.html#attributes>`_
    in
    the *Amazon Elastic Container Service Developer Guide*.
    """
    placementConstraints: List["TaskDefinitionPlacementConstraint"] | None = None
    """
    An array of placement constraint objects to use for tasks.
    """
    compatibilities: List[
        Literal["EC2", "FARGATE", "EXTERNAL", "MANAGED_INSTANCES"]
    ] = Field(default_factory=list, frozen=True)
    """
    Amazon ECS validates the task definition parameters with those supported by the
    launch type.

    For more information, see
    `Amazon ECS launch types <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html>`_
    in the *Amazon
    Elastic Container Service Developer Guide*.
    """
    runtimePlatform: RuntimePlatform | None = None
    """
    The operating system that your task definitions are running on.

    A platform family is specified only for tasks using the Fargate launch type.
    """
    requiresCompatibilities: List[Literal["EC2", "FARGATE", "EXTERNAL", "MANAGED_INSTANCES"]] | None = None
    """
    The task launch types the task definition was validated against.

    The valid values are ``EC2``, ``FARGATE``, and
    ``EXTERNAL``. For more information, see `Amazon ECS launch
    types <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html>`_ in the *Amazon Elastic Container
    Service Developer Guide*.
    """
    cpu: str | None = None
    """
    The number of ``cpu`` units used by the task.

    If you use the EC2 launch type, this field is optional. Any value can be
    used. If you use the Fargate launch type, this field is required. You must use one of the following values. The value
    that you choose determines your range of valid values for the ``memory`` parameter.
    """
    memory: str | None = None
    """
    The amount (in MiB) of memory used by the task.
    """
    inferenceAccelerators: List["InferenceAccelerator"] | None = None
    """
    The Elastic Inference accelerator that's associated with the task.
    """
    pidMode: Literal["host", "task"] | None = None
    """
    The process namespace to use for the containers in the task.

    The valid values are ``host`` or ``task``. On Fargate for
    Linux containers, the only valid value is ``task``. For example, monitoring sidecars might need ``pidMode`` to access
    information about other containers running in the same task.
    """
    ipcMode: Literal["host", "task", "none"] | None = None
    """
    The IPC resource namespace to use for the containers in the task.

    The valid values are ``host``, ``task``, or ``none``.
    If ``host`` is specified, then all containers within the tasks that specified the ``host`` IPC mode on the same
    container instance share the same IPC resources with the host Amazon EC2 instance. If ``task`` is specified, all
    containers within the specified task share the same IPC resources. If ``none`` is specified, then IPC resources within
    the containers of a task are private and not shared with other containers in a task or on the container instance. If no
    value is specified, then the IPC resource namespace sharing depends on the Docker daemon setting on the container
    instance.
    """
    proxyConfiguration: ProxyConfiguration | None = None
    """
    The configuration details for the App Mesh proxy.
    """
    registeredAt: datetime = Field(default=None, frozen=True)
    """
    The Unix timestamp for the time when the task definition was registered.
    """
    deregisteredAt: datetime = Field(default=None, frozen=True)
    """
    The Unix timestamp for the time when the task definition was deregistered.
    """
    registeredBy: str = Field(default=None, frozen=True)
    """
    The principal that registered the task definition.
    """
    ephemeralStorage: EphemeralStorage | None = None
    """
    The ephemeral storage settings to use for tasks run with the task definition.
    """
    enableFaultInjection: bool | None = None
    """
    Enables fault injection and allows for fault injection requests to be accepted from
    the task's containers.

    The default
    value is ``false``.
    """
    Tags: List["ECSTag"] | None = None
    """
    The tags for the task definition.
    """

    @property
    def pk(self) -> str | None:
        """
        Return the primary key of the model.   This is the value of the
        :py:attr:`taskDefinitionArn` attribute.

        Returns:
            The primary key of the model instance.
        """
        return self.taskDefinitionArn

    @property
    def arn(self) -> str | None:
        """
        Return the ARN of the model.   This is the value of the
        :py:attr:`taskDefinitionArn` attribute.

        Returns:
            The ARN of the model instance.
        """
        return self.taskDefinitionArn

    def __hash__(self) -> int:
        """
        Return the hash of the model.

        This is the value of the
        :py:attr:`taskDefinitionArn` attribute.
        """
        return hash(self.taskDefinitionArn)

    def deregister(self) -> "TaskDefinition":
        """
        Deregisters the specified task definition by family and revision.

        Upon deregistration, the task definition is marked as
        ````INACTIVE````. Existing tasks and services that reference an ````INACTIVE```` task definition continue to run without
        disruption. Existing services that reference an ````INACTIVE```` task definition can still scale up or down by modifying
        the service's desired count. If you want to delete a task definition revision, you must first deregister the task
        definition revision.
        """

        return (
            cast("TaskDefinitionManager", self.objects)  # type: ignore[attr-defined]
            .using(self.session)
            .deregister(
                self.taskDefinitionArn,
            )
        )


class NetworkBinding(Boto3Model):
    """
    Details on the network bindings between a container and its host container instance.

    After a task reaches the
    ``RUNNING`` status, manual and automatic host and container port assignments are visible in the ``networkBindings``
    section of `DescribeTasks <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeTasks.html>`_ API
    responses.
    """

    bindIP: str | None = None
    """
    The IP address that the container is bound to on the container instance.
    """
    containerPort: int | None = None
    """
    The port number on the container that's used with the network binding.
    """
    hostPort: int | None = None
    """
    The port number on the host that's used with the network binding.
    """
    protocol: Literal["tcp", "udp"] | None = None
    """
    The protocol used for the network binding.
    """
    containerPortRange: str | None = None
    """
    The port number range on the container that's bound to the dynamically mapped host
    port range.
    """
    hostPortRange: str | None = None
    """
    The port number range on the host that's used with the network binding.

    This is assigned is assigned by Docker and delivered by the Amazon ECS agent.
    """


class ManagedAgent(Boto3Model):
    """
    Details about the managed agent status for the container.
    """

    lastStartedAt: datetime | None = None
    """
    The Unix timestamp for the time when the managed agent was last started.
    """
    name: Literal["ExecuteCommandAgent"] | None = None
    """
    The name of the managed agent.

    When the execute command feature is turned on, the managed agent name is
    ``ExecuteCommandAgent``.
    """
    reason: str | None = None
    """
    The reason for why the managed agent is in the state it is in.
    """
    lastStatus: str | None = None
    """
    The last known status of the managed agent.
    """


class Container(Boto3Model):
    """
    A Docker container that's part of a task.
    """

    containerArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the container.
    """
    taskArn: str | None = None
    """
    The ARN of the task.
    """
    name: str | None = None
    """
    The name of the container.
    """
    image: str | None = None
    """
    The image used for the container.
    """
    imageDigest: str | None = None
    """
    The container image manifest digest.
    """
    runtimeId: str | None = None
    """
    The ID of the Docker container.
    """
    lastStatus: str | None = None
    """
    The last known status of the container.
    """
    exitCode: int | None = None
    """
    The exit code returned from the container.
    """
    reason: str | None = None
    """
    A short (1024 max characters) human-readable string to provide additional details
    about a running or stopped container.
    """
    networkBindings: List["NetworkBinding"] | None = None
    """
    The network bindings associated with the container.
    """
    networkInterfaces: List[NetworkInterface] | None = None
    """
    The network interfaces associated with the container.
    """
    healthStatus: Literal["HEALTHY", "UNHEALTHY", "UNKNOWN"] | None = None
    """
    The health status of the container.

    If health checks aren't configured for this container in its task definition, then
    it reports the health status as ``UNKNOWN``.
    """
    managedAgents: List["ManagedAgent"] | None = None
    """
    The details of any Amazon ECS managed agents associated with the container.
    """
    cpu: str | None = None
    """
    The number of CPU units set for the container.

    The value is ``0`` if no value was specified in the container definition
    when the task definition was registered.
    """
    memory: str | None = None
    """
    The hard limit (in MiB) of memory set for the container.
    """
    memoryReservation: str | None = None
    """
    The soft limit (in MiB) of memory set for the container.
    """
    gpuIds: List[str] | None = None
    """
    The IDs of each GPU assigned to the container.
    """


class ContainerOverride(Boto3Model):
    """
    The overrides that are sent to a container. An empty container override can be
    passed in. An example of an empty container override is ``{"containerOverrides": ` ]
    }``. If a non-empty container override is specified, the ``name`` parameter must be
    included.

    You can use Secrets Manager or Amazon Web Services Systems Manager Parameter Store to store the sensitive data. For more
    information, see [Retrieve secrets through environment
    variables <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/secrets-envvar.html>`_ in the Amazon ECS Developer
    Guide.
    """

    name: str | None = None
    """
    The name of the container that receives the override.

    This parameter is required if any override is specified.
    """
    command: List[str] | None = None
    """
    The command to send to the container that overrides the default command from the
    Docker image or the task definition.

    You must also specify a container name.
    """
    environment: List["KeyValuePair"] | None = None
    """
    The environment variables to send to the container.

    You can add new environment variables, which are added to the container at launch,
    or you can override the existing environment variables from the Docker image or the
    task definition. You must also specify a container name.
    """
    environmentFiles: List["EnvironmentFile"] | None = None
    """
    A list of files containing the environment variables to pass to a container, instead
    of the value from the container definition.
    """
    cpu: int | None = None
    """
    The number of ``cpu`` units reserved for the container, instead of the default value
    from the task definition.

    You must also specify a container name.
    """
    memory: int | None = None
    """
    The hard limit (in MiB) of memory to present to the container, instead of the
    default value from the task definition.

    If your container attempts to exceed the memory specified here, the container is
    killed. You must also specify a container name.
    """
    memoryReservation: int | None = None
    """
    The soft limit (in MiB) of memory to reserve for the container, instead of the
    default value from the task definition.

    You must also specify a container name.
    """
    resourceRequirements: List["ResourceRequirement"] | None = None
    """
    The type and amount of a resource to assign to a container, instead of the default
    value from the task definition.

    The only supported resource is a GPU.
    """


class InferenceAcceleratorOverride(Boto3Model):
    """
    Details on an Elastic Inference accelerator task override.

    This parameter is used to override the Elastic Inference accelerator specified in
    the task definition. For more information, see
    `Working with Amazon Elastic Inference on Amazon ECS <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-inference.html>`_
    in the *Amazon Elastic Container
    Service Developer Guide*.
    """

    deviceName: str | None = None
    """
    The Elastic Inference accelerator device name to override for the task.

    This parameter must match a ``deviceName``
    specified in the task definition.
    """
    deviceType: str | None = None
    """
    The Elastic Inference accelerator type to use.
    """


class TaskOverride(Boto3Model):
    """
    The overrides that are associated with a task.
    """

    containerOverrides: List["ContainerOverride"] | None = None
    """
    One or more container overrides that are sent to a task.
    """
    cpu: str | None = None
    """
    The CPU override for the task.
    """
    inferenceAcceleratorOverrides: List["InferenceAcceleratorOverride"] | None = None
    """
    The Elastic Inference accelerator override for the task.
    """
    executionRoleArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the task execution role override for the task.

    For more information, see
    `Amazon ECS task execution IAM role <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html>`_
    in
    the *Amazon Elastic Container Service Developer Guide*.
    """
    memory: str | None = None
    """
    The memory override for the task.
    """
    taskRoleArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the role that containers in this task can assume.

    All containers in this task are granted the permissions that are specified in this
    role. For more information, see
    `IAM Role for Tasks <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html>`_
    in the *Amazon Elastic Container
    Service Developer Guide*.
    """
    ephemeralStorage: EphemeralStorage | None = None
    """
    The ephemeral storage setting override for the task.
    """


class TaskEphemeralStorage(Boto3Model):
    """
    The amount of ephemeral storage to allocate for the task.
    """

    sizeInGiB: int | None = None
    """
    The total amount, in GiB, of the ephemeral storage to set for the task.

    The minimum supported value is ``20`` GiB and
    the maximum supported value is
     ``200`` GiB.
    """
    kmsKeyId: str | None = None
    """
    Specify an Key Management Service key ID to encrypt the ephemeral storage for the
    task.
    """


class Task(TagsDictMixin, PrimaryBoto3Model):
    """
    Details on a task in a cluster.
    """

    tag_class: ClassVar[Type] = ECSTag
    manager_class: ClassVar[Type[Boto3ModelManager]] = TaskManager

    Tags: List["ECSTag"] = Field(default_factory=list, alias="tags")
    """
    The metadata that you apply to the task to help you categorize and organize the
    task.

    Each tag consists of a key and an optional value. You define both the key and value.
    """
    clusterArn: str
    """
    The ARN of the cluster that hosts the task.
    """
    platformVersion: str | None = "LATEST"
    """
    The platform version where your task runs on.

    A platform version is only specified for tasks that use the Fargate launch
    type. If you didn't specify one, the ``LATEST`` platform version is used. For more information, see `Fargate Platform
    Versions <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html>`_ in the *Amazon Elastic
    Container Service Developer Guide*.
    """
    launchType: Literal["EC2", "FARGATE", "EXTERNAL", "MANAGED_INSTANCES"] | None = (
        "FARGATE"
    )
    """
    The infrastructure where your task runs on.

    For more information, see
    `Amazon ECS launch types <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html>`_
    in the *Amazon Elastic Container
    Service Developer Guide*.
    """
    attachments: List["Attachment"] = Field(default_factory=list, frozen=True)
    """
    The Elastic Network Adapter that's associated with the task if the task uses the
    ``awsvpc`` network mode.
    """
    attributes: List["Attribute"] = Field(default_factory=list, frozen=True)
    """
    The attributes of the task.
    """
    availabilityZone: str = Field(default=None, frozen=True)
    """
    The Availability Zone for the task.
    """
    capacityProviderName: str = Field(default=None, frozen=True)
    """
    The capacity provider that's associated with the task.
    """
    connectivity: Literal["CONNECTED", "DISCONNECTED"] = Field(
        default=None, frozen=True
    )
    """
    The connectivity status of a task.
    """
    connectivityAt: datetime = Field(default=None, frozen=True)
    """
    The Unix timestamp for the time when the task last went into ``CONNECTED`` status.
    """
    containerInstanceArn: str = Field(default=None, frozen=True)
    """
    The ARN of the container instances that host the task.
    """
    containers: List["Container"] = Field(default_factory=list, frozen=True)
    """
    The containers that's associated with the task.
    """
    cpu: str = Field(default=None, frozen=True)
    """
    The number of CPU units used by the task as expressed in a task definition.

    It can be expressed as an integer using CPU
    units (for example, ``1024``). It can also be expressed as a string using vCPUs (for example, ``1 vCPU`` or ``1 vcpu``).
    String values are converted to an integer that indicates the CPU units when the task definition is registered.
    """
    createdAt: datetime = Field(default=None, frozen=True)
    """
    The Unix timestamp for the time when the task was created.

    More specifically, it's for the time when the task entered
    the ``PENDING`` state.
    """
    desiredStatus: str = Field(default=None, frozen=True)
    """
    The desired status of the task.

    For more information, see
    `Task Lifecycle <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-lifecycle.html>`_.
    """
    enableExecuteCommand: bool | None = None
    """
    Determines whether execute command functionality is turned on for this task.

    If ``true``, execute command functionality
    is turned on all the containers in the task.
    """
    executionStoppedAt: datetime = Field(default=None, frozen=True)
    """
    The Unix timestamp for the time when the task execution stopped.
    """
    group: str | None = None
    """
    The name of the task group that's associated with the task.
    """
    healthStatus: Literal["HEALTHY", "UNHEALTHY", "UNKNOWN"] = Field(
        default=None, frozen=True
    )
    """
    The health status for the task.

    It's determined by the health of the essential containers in the task. If all essential
    containers in the task are reporting as ``HEALTHY``, the task status also reports as ``HEALTHY``. If any essential
    containers in the task are reporting as ``UNHEALTHY`` or ``UNKNOWN``, the task status also reports as ``UNHEALTHY`` or
    ``UNKNOWN``.
    """
    inferenceAccelerators: List["InferenceAccelerator"] = Field(
        default_factory=list, frozen=True
    )
    """
    The Elastic Inference accelerator that's associated with the task.
    """
    lastStatus: str = Field(default=None, frozen=True)
    """
    The last known status for the task.

    For more information, see
    `Task Lifecycle <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-lifecycle.html>`_.
    """
    memory: str = Field(default=None, frozen=True)
    """
    The amount of memory (in MiB) that the task uses as expressed in a task definition.

    It can be expressed as an integer
    using MiB (for example, ``1024``). If it's expressed as a string using GB (for example, ``1GB`` or ``1 GB``), it's
    converted to an integer indicating the MiB when the task definition is registered.
    """
    overrides: TaskOverride | None = None
    """
    One or more container overrides.
    """
    platformFamily: str = Field(default=None, frozen=True)
    """
    The operating system that your tasks are running on.

    A platform family is specified only for tasks that use the Fargate launch type.
    """
    pullStartedAt: datetime = Field(default=None, frozen=True)
    """
    The Unix timestamp for the time when the container image pull began.
    """
    pullStoppedAt: datetime = Field(default=None, frozen=True)
    """
    The Unix timestamp for the time when the container image pull completed.
    """
    startedAt: datetime = Field(default=None, frozen=True)
    """
    The Unix timestamp for the time when the task started.

    More specifically, it's for the time when the task transitioned
    from the ``PENDING`` state to the ``RUNNING`` state.
    """
    startedBy: str | None = None
    """
    The tag specified when a task is started.

    If an Amazon ECS service started the task, the ``startedBy`` parameter
    contains the deployment ID of that service.
    """
    stopCode: Literal[
        "TaskFailedToStart",
        "EssentialContainerExited",
        "UserInitiated",
        "ServiceSchedulerInitiated",
        "SpotInterruption",
        "TerminationNotice",
    ] = Field(default=None, frozen=True)
    """
    The stop code indicating why a task was stopped.

    The ``stoppedReason`` might contain additional details.
    """
    stoppedAt: datetime = Field(default=None, frozen=True)
    """
    The Unix timestamp for the time when the task was stopped.

    More specifically, it's for the time when the task
    transitioned from the ``RUNNING`` state to the ``STOPPED`` state.
    """
    stoppedReason: str = Field(default=None, frozen=True)
    """
    The reason that the task was stopped.
    """
    stoppingAt: datetime = Field(default=None, frozen=True)
    """
    The Unix timestamp for the time when the task stops.

    More specifically, it's for the time when the task transitions from
    the ``RUNNING`` state to ``STOPPING``.
    """
    taskArn: str = Field(default=None, frozen=True)
    """
    The Amazon Resource Name (ARN) of the task.
    """
    taskDefinitionArn: str = Field(default=None, frozen=True)
    """
    The ARN of the task definition that creates the task.
    """
    version: int = Field(default=None, frozen=True)
    """
    The version counter for the task.

    Every time a task experiences a change that starts a CloudWatch event, the version
    counter is incremented. If you replicate your Amazon ECS task state with CloudWatch Events, you can compare the version
    of a task reported by the Amazon ECS API actions with the version reported in CloudWatch Events for the task (inside the
    ``detail`` object) to verify that the version in your event stream is current.
    """
    ephemeralStorage: EphemeralStorage = Field(default=None, frozen=True)
    """
    The ephemeral storage settings for the task.
    """
    fargateEphemeralStorage: TaskEphemeralStorage = Field(default=None, frozen=True)
    """
    The Fargate ephemeral storage settings for the task.
    """
    taskDefinition: str | None = None
    """
    The ``family`` and ``revision`` (``family:revision``) or full ARN of the task
    definition to run.

    If a ``revision`` isn't
    specified, the latest ``ACTIVE`` revision is used.
    """

    @property
    def pk(self) -> str | None:
        """
        Return the primary key of the model.   This is the value of the
        :py:attr:`taskArn` attribute.

        Returns:
            The primary key of the model instance.
        """
        return self.taskArn

    @property
    def arn(self) -> str | None:
        """
        Return the ARN of the model.   This is the value of the :py:attr:`taskArn`
        attribute.

        Returns:
            The ARN of the model instance.
        """
        return self.taskArn

    def __hash__(self) -> int:
        """
        Return the hash of the model.

        This is the value of the
        :py:attr:`taskArn` attribute.
        """
        return hash(self.taskArn)

    @property
    def serviceName(self) -> str | None:
        """
        The name of the service that ran this task, if any.
        """

        return self.transform("group", r"^service:(.+)$")

    @cached_property
    def cluster(self) -> Optional["Cluster"]:
        """
        Return the :py:class:`Cluster` object that this task belongs to, if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "cluster": self.clusterArn,
                }
            )
        except AttributeError:
            return None
        return Cluster.objects.using(self.session).get(**pk)  # type: ignore[arg-type]

    @cached_property
    def task_definition(self) -> Optional["TaskDefinition"]:
        """
        Return the :py:class:`TaskDefinition` object that this task uses, if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "taskDefinition": self.taskDefinition,
                }
            )
        except AttributeError:
            return None
        return TaskDefinition.objects.using(self.session).get(**pk)  # type: ignore[arg-type]

    @cached_property
    def container_instance(self) -> Optional["ContainerInstance"]:
        """
        Return the :py:class:`ContainerInstance` object that runs this task, if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "containerInstance": self.containerInstanceArn,
                    "cluster": self.clusterArn,
                }
            )
        except AttributeError:
            return None
        return ContainerInstance.objects.using(self.session).get(**pk)  # type: ignore[arg-type]

    @cached_property
    def service(self) -> Optional["Service"]:
        """
        Return the :py:class:`Service` object that runs this task, if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "service": self.serviceName,
                    "cluster": self.clusterArn,
                }
            )
        except AttributeError:
            return None
        return Service.objects.using(self.session).get(**pk)  # type: ignore[arg-type]


class VersionInfo(Boto3Model):
    """
    The Docker and Amazon ECS container agent version information about a container
    instance.
    """

    agentVersion: str | None = None
    """
    The version number of the Amazon ECS container agent.
    """
    agentHash: str | None = None
    """
The Git commit hash for the Amazon ECS container agent build on the `amazon-ecs-agent <https://github.com/aws/amazon-
ecs-agent>`_  GitHub repository.
    """
    dockerVersion: str | None = None
    """
    The Docker version that's running on the container instance.
    """


class ContainerInstanceResource(Boto3Model):
    """
    Describes the resources available for a container instance.
    """

    name: str | None = None
    """
    The name of the resource, such as ``CPU``, ``MEMORY``, ``PORTS``, ``PORTS_UDP``, or
    a user-defined resource.
    """
    type: str | None = None
    """
    The type of the resource.

    Valid values: ``INTEGER``, ``DOUBLE``, ``LONG``, or ``STRINGSET``.
    """
    doubleValue: float | None = None
    """
    When the ``doubleValue`` type is set, the value of the resource must be a double
    precision floating-point type.
    """
    longValue: int | None = None
    """
    When the ``longValue`` type is set, the value of the resource must be an extended
    precision floating-point type.
    """
    integerValue: int | None = None
    """
    When the ``integerValue`` type is set, the value of the resource must be an integer.
    """
    stringSetValue: List[str] | None = None
    """
    When the ``stringSetValue`` type is set, the value of the resource must be a string
    type.
    """


class InstanceHealthCheckResult(Boto3Model):
    """
    An object representing the result of a container instance health status check.
    """

    type: Literal["CONTAINER_RUNTIME"] | None = None
    """
    The type of container instance health status that was verified.
    """
    status: Literal["OK", "IMPAIRED", "INSUFFICIENT_DATA", "INITIALIZING"] | None = (
        None
    )
    """
    The container instance health status.
    """
    lastUpdated: datetime | None = None
    """
    The Unix timestamp for when the container instance health status was last updated.
    """
    lastStatusChange: datetime | None = None
    """
    The Unix timestamp for when the container instance health status last changed.
    """


class ContainerInstanceHealthStatus(Boto3Model):
    """
    An object representing the health status of the container instance.
    """

    overallStatus: Literal["OK", "IMPAIRED", "INSUFFICIENT_DATA", "INITIALIZING"] | None = None
    """
    The overall health status of the container instance.

    This is an aggregate status of all container instance health checks.
    """
    details: List["InstanceHealthCheckResult"] | None = None
    """
    An array of objects representing the details of the container instance health
    status.
    """


class ContainerInstance(
    TagsDictMixin, ECSContainerInstanceModelMixin, ReadonlyPrimaryBoto3Model
):
    """
    An Amazon EC2 or External instance that's running the Amazon ECS agent and has been
    registered with a cluster.
    """

    tag_class: ClassVar[Type] = ECSTag
    manager_class: ClassVar[Type[Boto3ModelManager]] = ContainerInstanceManager

    Tags: List["ECSTag"] = Field(default_factory=list, alias="tags")
    """
    The metadata that you apply to the container instance to help you categorize and
    organize them.

    Each tag consists of a key and an optional value. You define both.
    """
    containerInstanceArn: str | None = None
    """
    The Amazon Resource Name (ARN) of the container instance.

    For more information about the ARN format, see `Amazon
    Resource Name (ARN) <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-account-settings.html#ecs-resource-
    ids>`_ in the *Amazon ECS Developer Guide*.
    """
    ec2InstanceId: str | None = None
    """
    The ID of the container instance.

    For Amazon EC2 instances, this value is the Amazon EC2 instance ID. For external
    instances, this value is the Amazon Web Services Systems Manager managed instance
    ID.
    """
    capacityProviderName: str | None = None
    """
    The capacity provider that's associated with the container instance.
    """
    version: int | None = None
    """
    The version counter for the container instance.

    Every time a container instance experiences a change that triggers a
    CloudWatch event, the version counter is incremented. If you're replicating your Amazon ECS container instance state
    with CloudWatch Events, you can compare the version of a container instance reported by the Amazon ECS APIs with the
    version reported in CloudWatch Events for the container instance (inside the ``detail`` object) to verify that the
    version in your event stream is current.
    """
    versionInfo: VersionInfo | None = None
    """
    The version information for the Amazon ECS container agent and Docker daemon running
    on the container instance.
    """
    remainingResources: List["ContainerInstanceResource"] | None = None
    """
    For CPU and memory resource types, this parameter describes the remaining CPU and
    memory that wasn't already allocated to tasks and is therefore available for new
    tasks.

    For port resource types, this parameter describes the ports that were
    reserved by the Amazon ECS container agent (at instance registration time) and any task containers that have reserved
    port mappings on the host (with the ``host`` or ``bridge`` network mode). Any port that's not specified here is
    available for new tasks.
    """
    registeredResources: List["ContainerInstanceResource"] | None = None
    """
    For CPU and memory resource types, this parameter describes the amount of each
    resource that was available on the container instance when the container agent
    registered it with Amazon ECS.

    This value represents the total amount of CPU and memory that can be allocated on
    this container instance to tasks. For port resource types, this parameter describes
    the ports that were reserved by the Amazon ECS container agent when it registered
    the container instance with Amazon ECS.
    """
    status: str | None = None
    """
    The status of the container instance.

    The valid values are ``REGISTERING``, ``REGISTRATION_FAILED``, ``ACTIVE``,
    ``INACTIVE``, ``DEREGISTERING``, or ``DRAINING``.
    """
    statusReason: str | None = None
    """
    The reason that the container instance reached its current status.
    """
    agentConnected: bool | None = None
    """
    This parameter returns ``true`` if the agent is connected to Amazon ECS.

    An instance with an agent that may be unhealthy
    or stopped return ``false``. Only instances connected to an agent can accept task placement requests.
    """
    runningTasksCount: int | None = None
    """
    The number of tasks on the container instance that have a desired status
    (``desiredStatus``) of ``RUNNING``.
    """
    pendingTasksCount: int | None = None
    """
    The number of tasks on the container instance that are in the ``PENDING`` status.
    """
    agentUpdateStatus: Literal["PENDING", "STAGING", "STAGED", "UPDATING", "UPDATED", "FAILED"] | None = None
    """
    The status of the most recent agent update.

    If an update wasn't ever requested, this value is ``NULL``.
    """
    attributes: List["Attribute"] | None = None
    """
The attributes set for the container instance, either by the Amazon ECS container agent at instance registration or
manually with the `PutAttributes <https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_PutAttributes.html>`_
operation.
    """
    registeredAt: datetime | None = None
    """
    The Unix timestamp for the time when the container instance was registered.
    """
    attachments: List["Attachment"] | None = None
    """
    The resources attached to a container instance, such as an elastic network
    interface.
    """
    healthStatus: ContainerInstanceHealthStatus | None = None
    """
    An object representing the health status of the container instance.
    """

    @property
    def pk(self) -> str | None:
        """
        Return the primary key of the model.   This is the value of the
        :py:attr:`containerInstanceArn` attribute.

        Returns:
            The primary key of the model instance.
        """
        return self.containerInstanceArn

    @property
    def arn(self) -> str | None:
        """
        Return the ARN of the model.   This is the value of the
        :py:attr:`containerInstanceArn` attribute.

        Returns:
            The ARN of the model instance.
        """
        return self.containerInstanceArn

    def __hash__(self) -> int:
        """
        Return the hash of the model.

        This is the value of the
        :py:attr:`containerInstanceArn` attribute.
        """
        return hash(self.containerInstanceArn)

    @property
    def clusterName(self) -> str | None:
        """
        The name of the cluster that houses this task, if any.
        """

        return self.transform(
            "containerInstanceArn", r":container-instance/(.+)/[0-9a-f]+$"
        )

    @property
    def name(self) -> str | None:
        """
        The name of the cluster that houses this task, if any.
        """

        return self.transform(
            "containerInstanceArn", r":container-instance/.+/([0-9a-f]+)$"
        )

    @cached_property
    def instance(self) -> Optional["Instance"]:
        """
        Return the :py:class:`Instance` object that this container instance represents,
        if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "InstanceId": self.ec2InstanceId,
                }
            )
        except AttributeError:
            return None
        return Instance.objects.using(self.session).get(**pk)  # type: ignore[arg-type]

    @property
    def tasks(self) -> List["Task"] | None:
        """
        Return the ARNs of :py:class:`Task` objects that run on this container instance,
        if any.
        """

        try:
            pk = OrderedDict(
                {
                    "cluster": self.clusterName,
                    "containerInstance": self.containerInstanceArn,
                    "desiredStatus": "RUNNING",
                }
            )
        except AttributeError:
            return []
        return Task.objects.using(self.session).list(**pk)  # type: ignore[arg-type]


class ServiceRevisionSummary(Boto3Model):
    """
    The information about the number of requested, pending, and running tasks for a
    service revision.
    """

    arn: str | None = None
    """
    The ARN of the service revision.
    """
    requestedTaskCount: int | None = None
    """
    The number of requested tasks for the service revision.
    """
    runningTaskCount: int | None = None
    """
    The number of running tasks for the service revision.
    """
    pendingTaskCount: int | None = None
    """
    The number of pending tasks for the service revision.
    """


class Rollback(Boto3Model):
    """
    Information about the service deployment rollback.
    """

    reason: str | None = None
    """
    The reason the rollback happened.

    For example, the circuit breaker initiated the rollback operation.
    """
    startedAt: datetime | None = None
    """
    Time time that the rollback started.

    The format is yyyy-MM-dd HH:mm:ss.SSSSSS.
    """
    serviceRevisionArn: str | None = None
    """
    The ARN of the service revision deployed as part of the rollback.
    """


class ServiceDeploymentCircuitBreaker(Boto3Model):
    """
    Information about the circuit breaker used to determine when a service deployment
    has failed.

    The deployment circuit breaker is the rolling update mechanism that determines if
    the tasks reach a steady state. The deployment circuit breaker has an option that
    will automatically roll back a failed deployment to the last cpompleted service
    revision. For more information, see
    `How the Amazon ECS deployment circuit breaker detects failures <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-circuit-breaker.html>`_
    in the *Amazon
    ECS Developer Guide*.
    """

    status: Literal["TRIGGERED", "MONITORING", "MONITORING_COMPLETE", "DISABLED"] | None = None
    """
    The circuit breaker status.

    Amazon ECS is not using the circuit breaker for service deployment failures when the status
    is ``DISABLED``.
    """
    failureCount: int | None = None
    """
    The number of times the circuit breaker detected a service deploymeny failure.
    """
    threshold: int | None = None
    """
    The threshhold which determines that the service deployment failed.
    """


class ServiceDeploymentAlarms(Boto3Model):
    """
    The CloudWatch alarms used to determine a service deployment failed.

    Amazon ECS considers the service deployment as failed when any of the alarms move to the ``ALARM`` state. For more
    information, see `How CloudWatch alarms detect Amazon ECS deployment
    failures <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-alarm-failure.html>`_ in the Amazon ECS
    Developer Guide.
    """

    status: Literal["TRIGGERED", "MONITORING", "MONITORING_COMPLETE", "DISABLED"] | None = None
    """
    The status of the alarms check.

    Amazon ECS is not using alarms for service deployment failures when the status is
    ``DISABLED``.
    """
    alarmNames: List[str] | None = None
    """
    The name of the CloudWatch alarms that determine when a service deployment failed.

    A "," separates the alarms.
    """
    triggeredAlarmNames: List[str] | None = None
    """
    One or more CloudWatch alarm names that have been triggered during the service
    deployment.

    A "," separates the alarm names.
    """


class ServiceDeployment(ReadonlyPrimaryBoto3Model):
    """
    Information about the service deployment.

    Service deployments provide a comprehensive view of your deployments. For
    information about service deployments, see
    `View service history using Amazon ECS service deployments <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-deployment.html>`_
    in the  **Amazon
    Elastic Container Service Developer Guide** .
    """

    manager_class: ClassVar[Type[Boto3ModelManager]] = ServiceDeploymentManager

    serviceDeploymentArn: str | None = None
    """
    The ARN of the service deployment.
    """
    serviceArn: str | None = None
    """
    The ARN of the service for this service deployment.
    """
    clusterArn: str | None = None
    """
    The ARN of the cluster that hosts the service.
    """
    createdAt: datetime | None = None
    """
    The time the service deployment was created.

    The format is yyyy-MM-dd HH:mm:ss.SSSSSS.
    """
    startedAt: datetime | None = None
    """
    The time the service deployment statred.

    The format is yyyy-MM-dd HH:mm:ss.SSSSSS.
    """
    finishedAt: datetime | None = None
    """
    The time the service deployment finished.

    The format is yyyy-MM-dd HH:mm:ss.SSSSSS.
    """
    stoppedAt: datetime | None = None
    """
    The time the service deployment stopped.

    The format is yyyy-MM-dd HH:mm:ss.SSSSSS.
    """
    updatedAt: datetime | None = None
    """
    The time that the service deployment was last updated.

    The format is yyyy-MM-dd HH:mm:ss.SSSSSS.
    """
    sourceServiceRevisions: List["ServiceRevisionSummary"] | None = None
    """
    The currently deployed workload configuration.
    """
    targetServiceRevision: ServiceRevisionSummary | None = None
    """
    The workload configuration being deployed.
    """
    status: Literal["PENDING", "SUCCESSFUL", "STOPPED", "STOP_REQUESTED", "IN_PROGRESS", "ROLLBACK_REQUESTED", "ROLLBACK_IN_PROGRESS", "ROLLBACK_SUCCESSFUL", "ROLLBACK_FAILED"] | None = None
    """
    The service deployment state.
    """
    statusReason: str | None = None
    """
    Information about why the service deployment is in the current status.

    For example, the circuit breaker detected a failure.
    """
    lifecycleStage: Literal["RECONCILE_SERVICE", "PRE_SCALE_UP", "SCALE_UP", "POST_SCALE_UP", "TEST_TRAFFIC_SHIFT", "POST_TEST_TRAFFIC_SHIFT", "PRODUCTION_TRAFFIC_SHIFT", "POST_PRODUCTION_TRAFFIC_SHIFT", "BAKE_TIME", "CLEAN_UP"] | None = None
    """
    The current lifecycle stage of the deployment.

    Possible values include:
    """
    deploymentConfiguration: DeploymentConfiguration | None = None
    """
    Optional deployment parameters that control how many tasks run during a deployment
    and the ordering of stopping and starting tasks.
    """
    rollback: Rollback | None = None
    """
    The rollback options the service deployment uses when the deployment fails.
    """
    deploymentCircuitBreaker: ServiceDeploymentCircuitBreaker | None = None
    """
    The circuit breaker configuration that determines a service deployment failed.
    """
    alarms: ServiceDeploymentAlarms | None = None
    """
    The CloudWatch alarms that determine when a service deployment fails.
    """

    @property
    def pk(self) -> str | None:
        """
        Return the primary key of the model.   This is the value of the
        :py:attr:`serviceDeploymentArn` attribute.

        Returns:
            The primary key of the model instance.
        """
        return self.serviceDeploymentArn

    @property
    def arn(self) -> str | None:
        """
        Return the ARN of the model.   This is the value of the
        :py:attr:`serviceDeploymentArn` attribute.

        Returns:
            The ARN of the model instance.
        """
        return self.serviceDeploymentArn

    def __hash__(self) -> int:
        """
        Return the hash of the model.

        This is the value of the
        :py:attr:`serviceDeploymentArn` attribute.
        """
        return hash(self.serviceDeploymentArn)

    @cached_property
    def target_task_definition(self) -> Optional["TaskDefinition"]:
        """
        Return the :py:class:`TaskDefinition` object that this deployment uses, if any.

        .. note::

            The output of this property is cached on the model instance, so
            calling this multiple times will not result in multiple calls to the
            AWS API.   If you need a fresh copy of the data, you can re-get the
            model instance from the manager.
        """

        try:
            pk = OrderedDict(
                {
                    "taskDefinition": self.targetServiceRevision.arn,
                }
            )
        except AttributeError:
            return None
        return TaskDefinition.objects.using(self.session).get(**pk)  # type: ignore[arg-type]


# =======================
# Request/Response Models
# =======================


class CreateServiceResponse(Boto3Model):
    service: Service | None = None
    """
    The full description of your service following the create call.
    """


class DeleteServiceResponse(Boto3Model):
    service: Service | None = None
    """
    The full description of the deleted service.
    """


class Failure(Boto3Model):
    """
    A failed resource.

    For a list of common causes, see
    `API failure reasons <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/api_failures_messages.html>`_
    in the *Amazon Elastic
    Container Service Developer Guide*.
    """

    arn: str | None = None
    """
    The Amazon Resource Name (ARN) of the failed resource.
    """
    reason: str | None = None
    """
    The reason for the failure.
    """
    detail: str | None = None
    """
    The details of the failure.
    """


class DescribeServicesResponse(Boto3Model):
    services: List["Service"] | None = None
    """
    The list of services described.
    """
    failures: List["Failure"] | None = None
    """
    Any failures associated with the call.
    """


class ListServicesResponse(Boto3Model):
    serviceArns: List[str] | None = None
    """
    The list of full ARN entries for each service that's associated with the specified
    cluster.
    """
    nextToken: str | None = None
    """
    The ``nextToken`` value to include in a future ``ListServices`` request.

    When the results of a ``ListServices`` request
    exceed ``maxResults``, this value can be used to retrieve the next page of results. This value is ``null`` when there
    are no more results to return.
    """


class UpdateServiceResponse(Boto3Model):
    service: Service | None = None
    """
    The full description of your service following the update call.
    """


class ClusterServiceConnectDefaultsRequest(Boto3Model):
    """
    Use this parameter to set a default Service Connect namespace. After you set a
    default Service Connect namespace, any new services with Service Connect turned on
    that are created in the cluster are added as client services in the namespace. This
    setting only applies to new services that set the ``enabled`` parameter to ``true``
    in the ``ServiceConnectConfiguration``. You can set the namespace of each service
    individually in the ``ServiceConnectConfiguration`` to override this default
    parameter.

    Tasks that run in a namespace can use short names to connect to services in the
    namespace. Tasks can connect to services across all of the clusters in the
    namespace. Tasks connect through a managed proxy container that collects logs and
    metrics for increased visibility. Only the tasks that Amazon ECS services create are
    supported with Service Connect. For more information, see
    `Service Connect <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-
    connect.html>`_ in the *Amazon Elastic Container Service Developer Guide*.
    """

    namespace: str
    """
    The namespace name or full Amazon Resource Name (ARN) of the Cloud Map namespace
    that's used when you create a service and don't specify a Service Connect
    configuration.

    The namespace name can include up to 1024 characters. The name is case-sensitive.
    The name can't include greater than (>), less than (<), double quotation marks ("),
    or slash (/).
    """


class CreateClusterResponse(Boto3Model):
    cluster: Cluster | None = None
    """
    The full description of your new cluster.
    """


class DeleteClusterResponse(Boto3Model):
    cluster: Cluster | None = None
    """
    The full description of the deleted cluster.
    """


class DescribeClustersResponse(Boto3Model):
    clusters: List["Cluster"] | None = None
    """
    The list of clusters.
    """
    failures: List["Failure"] | None = None
    """
    Any failures associated with the call.
    """


class ListClustersResponse(Boto3Model):
    clusterArns: List[str] | None = None
    """
    The list of full Amazon Resource Name (ARN) entries for each cluster that's
    associated with your account.
    """
    nextToken: str | None = None
    """
    The ``nextToken`` value to include in a future ``ListClusters`` request.

    When the results of a ``ListClusters`` request
    exceed ``maxResults``, this value can be used to retrieve the next page of results. This value is ``null`` when there
    are no more results to return.
    """


class UpdateClusterResponse(Boto3Model):
    cluster: Cluster | None = None
    """
    Details about the cluster.
    """


class RegisterTaskDefinitionResponse(TagsDictMixin, Boto3Model):
    tag_class: ClassVar[Type] = ECSTag
    Tags: List["ECSTag"] = Field(default_factory=list, alias="tags")
    """
    The list of tags associated with the task definition.
    """
    taskDefinition: TaskDefinition | None = None
    """
    The full description of the registered task definition.
    """


class DeleteTaskDefinitionsResponse(Boto3Model):
    taskDefinitions: List["TaskDefinition"] | None = None
    """
    The list of deleted task definitions.
    """
    failures: List["Failure"] | None = None
    """
    Any failures associated with the call.
    """


class DescribeTaskDefinitionResponse(TagsDictMixin, Boto3Model):
    tag_class: ClassVar[Type] = ECSTag
    Tags: List["ECSTag"] = Field(default_factory=list, alias="tags")
    """
    The metadata that's applied to the task definition to help you categorize and
    organize them.

    Each tag consists of a key and an optional value. You define both.
    """
    taskDefinition: TaskDefinition | None = None
    """
    The full task definition description.
    """


class ListTaskDefinitionsResponse(Boto3Model):
    taskDefinitionArns: List[str] | None = None
    """
    The list of task definition Amazon Resource Name (ARN) entries for the
    ``ListTaskDefinitions`` request.
    """
    nextToken: str | None = None
    """
    The ``nextToken`` value to include in a future ``ListTaskDefinitions`` request.

    When the results of a
    ``ListTaskDefinitions`` request exceed ``maxResults``, this value can be used to retrieve the next page of results. This
    value is ``null`` when there are no more results to return.
    """


class DeregisterTaskDefinitionResponse(Boto3Model):
    taskDefinition: TaskDefinition | None = None
    """
    The full description of the deregistered task.
    """


class ListTaskDefinitionFamiliesResponse(Boto3Model):
    families: List[str] | None = None
    """
    The list of task definition family names that match the
    ``ListTaskDefinitionFamilies`` request.
    """
    nextToken: str | None = None
    """
    The ``nextToken`` value to include in a future ``ListTaskDefinitionFamilies``
    request.

    When the results of a
    ``ListTaskDefinitionFamilies`` request exceed ``maxResults``, this value can be used to retrieve the next page of
    results. This value is ``null`` when there are no more results to return.
    """


class DescribeContainerInstancesResponse(Boto3Model):
    containerInstances: List["ContainerInstance"] | None = None
    """
    The list of container instances.
    """
    failures: List["Failure"] | None = None
    """
    Any failures associated with the call.
    """


class ListContainerInstancesResponse(Boto3Model):
    containerInstanceArns: List[str] | None = None
    """
    The list of container instances with full ARN entries for each container instance
    associated with the specified cluster.
    """
    nextToken: str | None = None
    """
    The ``nextToken`` value to include in a future ``ListContainerInstances`` request.

    When the results of a
    ``ListContainerInstances`` request exceed ``maxResults``, this value can be used to retrieve the next page of results.
    This value is ``null`` when there are no more results to return.
    """


class ListTasksResponse(Boto3Model):
    taskArns: List[str] | None = None
    """
    The list of task ARN entries for the ``ListTasks`` request.
    """
    nextToken: str | None = None
    """
    The ``nextToken`` value to include in a future ``ListTasks`` request.

    When the results of a ``ListTasks`` request exceed
    ``maxResults``, this value can be used to retrieve the next page of results. This value is ``null`` when there are no
    more results to return.
    """


class DescribeTasksResponse(Boto3Model):
    tasks: List["Task"] | None = None
    """
    The list of tasks.
    """
    failures: List["Failure"] | None = None
    """
    Any failures associated with the call.
    """


class TaskManagedEBSVolumeTerminationPolicy(Boto3Model):
    """
    The termination policy for the Amazon EBS volume when the task exits.

    For more information, see
    `Amazon ECS volume termination policy <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ebs-volumes.html#ebs-volume-types>`_.
    """

    deleteOnTermination: bool
    """
    Indicates whether the volume should be deleted on when the task stops.

    If a value of ``true`` is specified,
    Amazon ECS
    deletes the Amazon EBS volume on your behalf when the task goes into the ``STOPPED`` state. If no value is specified,
    the
    default value is ``true`` is used. When set to ``false``, Amazon ECS leaves the volume in your
    account.
    """


class TaskManagedEBSVolumeConfiguration(Boto3Model):
    """
    The configuration for the Amazon EBS volume that Amazon ECS creates and manages on
    your behalf.

    These settings are used to create each Amazon EBS volume, with one volume created
    for each task.
    """

    encrypted: bool | None = None
    """
    Indicates whether the volume should be encrypted.

    If you turn on Region-level Amazon EBS encryption by default but set
    this value as ``false``, the setting is overridden and the volume is encrypted with the KMS key specified for Amazon EBS
    encryption by default. This parameter maps 1:1 with the ``Encrypted`` parameter of the `CreateVolume
    API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the *Amazon EC2 API Reference*.
    """
    kmsKeyId: str | None = None
    """
    The Amazon Resource Name (ARN) identifier of the Amazon Web Services Key Management
    Service key to use for Amazon EBS encryption.

    When a key is specified using this parameter, it overrides Amazon EBS default encryption or any KMS key that
    you specified for cluster-level managed storage encryption. This parameter maps 1:1 with the ``KmsKeyId`` parameter of
    the `CreateVolume API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the *Amazon EC2
    API Reference*. For more information about encrypting Amazon EBS volumes attached to a task, see `Encrypt data stored in
    Amazon EBS volumes attached to Amazon ECS tasks <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ebs-kms-
    encryption.html>`_.
    """
    volumeType: str | None = None
    """
    The volume type.

    This parameter maps 1:1 with the ``VolumeType`` parameter of the `CreateVolume
    API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the *Amazon EC2 API Reference*.
    For more information, see `Amazon EBS volume types <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volume-
    types.html>`_ in the *Amazon EC2 User Guide*.
    """
    sizeInGiB: int | None = None
    """
    The size of the volume in GiB.

    You must specify either a volume size or a snapshot ID. If you specify a snapshot ID, the
    snapshot size is used for the volume size by default. You can optionally specify a volume size greater than or equal to
    the snapshot size. This parameter maps 1:1 with the ``Size`` parameter of the `CreateVolume
    API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the *Amazon EC2 API Reference*.
    """
    snapshotId: str | None = None
    """
    The snapshot that Amazon ECS uses to create the volume.

    You must specify either a snapshot ID or a volume size. This
    parameter maps 1:1 with the ``SnapshotId`` parameter of the `CreateVolume
    API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the *Amazon EC2 API Reference*.
    """
    volumeInitializationRate: int | None = None
    """
    The rate, in MiB/s, at which data is fetched from a snapshot of an existing Amazon
    EBS volume to create a new volume for attachment to the task.

    This property can be specified only if you specify a ``snapshotId``. For more information, see
    `Initialize Amazon EBS volumes <https://docs.aws.amazon.com/ebs/latest/userguide/initalize-volume.html>`_ in the *Amazon
    EBS User Guide*.
    """
    iops: int | None = None
    """
    The number of I/O operations per second (IOPS).

    For ``gp3``, ``io1``, and ``io2`` volumes, this represents the number of
    IOPS that are provisioned for the volume. For ``gp2`` volumes, this represents the baseline performance of the volume
    and the rate at which the volume accumulates I/O credits for bursting.
    """
    throughput: int | None = None
    """
    The throughput to provision for a volume, in MiB/s, with a maximum of 1,000 MiB/s.

    This parameter maps 1:1 with the
    ``Throughput`` parameter of the `CreateVolume
    API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the *Amazon EC2 API Reference*.
    """
    tagSpecifications: List["EBSTagSpecification"] | None = None
    """
    The tags to apply to the volume.

    Amazon ECS applies service-managed tags by default. This parameter maps 1:1 with the
    ``TagSpecifications.N`` parameter of the `CreateVolume
    API <https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVolume.html>`_ in the *Amazon EC2 API Reference*.
    """
    roleArn: str
    """
    The ARN of the IAM role to associate with this volume.

    This is the Amazon ECS infrastructure IAM role that is used to
    manage your Amazon Web Services infrastructure. We recommend using the Amazon ECS-managed
    ``AmazonECSInfrastructureRolePolicyForVolumes`` IAM policy with this role. For more information, see `Amazon ECS
    infrastructure IAM role <https://docs.aws.amazon.com/AmazonECS/latest/developerguide/infrastructure_IAM_role.html>`_ in
    the *Amazon ECS Developer Guide*.
    """
    terminationPolicy: TaskManagedEBSVolumeTerminationPolicy | None = None
    """
    The termination policy for the volume when the task exits.

    This provides a way to control whether Amazon ECS terminates the Amazon EBS volume
    when the task stops.
    """
    filesystemType: Literal["ext3", "ext4", "xfs", "ntfs"] | None = None
    """
    The Linux filesystem type for the volume.

    For volumes created from a snapshot, you must specify the same filesystem type that
    the volume was using when the snapshot was created. If there is a filesystem type
    mismatch, the task will fail to start.
    """


class TaskVolumeConfiguration(Boto3Model):
    """
    Configuration settings for the task volume that was ``configuredAtLaunch`` that
    weren't set during ``RegisterTaskDef``.
    """

    name: str
    """
    The name of the volume.

    This value must match the volume name from the ``Volume`` object in the task definition.
    """
    managedEBSVolume: TaskManagedEBSVolumeConfiguration | None = None
    """
    The configuration for the Amazon EBS volume that Amazon ECS creates and manages on
    your behalf.

    These settings are used to create each Amazon EBS volume, with one volume created
    for each task. The Amazon EBS volumes are visible in your account in the Amazon EC2
    console once they are created.
    """


class RunTaskResponse(Boto3Model):
    tasks: List["Task"] | None = None
    """
    A full description of the tasks that were run.

    The tasks that were successfully placed on your cluster are described here.
    """
    failures: List["Failure"] | None = None
    """
    Any failures associated with the call.
    """


class StopTaskResponse(Boto3Model):
    task: Task | None = None
    """
    The task that was stopped.
    """


class DescribeServiceDeploymentsResponse(Boto3Model):
    serviceDeployments: List["ServiceDeployment"] | None = None
    """
    The list of service deployments described.
    """
    failures: List["Failure"] | None = None
    """
    Any failures associated with the call.
    """


class CreatedAt(Boto3Model):
    """
    The optional filter to narrow the ``ListServiceDeployment`` results.

    If you do not specify a value, service deployments that were created before the
    current time are included in the result.
    """

    before: datetime | None = None
    """
    Include service deployments in the result that were created before this time.

    The format is yyyy-MM-dd HH:mm:ss.SSSSSS.
    """
    after: datetime | None = None
    """
    Include service deployments in the result that were created after this time.

    The format is yyyy-MM-dd HH:mm:ss.SSSSSS.
    """


class ServiceDeploymentBrief(Boto3Model):
    """
    The service deployment properties that are retured when you call
    ``ListServiceDeployments``.

    This provides a high-level overview of the service deployment.
    """

    serviceDeploymentArn: str | None = None
    """
    The ARN of the service deployment.
    """
    serviceArn: str | None = None
    """
    The ARN of the service for this service deployment.
    """
    clusterArn: str | None = None
    """
    The ARN of the cluster that hosts the service.
    """
    startedAt: datetime | None = None
    """
    The time that the service deployment statred.

    The format is yyyy-MM-dd HH:mm:ss.SSSSSS.
    """
    createdAt: datetime | None = None
    """
    The time that the service deployment was created.

    The format is yyyy-MM-dd HH:mm:ss.SSSSSS.
    """
    finishedAt: datetime | None = None
    """
    The time that the service deployment completed.

    The format is yyyy-MM-dd HH:mm:ss.SSSSSS.
    """
    targetServiceRevisionArn: str | None = None
    """
    The ARN of the service revision being deplyed.
    """
    status: Literal["PENDING", "SUCCESSFUL", "STOPPED", "STOP_REQUESTED", "IN_PROGRESS", "ROLLBACK_REQUESTED", "ROLLBACK_IN_PROGRESS", "ROLLBACK_SUCCESSFUL", "ROLLBACK_FAILED"] | None = None
    """
    The status of the service deployment.
    """
    statusReason: str | None = None
    """
    Information about why the service deployment is in the current status.

    For example, the circuit breaker detected a deployment failure.
    """


class ListServiceDeploymentsResponse(Boto3Model):
    serviceDeployments: List["ServiceDeploymentBrief"] | None = None
    """
    An overview of the service deployment, including the following properties:
    """
    nextToken: str | None = None
    """
    The ``nextToken`` value to include in a future ``ListServiceDeployments`` request.

    When the results of a
    ``ListServiceDeployments`` request exceed ``maxResults``, this value can be used to retrieve the next page of results.
    This value is null when there are no more results to return.
    """


class StopServiceDeploymentResponse(Boto3Model):
    serviceDeploymentArn: str | None = None
    """
    The ARN of the stopped service deployment.
    """
