How To Create An ECS Task Definition Using AWS CLI
Hello Everyone
Welcome to CloudAffaire and this is Debjeet.
In the last AWS blog post, we have discussed the ECS Cluster and created our 1st ECS Cluster using AWS CLI.
https://cloudaffaire.com/how-to-create-an-ecs-cluster-using-aws-cli/
In this blog post, we will discuss Task Definition in ECS. We will also create an ECS Task Definition using AWS CLI.
What is Task Definition in ECS?
A task definition is required to run Docker containers in Amazon ECS. You can define multiple containers in a task definition. The parameters that you use depend on the launch type you choose for the task. Not all parameters are valid for a specific case. Your entire application stack does not need to exist on a single task definition and in most cases it should not. Your application can span multiple task definitions by combining related containers into their own task definitions each representing a single component.
Task Definition Parameters:
Task definitions are split into separate parts: the task family the IAM task role the network mode container definitions volumes task placement constraints and launch types. The family and container definitions are required in a task definition while task role network mode volumes task placement constraints and launch type are optional. Below is the list of all available ECS task definition parameters:
- family: Name of your task definition specified with a revision number that starts with 1
- taskRoleArn: Allows the containers in the task permission to call the AWS APIs
- executionRoleArn: Allows the containers in the task to pull container images and publish container logs to CloudWatch
- networkMode: Docker networking mode to use for the containers in the task Valid Values: none | bridge | awsvpc | host
- containerDefinitions: A list of container definitions that are passed to the Docker daemon on a container instance
- name: The name of a container
- image: The image used to start a container
- repositoryCredentials: The repository credentials for private registry authentication
- credentialsParameter: The ARN of the secret containing the private repository credentials
- cpu: CPU allocated to the container
- memory: The amount (in MiB) of memory to present to the container
- memoryReservation: The soft limit (in MiB) of memory to reserve for the container
- links: Allows containers to communicate with each other without the need for port mappings
- portMappings: Allow containers to access ports on the host container instance to send or receive traffic
- containerPort: The port number on the container that is bound to the userspecified or automatically assigned host port
- hostPort: The port number on the container instance to reserve for your container
- protocol: The protocol used for the port mapping. Valid values are tcp and udp
- essential: When true, all the container part of the task will be stopped if this container fails or stop
- entryPoint: Allows you to configure a container that will run as an executable
- command: The command that is passed to the container
- environment: The environment variables to pass to a container
- name: The name of the environment variable
- value: The value of the environment variable
- mountPoints: The mount points for data volumes in your container
- sourceVolume: The name of the volume to mount
- containerPath: The path on the container to mount the volume at
- readOnly: When true the container has readonly access to the volume
- volumesFrom: Data volumes to mount from another container
- sourceContainer: The name of the container to mount volumes from
- readOnly: When true the container has readonly access to the volume
- linuxParameters: Linuxspecific options that are applied to the container such as KernelCapabilities
- capabilities: The Linux capabilities for the container that are added to or dropped from the default configuration provided by Docker
- add: The Linux capabilities for the container to add to the default configuration provided by Docker
- drop: The Linux capabilities for the container to remove from the default configuration provided by Docker
- devices: Any host devices to expose to the container
- hostPath: The path for the device on the host container instance
- containerPath: The path inside the container at which to expose the host device
- permissions: The explicit permissions to provide to the container for the device Valid Values: read | write | mknod
- initProcessEnabled: if true Run an init process inside the container that forwards signals and reaps processes
- sharedMemorySize: The value for the size (in MiB) of the /dev/shm volume
- tmpfs: The container path mount options and size (in MiB) of the tmpfs mount
- containerPath: The absolute file path where the tmpfs volume is to be mounted
- size: The size (in MiB) of the tmpfs volume
- mountOptions: The list of tmpfs volume mount options
- maxSwap: The total amount of swap memory (in MiB) a container can use
- swappiness: This allows you to tune a container’s memory swappiness behavior Valid Range: 0 to 100
- capabilities: The Linux capabilities for the container that are added to or dropped from the default configuration provided by Docker
- secrets: An object representing the secret to expose to your container
- name: The value to set as the environment variable on the containe
- valueFrom: The secret to expose to the container Valid Values: ARN of AWS Secrets Manager or Systems Manager Parameter Store
- dependsOn: The dependencies defined for container startup and shutdown
- containerName: The container name that must meet the specified condition
- condition: The dependency condition of the container Valid Values: START | COMPLETE | SUCCESS | HEALTHY
- startTimeout: Time duration (in seconds) to wait before giving up on resolving dependencies for a container
- stopTimeout: Time duration (in seconds) to wait before the container is forcefully killed if it doesn’t exit normally on its own
- hostname: The hostname to use for your container
- user: The user name to use inside the container
- workingDirectory: The working directory in which to run commands inside the container
- disableNetworking: When true networking is disabled within the container
- privileged: When true the container is given elevated privileges on the host container instance (similar to the root user)
- readonlyRootFilesystem: When true the container is given readonly access to its root file system
- dnsServers: A list of DNS servers that are presented to the container
- dnsSearchDomains: A list of DNS search domains that are presented to the container
- extraHosts: A list of hostnames and IP address mappings to append to the /etc/hosts file on the containe
- hostname: The hostname to use in the /etc/hosts entry
- ipAddress: The IP address to use in the /etc/hosts entry
- dockerSecurityOptions: A list of strings to provide custom labels for SELinux and AppArmor multilevel security systems not valid for Fargate launch type
- interactive: When true allows you to deploy containerized applications that require stdin or a tty to be allocated
- pseudoTerminal: When true a TTY is allocated
- dockerLabels: A key/value map of labels to add to the container
- KeyName: KeyValue
- ulimits: A list of ulimits to set in the container
- name: The type of the ulimit Valid Values: core | cpu | data | fsize | locks etc.
- softLimit: The soft limit for the ulimit type
- hardLimit: The hard limit for the ulimit type
- logConfiguration: The log configuration specification for the container
- logDriver: The log driver to use for the container Valid Values: awslogs | journald | splunk | syslog etc.
- options: The configuration options to send to the log driver
- KeyName: KeyValue
- secretOptions: An object representing the secret to pass to the log configuration
- name: The value to set as the environment variable on the container
- valueFrom: The secret to expose to the log configuration of the container
- healthCheck: The health check command and associated configuration parameters for the container
- command: A string array representing the command that the container runs to determine if it is healthy
- interval: The time period in seconds between each health check execution
- timeout: The time period in seconds to wait for a health check to succeed before it is considered a failure
- retries: The number of times to retry a failed health check before the container is considered unhealthy
- startPeriod: Grace period within which to provide containers time to bootstrap before failed health checks count towards the maximum number of retries
- systemControls: A list of namespaced kernel parameters to set in the container
- namespace: The namespaced kernel parameter to set a value for
- value: The value for the namespaced kernel parameter specifed in namespace
- resourceRequirements: The type and amount of a resource to assign to a container
- value: The value for the specified resource type
- type: The type of resource to assign to a container. The supported values are GPU or InferenceAccelerator
- firelensConfiguration: The FireLens configuration for the container
- type: The log router to use. The valid values are fluentd or fluentbit
- options: The options to use when configuring the log router
- KeyName: KeyValue
- volumes: A list of volumes to be passed to the Docker daemon on a container instance
- name: The name of the volume
- host: This parameter is specified when using bind mounts
- sourcePath: To declare the path on the host container instance that is presented to the container
- dockerVolumeConfiguration: This parameter is specified when using Docker volumes. Docker volumes are only supported when using the EC2 launch type
- scope: The scope for the Docker volume which determines its lifecycle Valid Values: task | shared
- autoprovision: When true the Docker volume is created if it does not already exist
- driver: The Docker volume driver to use
- driverOpts: A map of Docker driver specific options to pass through
- KeyName: KeyValue
- labels: Custom metadata to add to your Docker volume
- KeyName: KeyValue
- placementConstraints: An object representing a constraint on task placement
- type: The type of constraint Valid Values: distinctInstance | memberOf
- expression: A cluster query language expression to apply to the constraint
- requiresCompatibilities: The launch type the task is using Valid Values: EC2 | FARGATE
- cpu: The hard limit of CPU units to present for the task
- memory: The hard limit of memory (in MiB) to present to the task
- tags: The metadata that you apply to a resource to help you categorize and organize them
- key: One part of a keyvalue pair that make up a tag
- value: The optional part of a keyvalue pair that make up a tag
- pidMode: The process namespace to use for the containers in the task Valid Values: host | task
- ipcMode: The IPC resource namespace to use for the containers in the task Valid Values: host | task | none
- proxyConfiguration: The configuration details for the App Mesh proxy
- type: The proxy type. The only supported value is APPMESH
- containerName: The name of the container that will serve as the App Mesh proxy
- properties: The set of network configuration parameters to provide the Container Network Interface (CNI) plugin specified as keyvalue pairs
- name: The name of the key-value pair
- value: The value of the key-value pair
How To Create ECS Task Definition Using AWS CLI:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
################################################# ## Create An ECS Task Definition Using AWS CLI ## ################################################# ## Prerequisite: AWS CLI installed and configured with proper access ## https://cloudaffaire.com/category/aws/aws-cli/ ## Get task definition file template for reference ## Will list all available parameters in task definition aws ecs register-task-definition \ --generate-cli-skeleton ## Create a task definition file vi mytaskdefinition.json ----------------------- { "family": "mytaskdefinition", "networkMode": "awsvpc", "containerDefinitions": [{ "name": "myappv1", "image": "httpd:2.4", "portMappings": [{ "containerPort": 80, "hostPort": 80, "protocol": "tcp" }], "essential": true, "entryPoint": [ "sh", "-c" ], "command": [ "/bin/sh -c \"echo 'hello from ecs fargate cluster' > /usr/local/apache2/htdocs/index.html && httpd-foreground\"" ] }], "requiresCompatibilities": [ "FARGATE" ], "cpu": "256", "memory": "512" } ----------------------- :wq ## Register the task definition aws ecs register-task-definition \ --cli-input-json file://mytaskdefinition.json ## Get current list of task definitions aws ecs list-task-definitions ## Get the list of active task definition families aws ecs list-task-definition-families \ --status ACTIVE ## Get details of the task definition aws ecs describe-task-definition \ --task-definition mytaskdefinition ## Observe "revision": 1, when you create the task definition for the 1st time, aws assigns ## revision 1 to your task definition. This revision will be incremented by one every time you ## update the same task definition ## Update the mytaskdefinition.json file and change name to myappv2 from myappv1 ## Register the task definition with update aws ecs register-task-definition \ --cli-input-json file://mytaskdefinition.json ## Get details of the task definition aws ecs describe-task-definition \ --task-definition mytaskdefinition:1 #for 1st revision (name: myappv1) aws ecs describe-task-definition \ --task-definition mytaskdefinition:2 #for 2nd revision (name: myappv2) ## Deregister the task definitions aws ecs deregister-task-definition \ --task-definition mytaskdefinition:1 && aws ecs deregister-task-definition \ --task-definition mytaskdefinition:2 |
Hope you have enjoyed this article, In the next blog post, we will create an ECS cluster with EC2 launch type.
All the public cloud providers are changing the console user interface rapidly and due to this some of the screenshots used in our previous AWS blogs are no longer relevant. Hence, we have decided that from now onwards most of the demo will be done programmatically. Let us know your feedback on this in the comment section.
To get more details on AWS ECS, please refer below AWS documentation
https://docs.aws.amazon.com/ecs/index.html