terraform-tofu-labs/2-simple-example/iac/modules/service/README.md
2024-04-15 16:31:58 +01:00

35 KiB

Amazon ECS Service Module

Configuration in this directory creates an Amazon ECS Service and associated resources.

Some notable configurations to be aware of when using this module:

  1. desired_count/scale is always ignored; the module is designed to utilize autoscaling by default (though it can be disabled)
  2. The default configuration is intended for FARGATE use

For more details see the design doc

Logging

Please refer to FireLens examples repository for logging configuration examples for FireLens on Amazon ECS and AWS Fargate.

Usage

module "ecs_service" {
  source = "terraform-aws-modules/ecs/aws//modules/service"

  name        = "example"
  cluster_arn = "arn:aws:ecs:us-west-2:123456789012:cluster/default"

  cpu    = 1024
  memory = 4096

  # Container definition(s)
  container_definitions = {

    fluent-bit = {
      cpu       = 512
      memory    = 1024
      essential = true
      image     = "906394416424.dkr.ecr.us-west-2.amazonaws.com/aws-for-fluent-bit:stable"
      firelens_configuration = {
        type = "fluentbit"
      }
      memory_reservation = 50
    }

    ecs-sample = {
      cpu       = 512
      memory    = 1024
      essential = true
      image     = "public.ecr.aws/aws-containers/ecsdemo-frontend:776fd50"
      port_mappings = [
        {
          name          = "ecs-sample"
          containerPort = 80
          protocol      = "tcp"
        }
      ]

      # Example image used requires access to write to root filesystem
      readonly_root_filesystem = false

      dependencies = [{
        containerName = "fluent-bit"
        condition     = "START"
      }]

      enable_cloudwatch_logging = false
      log_configuration = {
        logDriver = "awsfirelens"
        options = {
          Name                    = "firehose"
          region                  = "eu-west-1"
          delivery_stream         = "my-stream"
          log-driver-buffer-limit = "2097152"
        }
      }
      memory_reservation = 100
    }
  }

  service_connect_configuration = {
    namespace = "example"
    service = {
      client_alias = {
        port     = 80
        dns_name = "ecs-sample"
      }
      port_name      = "ecs-sample"
      discovery_name = "ecs-sample"
    }
  }

  load_balancer = {
    service = {
      target_group_arn = "arn:aws:elasticloadbalancing:eu-west-1:1234567890:targetgroup/bluegreentarget1/209a844cd01825a4"
      container_name   = "ecs-sample"
      container_port   = 80
    }
  }

  subnet_ids = ["subnet-abcde012", "subnet-bcde012a", "subnet-fghi345a"]
  security_group_rules = {
    alb_ingress_3000 = {
      type                     = "ingress"
      from_port                = 80
      to_port                  = 80
      protocol                 = "tcp"
      description              = "Service port"
      source_security_group_id = "sg-12345678"
    }
    egress_all = {
      type        = "egress"
      from_port   = 0
      to_port     = 0
      protocol    = "-1"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }

  tags = {
    Environment = "dev"
    Terraform   = "true"
  }
}

Conditional Creation

The following values are provided to toggle on/off creation of the associated resources as desired:

module "ecs_service" {
  source = "terraform-aws-modules/ecs/aws//modules/service"

  # Disable creation of service and all resources
  create = false

  # Enable ECS Exec
  enable_execute_command = true

  # Disable creation of the service IAM role; `iam_role_arn` should be provided
  create_iam_role = false

  # Disable creation of the task definition; `task_definition_arn` should be provided
  create_task_definition = false

  # Disable creation of the task execution IAM role; `task_exec_iam_role_arn` should be provided
  create_task_exec_iam_role = false

  # Disable creation of the task execution IAM role policy
  create_task_exec_policy = false

  # Disable creation of the tasks IAM role; `tasks_iam_role_arn` should be provided
  create_tasks_iam_role = false

  # Disable creation of the service security group
  create_security_group = false

  # ... omitted
}

Examples

Requirements

Name Version
terraform >= 1.0
aws >= 4.66.1

Providers

Name Version
aws >= 4.66.1

Modules

Name Source Version
container_definition ../container-definition n/a

Resources

Name Type
aws_appautoscaling_policy.this resource
aws_appautoscaling_scheduled_action.this resource
aws_appautoscaling_target.this resource
aws_ecs_service.ignore_task_definition resource
aws_ecs_service.this resource
aws_ecs_task_definition.this resource
aws_ecs_task_set.ignore_task_definition resource
aws_ecs_task_set.this resource
aws_iam_policy.service resource
aws_iam_policy.task_exec resource
aws_iam_role.service resource
aws_iam_role.task_exec resource
aws_iam_role.tasks resource
aws_iam_role_policy.tasks resource
aws_iam_role_policy_attachment.service resource
aws_iam_role_policy_attachment.task_exec resource
aws_iam_role_policy_attachment.task_exec_additional resource
aws_iam_role_policy_attachment.tasks resource
aws_security_group.this resource
aws_security_group_rule.this resource
aws_caller_identity.current data source
aws_ecs_task_definition.this data source
aws_iam_policy_document.service data source
aws_iam_policy_document.service_assume data source
aws_iam_policy_document.task_exec data source
aws_iam_policy_document.task_exec_assume data source
aws_iam_policy_document.tasks data source
aws_iam_policy_document.tasks_assume data source
aws_partition.current data source
aws_region.current data source
aws_subnet.this data source

Inputs

Name Description Type Default Required
alarms Information about the CloudWatch alarms any {} no
assign_public_ip Assign a public IP address to the ENI (Fargate launch type only) bool false no
autoscaling_max_capacity Maximum number of tasks to run in your service number 10 no
autoscaling_min_capacity Minimum number of tasks to run in your service number 1 no
autoscaling_policies Map of autoscaling policies to create for the service any
{
"cpu": {
"policy_type": "TargetTrackingScaling",
"target_tracking_scaling_policy_configuration": {
"predefined_metric_specification": {
"predefined_metric_type": "ECSServiceAverageCPUUtilization"
}
}
},
"memory": {
"policy_type": "TargetTrackingScaling",
"target_tracking_scaling_policy_configuration": {
"predefined_metric_specification": {
"predefined_metric_type": "ECSServiceAverageMemoryUtilization"
}
}
}
}
no
autoscaling_scheduled_actions Map of autoscaling scheduled actions to create for the service any {} no
capacity_provider_strategy Capacity provider strategies to use for the service. Can be one or more any {} no
cluster_arn ARN of the ECS cluster where the resources will be provisioned string "" no
container_definition_defaults A map of default values for container definitions created by container_definitions any {} no
container_definitions A map of valid container definitions. Please note that you should only provide values that are part of the container definition document any {} no
cpu Number of cpu units used by the task. If the requires_compatibilities is FARGATE this field is required number 1024 no
create Determines whether resources will be created (affects all resources) bool true no
create_iam_role Determines whether the ECS service IAM role should be created bool true no
create_security_group Determines if a security group is created bool true no
create_service Determines whether service resource will be created (set to false in case you want to create task definition only) bool true no
create_task_definition Determines whether to create a task definition or use existing/provided bool true no
create_task_exec_iam_role Determines whether the ECS task definition IAM role should be created bool true no
create_task_exec_policy Determines whether the ECS task definition IAM policy should be created. This includes permissions included in AmazonECSTaskExecutionRolePolicy as well as access to secrets and SSM parameters bool true no
create_tasks_iam_role Determines whether the ECS tasks IAM role should be created bool true no
deployment_circuit_breaker Configuration block for deployment circuit breaker any {} no
deployment_controller Configuration block for deployment controller configuration any {} no
deployment_maximum_percent Upper limit (as a percentage of the service's desired_count) of the number of running tasks that can be running in a service during a deployment number 200 no
deployment_minimum_healthy_percent Lower limit (as a percentage of the service's desired_count) of the number of running tasks that must remain running and healthy in a service during a deployment number 66 no
desired_count Number of instances of the task definition to place and keep running number 1 no
enable_autoscaling Determines whether to enable autoscaling for the service bool true no
enable_ecs_managed_tags Specifies whether to enable Amazon ECS managed tags for the tasks within the service bool true no
enable_execute_command Specifies whether to enable Amazon ECS Exec for the tasks within the service bool false no
ephemeral_storage 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 AWS Fargate any {} no
external_id The external ID associated with the task set string null no
family A unique name for your task definition string null no
force_delete Whether to allow deleting the task set without waiting for scaling down to 0 bool null no
force_new_deployment Enable to force a new task deployment of the service. This can be used to update tasks to use a newer Docker image with same image/tag combination, roll Fargate tasks onto a newer platform version, or immediately deploy ordered_placement_strategy and placement_constraints updates bool true no
health_check_grace_period_seconds Seconds to ignore failing load balancer health checks on newly instantiated tasks to prevent premature shutdown, up to 2147483647. Only valid for services configured to use load balancers number null no
iam_role_arn Existing IAM role ARN string null no
iam_role_description Description of the role string null no
iam_role_name Name to use on IAM role created string null no
iam_role_path IAM role path string null no
iam_role_permissions_boundary ARN of the policy that is used to set the permissions boundary for the IAM role string null no
iam_role_statements A map of IAM policy statements for custom permission usage any {} no
iam_role_tags A map of additional tags to add to the IAM role created map(string) {} no
iam_role_use_name_prefix Determines whether the IAM role name (iam_role_name) is used as a prefix bool true no
ignore_task_definition_changes Whether changes to service task_definition changes should be ignored bool false no
inference_accelerator Configuration block(s) with Inference Accelerators settings any {} no
ipc_mode IPC resource namespace to be used for the containers in the task The valid values are host, task, and none string null no
launch_type Launch type on which to run your service. The valid values are EC2, FARGATE, and EXTERNAL. Defaults to FARGATE string "FARGATE" no
load_balancer Configuration block for load balancers any {} no
memory Amount (in MiB) of memory used by the task. If the requires_compatibilities is FARGATE this field is required number 2048 no
name Name of the service (up to 255 letters, numbers, hyphens, and underscores) string null no
network_mode Docker networking mode to use for the containers in the task. Valid values are none, bridge, awsvpc, and host string "awsvpc" no
ordered_placement_strategy Service level strategy rules that are taken into consideration during task placement. List from top to bottom in order of precedence any {} no
pid_mode Process namespace to use for the containers in the task. The valid values are host and task string null no
placement_constraints Configuration block for rules that are taken into consideration during task placement (up to max of 10). This is set at the service, see task_definition_placement_constraints for setting at the task definition any {} no
platform_version Platform version on which to run your service. Only applicable for launch_type set to FARGATE. Defaults to LATEST string null no
propagate_tags Specifies whether to propagate the tags from the task definition or the service to the tasks. The valid values are SERVICE and TASK_DEFINITION string null no
proxy_configuration Configuration block for the App Mesh proxy any {} no
requires_compatibilities Set of launch types required by the task. The valid values are EC2 and FARGATE list(string)
[
"FARGATE"
]
no
runtime_platform Configuration block for runtime_platform that containers in your task may use any
{
"cpu_architecture": "X86_64",
"operating_system_family": "LINUX"
}
no
scale A floating-point percentage of the desired number of tasks to place and keep running in the task set any {} no
scheduling_strategy Scheduling strategy to use for the service. The valid values are REPLICA and DAEMON. Defaults to REPLICA string null no
security_group_description Description of the security group created string null no
security_group_ids List of security groups to associate with the task or service list(string) [] no
security_group_name Name to use on security group created string null no
security_group_rules Security group rules to add to the security group created any {} no
security_group_tags A map of additional tags to add to the security group created map(string) {} no
security_group_use_name_prefix Determines whether the security group name (security_group_name) is used as a prefix bool true no
service_connect_configuration The ECS Service Connect configuration for this service to discover and connect to services, and be discovered by, and connected from, other services within a namespace any {} no
service_registries Service discovery registries for the service any {} no
service_tags A map of additional tags to add to the service map(string) {} no
skip_destroy If true, the task is not deleted when the service is deleted bool null no
subnet_ids List of subnets to associate with the task or service list(string) [] no
tags A map of tags to add to all resources map(string) {} no
task_definition_arn Existing task definition ARN. Required when create_task_definition is false string null no
task_definition_placement_constraints Configuration block for rules that are taken into consideration during task placement (up to max of 10). This is set at the task definition, see placement_constraints for setting at the service any {} no
task_exec_iam_role_arn Existing IAM role ARN string null no
task_exec_iam_role_description Description of the role string null no
task_exec_iam_role_max_session_duration Maximum session duration (in seconds) for ECS task execution role. Default is 3600. number null no
task_exec_iam_role_name Name to use on IAM role created string null no
task_exec_iam_role_path IAM role path string null no
task_exec_iam_role_permissions_boundary ARN of the policy that is used to set the permissions boundary for the IAM role string null no
task_exec_iam_role_policies Map of IAM role policy ARNs to attach to the IAM role map(string) {} no
task_exec_iam_role_tags A map of additional tags to add to the IAM role created map(string) {} no
task_exec_iam_role_use_name_prefix Determines whether the IAM role name (task_exec_iam_role_name) is used as a prefix bool true no
task_exec_iam_statements A map of IAM policy statements for custom permission usage any {} no
task_exec_secret_arns List of SecretsManager secret ARNs the task execution role will be permitted to get/read list(string)
[
"arn:aws:secretsmanager:::secret:*"
]
no
task_exec_ssm_param_arns List of SSM parameter ARNs the task execution role will be permitted to get/read list(string)
[
"arn:aws:ssm:::parameter/*"
]
no
task_tags A map of additional tags to add to the task definition/set created map(string) {} no
tasks_iam_role_arn Existing IAM role ARN string null no
tasks_iam_role_description Description of the role string null no
tasks_iam_role_name Name to use on IAM role created string null no
tasks_iam_role_path IAM role path string null no
tasks_iam_role_permissions_boundary ARN of the policy that is used to set the permissions boundary for the IAM role string null no
tasks_iam_role_policies Map of IAM role policy ARNs to attach to the IAM role map(string) {} no
tasks_iam_role_statements A map of IAM policy statements for custom permission usage any {} no
tasks_iam_role_tags A map of additional tags to add to the IAM role created map(string) {} no
tasks_iam_role_use_name_prefix Determines whether the IAM role name (tasks_iam_role_name) is used as a prefix bool true no
timeouts Create, update, and delete timeout configurations for the service map(string) {} no
triggers Map of arbitrary keys and values that, when changed, will trigger an in-place update (redeployment). Useful with timestamp() any {} no
volume Configuration block for volumes that containers in your task may use any {} no
wait_for_steady_state If true, Terraform will wait for the service to reach a steady state before continuing. Default is false bool null no
wait_until_stable Whether terraform should wait until the task set has reached STEADY_STATE bool null no
wait_until_stable_timeout Wait timeout for task set to reach STEADY_STATE. Valid time units include ns, us (or µs), ms, s, m, and h. Default 10m string null no

Outputs

Name Description
autoscaling_policies Map of autoscaling policies and their attributes
autoscaling_scheduled_actions Map of autoscaling scheduled actions and their attributes
container_definitions Container definitions
iam_role_arn Service IAM role ARN
iam_role_name Service IAM role name
iam_role_unique_id Stable and unique string identifying the service IAM role
id ARN that identifies the service
name Name of the service
security_group_arn Amazon Resource Name (ARN) of the security group
security_group_id ID of the security group
task_definition_arn Full ARN of the Task Definition (including both family and revision)
task_definition_family The unique name of the task definition
task_definition_family_revision The family and revision (family:revision) of the task definition
task_definition_revision Revision of the task in a particular family
task_exec_iam_role_arn Task execution IAM role ARN
task_exec_iam_role_name Task execution IAM role name
task_exec_iam_role_unique_id Stable and unique string identifying the task execution IAM role
task_set_arn The Amazon Resource Name (ARN) that identifies the task set
task_set_id The ID of the task set
task_set_stability_status The stability status. This indicates whether the task set has reached a steady state
task_set_status The status of the task set
tasks_iam_role_arn Tasks IAM role ARN
tasks_iam_role_name Tasks IAM role name
tasks_iam_role_unique_id Stable and unique string identifying the tasks IAM role

License

Apache-2.0 Licensed. See LICENSE.