Skip to content

yariksheptykin/terraform-aws-ecs-alb-service-task

 
 

Repository files navigation

terraform-aws-ecs-alb-service-task Latest Release Slack Community

README Header

Cloud Posse

Terraform module to create an ECS Service for a web app (task), and an ALB target group to route requests.


This project is part of our comprehensive "SweetOps" approach towards DevOps.

Terraform Open Source Modules

It's 100% Open Source and licensed under the APACHE2.

We literally have hundreds of terraform modules that are Open Source and well-maintained. Check them out!

Usage

IMPORTANT: The master branch is used in source just as an example. In your code, do not pin to master because there may be breaking changes between releases. Instead pin to the release tag (e.g. ?ref=tags/x.y.z) of one of our latest releases.

For a complete example, see examples/complete.

For automated test of the complete example using bats and Terratest, see test.

  provider "aws" {
    region = var.region
  }

  module "label" {
    source     = "git::https://github.com/cloudposse/terraform-null-label.git?ref=tags/0.15.0"
    namespace  = var.namespace
    name       = var.name
    stage      = var.stage
    delimiter  = var.delimiter
    attributes = var.attributes
    tags       = var.tags
  }

  module "vpc" {
    source     = "git::https://github.com/cloudposse/terraform-aws-vpc.git?ref=tags/0.8.1"
    namespace  = var.namespace
    stage      = var.stage
    name       = var.name
    delimiter  = var.delimiter
    attributes = var.attributes
    cidr_block = var.vpc_cidr_block
    tags       = var.tags
  }

  module "subnets" {
    source               = "git::https://github.com/cloudposse/terraform-aws-dynamic-subnets.git?ref=tags/0.16.1"
    availability_zones   = var.availability_zones
    namespace            = var.namespace
    stage                = var.stage
    name                 = var.name
    attributes           = var.attributes
    delimiter            = var.delimiter
    vpc_id               = module.vpc.vpc_id
    igw_id               = module.vpc.igw_id
    cidr_block           = module.vpc.vpc_cidr_block
    nat_gateway_enabled  = true
    nat_instance_enabled = false
    tags                 = var.tags
  }

  resource "aws_ecs_cluster" "default" {
    name = module.label.id
    tags = module.label.tags
  }

  module "container_definition" {
    source                       = "git::https://github.com/cloudposse/terraform-aws-ecs-container-definition.git?ref=tags/0.21.0"
    container_name               = var.container_name
    container_image              = var.container_image
    container_memory             = var.container_memory
    container_memory_reservation = var.container_memory_reservation
    container_cpu                = var.container_cpu
    essential                    = var.container_essential
    readonly_root_filesystem     = var.container_readonly_root_filesystem
    environment                  = var.container_environment
    port_mappings                = var.container_port_mappings
    log_configuration            = var.container_log_configuration
  }

  module "ecs_alb_service_task" {
    source                             = "git::https://github.com/cloudposse/terraform-aws-ecs-alb-service-task.git?ref=master"
    namespace                          = var.namespace
    stage                              = var.stage
    name                               = var.name
    attributes                         = var.attributes
    delimiter                          = var.delimiter
    alb_security_group                 = module.vpc.vpc_default_security_group_id
    container_definition_json          = module.container_definition.json
    ecs_cluster_arn                    = aws_ecs_cluster.default.arn
    launch_type                        = var.ecs_launch_type
    vpc_id                             = module.vpc.vpc_id
    security_group_ids                 = [module.vpc.vpc_default_security_group_id]
    subnet_ids                         = module.subnets.public_subnet_ids
    tags                               = var.tags
    ignore_changes_task_definition     = var.ignore_changes_task_definition
    network_mode                       = var.network_mode
    assign_public_ip                   = var.assign_public_ip
    propagate_tags                     = var.propagate_tags
    health_check_grace_period_seconds  = var.health_check_grace_period_seconds
    deployment_minimum_healthy_percent = var.deployment_minimum_healthy_percent
    deployment_maximum_percent         = var.deployment_maximum_percent
    deployment_controller_type         = var.deployment_controller_type
    desired_count                      = var.desired_count
    task_memory                        = var.task_memory
    task_cpu                           = var.task_cpu
  }

The container_image in the container_definition module is the Docker image used to start a container.

This string is passed directly to the Docker daemon. Images in the Docker Hub registry are available by default. Other repositories are specified with either repository-url/image:tag or repository-url/image@digest. Up to 255 letters (uppercase and lowercase), numbers, hyphens, underscores, colons, periods, forward slashes, and number signs are allowed. This parameter maps to Image in the Create a container section of the Docker Remote API and the IMAGE parameter of docker run.

When a new task starts, the Amazon ECS container agent pulls the latest version of the specified image and tag for the container to use. However, subsequent updates to a repository image are not propagated to already running tasks.

Images in Amazon ECR repositories can be specified by either using the full registry/repository:tag or registry/repository@digest. For example, 012345678910.dkr.ecr.<region-name>.amazonaws.com/<repository-name>:latest or 012345678910.dkr.ecr.<region-name>.amazonaws.com/<repository-name>@sha256:94afd1f2e64d908bc90dbca0035a5b567EXAMPLE.

Images in official repositories on Docker Hub use a single name (for example, ubuntu or mongo).

Images in other repositories on Docker Hub are qualified with an organization name (for example, amazon/amazon-ecs-agent).

Images in other online repositories are qualified further by a domain name (for example, quay.io/assemblyline/ubuntu).

For more info, see Container Definition.

Makefile Targets

Available targets:

  help                                Help screen
  help/all                            Display help for all targets
  help/short                          This help short screen

Requirements

Name Version
terraform ~> 0.12.0
aws ~> 2.42
local ~> 1.3
null ~> 2.0
template ~> 2.0

Providers

Name Version
aws ~> 2.42

Inputs

Name Description Type Default Required
alb_security_group Security group of the ALB string "" no
assign_public_ip Assign a public IP address to the ENI (Fargate launch type only). Valid values are true or false. Default false bool false no
attributes Additional attributes (_e.g._ "1") list(string) [] no
capacity_provider_strategies The capacity provider strategies to use for the service. See capacity_provider_strategy configuration block: https://www.terraform.io/docs/providers/aws/r/ecs_service.html#capacity_provider_strategy
list(object({
capacity_provider = string
weight = number
base = number
}))
[] no
container_definition_json The JSON of the task container definition string n/a yes
container_port The port on the container to allow via the ingress security group number 80 no
delimiter Delimiter between namespace, stage, name and attributes string "-" no
deployment_controller_type Type of deployment controller. Valid values are CODE_DEPLOY and ECS string "ECS" no
deployment_maximum_percent The upper limit of the number of tasks (as a percentage of desired_count) that can be running in a service during a deployment number 200 no
deployment_minimum_healthy_percent The lower limit (as a percentage of desired_count) of the number of tasks that must remain running and healthy in a service during a deployment number 100 no
desired_count The number of instances of the task definition to place and keep running number 1 no
ecs_cluster_arn The ARN of the ECS cluster where service will be provisioned string n/a yes
ecs_load_balancers A list of load balancer config objects for the ECS service; see load_balancer docs https://www.terraform.io/docs/providers/aws/r/ecs_service.html
list(object({
container_name = string
container_port = number
elb_name = string
target_group_arn = string
}))
[] no
enable_ecs_managed_tags Specifies whether to enable Amazon ECS managed tags for the tasks within the service bool false no
enable_icmp_rule Specifies whether to enable ICMP on the security group bool true no
enabled Set to false to prevent the module from creating any resources bool true no
environment Environment, e.g. 'prod', 'staging', 'dev', 'pre-prod', 'UAT' string "" no
health_check_grace_period_seconds Seconds to ignore failing load balancer health checks on newly instantiated tasks to prevent premature shutdown, up to 7200. Only valid for services configured to use load balancers number 0 no
ignore_changes_task_definition Whether to ignore changes in container definition and task definition in the ECS service bool true no
launch_type The launch type on which to run your service. Valid values are EC2 and FARGATE string "FARGATE" no
name Name of the application string n/a yes
namespace Namespace (e.g. eg or cp) string "" no
network_mode The network mode to use for the task. This is required to be awsvpc for FARGATE launch_type string "awsvpc" no
nlb_cidr_blocks A list of CIDR blocks to add to the ingress rule for the NLB container port list(string) [] no
nlb_container_port The port on the container to allow via the ingress security group number 80 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. The maximum number of ordered_placement_strategy blocks is 5. See ordered_placement_strategy docs https://www.terraform.io/docs/providers/aws/r/ecs_service.html#ordered_placement_strategy-1
list(object({
type = string
field = string
}))
[] no
permissions_boundary A permissions boundary ARN to apply to the 3 roles that are created. string "" no
platform_version The platform version on which to run your service. Only applicable for launch_type set to FARGATE. More information about Fargate platform versions can be found in the AWS ECS User Guide. string "LATEST" 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 The proxy configuration details for the App Mesh proxy. See proxy_configuration docs https://www.terraform.io/docs/providers/aws/r/ecs_task_definition.html#proxy-configuration-arguments
object({
type = string
container_name = string
properties = map(string)
})
null no
scheduling_strategy The scheduling strategy to use for the service. The valid values are REPLICA and DAEMON. Note that Fargate tasks do not support the DAEMON scheduling strategy. string "REPLICA" no
security_group_ids Security group IDs to allow in Service network_configuration list(string) [] no
service_placement_constraints The rules that are taken into consideration during task placement. Maximum number of placement_constraints is 10. See placement_constraints docs https://www.terraform.io/docs/providers/aws/r/ecs_service.html#placement_constraints-1
list(object({
type = string
expression = string
}))
[] no
service_registries The service discovery registries for the service. The maximum number of service_registries blocks is 1. The currently supported service registry is Amazon Route 53 Auto Naming Service - aws_service_discovery_service; see service_registries docs https://www.terraform.io/docs/providers/aws/r/ecs_service.html#service_registries-1
list(object({
registry_arn = string
port = number
container_name = string
container_port = number
}))
[] no
stage Stage (e.g. prod, dev, staging) string "" no
subnet_ids Subnet IDs list(string) n/a yes
tags Additional tags (_e.g._ { BusinessUnit : ABC }) map(string) {} no
task_cpu The number of CPU units used by the task. If using FARGATE launch type task_cpu must match supported memory values (https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#task_size) number 256 no
task_exec_role_arn The ARN of IAM role that allows the ECS/Fargate agent to make calls to the ECS API on your behalf string "" no
task_memory The amount of memory (in MiB) used by the task. If using Fargate launch type task_memory must match supported cpu value (https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#task_size) number 512 no
task_placement_constraints A set of placement constraints rules that are taken into consideration during task placement. Maximum number of placement_constraints is 10. See placement_constraints docs https://www.terraform.io/docs/providers/aws/r/ecs_task_definition.html#placement-constraints-arguments
list(object({
type = string
expression = string
}))
[] no
task_role_arn The ARN of IAM role that allows your Amazon ECS container task to make calls to other AWS services string "" no
use_alb_security_group A flag to enable/disable adding the ingress rule to the ALB security group bool false no
use_nlb_cidr_blocks A flag to enable/disable adding the NLB ingress rule to the security group bool false no
use_old_arn A flag to enable/disable tagging the ecs resources that require the new arn format bool false no
volumes Task volume definitions as list of configuration objects
list(object({
host_path = string
name = string
docker_volume_configuration = list(object({
autoprovision = bool
driver = string
driver_opts = map(string)
labels = map(string)
scope = string
}))
efs_volume_configuration = list(object({
file_system_id = string
root_directory = string
transit_encryption = string
transit_encryption_port = string
authorization_config = list(object({
access_point_id = string
iam = string
}))
}))
}))
[] no
vpc_id The VPC ID where resources are created string n/a yes

Outputs

Name Description
ecs_exec_role_policy_id The ECS service role policy ID, in the form of role_name:role_policy_name
ecs_exec_role_policy_name ECS service role name
service_name ECS Service name
service_role_arn ECS Service role ARN
service_security_group_id Security Group ID of the ECS task
task_definition_family ECS task definition family
task_definition_revision ECS task definition revision
task_exec_role_arn ECS Task exec role ARN
task_exec_role_name ECS Task role name
task_role_arn ECS Task role ARN
task_role_id ECS Task role id
task_role_name ECS Task role name

Share the Love

Like this project? Please give it a ★ on our GitHub! (it helps us a lot)

Are you using this project or any of our other projects? Consider leaving a testimonial. =)

Related Projects

Check out these related projects.

Help

Got a question? We got answers.

File a GitHub issue, send us an email or join our Slack Community.

README Commercial Support

DevOps Accelerator for Startups

We are a DevOps Accelerator. We'll help you build your cloud infrastructure from the ground up so you can own it. Then we'll show you how to operate it and stick around for as long as you need us.

Learn More

Work directly with our team of DevOps experts via email, slack, and video conferencing.

We deliver 10x the value for a fraction of the cost of a full-time engineer. Our track record is not even funny. If you want things done right and you need it done FAST, then we're your best bet.

  • Reference Architecture. You'll get everything you need from the ground up built using 100% infrastructure as code.
  • Release Engineering. You'll have end-to-end CI/CD with unlimited staging environments.
  • Site Reliability Engineering. You'll have total visibility into your apps and microservices.
  • Security Baseline. You'll have built-in governance with accountability and audit logs for all changes.
  • GitOps. You'll be able to operate your infrastructure via Pull Requests.
  • Training. You'll receive hands-on training so your team can operate what we build.
  • Questions. You'll have a direct line of communication between our teams via a Shared Slack channel.
  • Troubleshooting. You'll get help to triage when things aren't working.
  • Code Reviews. You'll receive constructive feedback on Pull Requests.
  • Bug Fixes. We'll rapidly work with you to fix any bugs in our projects.

Slack Community

Join our Open Source Community on Slack. It's FREE for everyone! Our "SweetOps" community is where you get to talk with others who share a similar vision for how to rollout and manage infrastructure. This is the best place to talk shop, ask questions, solicit feedback, and work together as a community to build totally sweet infrastructure.

Discourse Forums

Participate in our Discourse Forums. Here you'll find answers to commonly asked questions. Most questions will be related to the enormous number of projects we support on our GitHub. Come here to collaborate on answers, find solutions, and get ideas about the products and services we value. It only takes a minute to get started! Just sign in with SSO using your GitHub account.

Newsletter

Sign up for our newsletter that covers everything on our technology radar. Receive updates on what we're up to on GitHub as well as awesome new projects we discover.

Office Hours

Join us every Wednesday via Zoom for our weekly "Lunch & Learn" sessions. It's FREE for everyone!

zoom

Contributing

Bug Reports & Feature Requests

Please use the issue tracker to report any bugs or file feature requests.

Developing

If you are interested in being a contributor and want to get involved in developing this project or help out with our other projects, we would love to hear from you! Shoot us an email.

In general, PRs are welcome. We follow the typical "fork-and-pull" Git workflow.

  1. Fork the repo on GitHub
  2. Clone the project to your own machine
  3. Commit changes to your own branch
  4. Push your work back up to your fork
  5. Submit a Pull Request so that we can review your changes

NOTE: Be sure to merge the latest changes from "upstream" before making a pull request!

Copyright

Copyright © 2017-2020 Cloud Posse, LLC

License

License

See LICENSE for full details.

Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.

Trademarks

All other trademarks referenced herein are the property of their respective owners.

About

This project is maintained and funded by Cloud Posse, LLC. Like it? Please let us know by leaving a testimonial!

Cloud Posse

We're a DevOps Professional Services company based in Los Angeles, CA. We ❤️ Open Source Software.

We offer paid support on all of our projects.

Check out our other projects, follow us on twitter, apply for a job, or hire us to help with your cloud strategy and implementation.

Contributors

Erik Osterman
Erik Osterman
Igor Rodionov
Igor Rodionov
Andriy Knysh
Andriy Knysh
Sarkis Varozian
Sarkis Varozian
Chris Weyl
Chris Weyl

README Footer Beacon

About

Terraform module which implements an ECS service which exposes a web service via ALB.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • HCL 79.2%
  • Go 13.5%
  • Makefile 7.3%