Module: ecs-codepipeline
Terraform Module for CI/CD with AWS Code Pipeline using GitHub webhook triggers and Code Build for ECS.
Usage
For a complete example, see examples/complete.
For automated tests of the complete example using bats
and Terratest
, see test.
Trigger on GitHub Push
In this example, we'll trigger the pipeline anytime the master
branch is updated.
module "ecs_push_pipeline" {
source = "cloudposse/ecs-codepipeline/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
name = "app"
namespace = "eg"
stage = "staging"
github_oauth_token = "xxxxxxxxxxxxxx"
github_webhooks_token = "xxxxxxxxxxxxxx"
repo_owner = "cloudposse"
repo_name = "example"
branch = "master"
service_name = "example"
ecs_cluster_name = "eg-staging-example-cluster"
privileged_mode = "true"
}
Trigger on GitHub Releases
In this example, we'll trigger anytime a new GitHub release is cut by setting the even type to release
and using the json_path
to exactly match an action
of published
.
module "ecs_release_pipeline" {
source = "cloudposse/ecs-codepipeline/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
name = "app"
namespace = "eg"
stage = "staging"
github_oauth_token = "xxxxxxxxxxxxxx"
github_webhooks_token = "xxxxxxxxxxxxxx"
repo_owner = "cloudposse"
repo_name = "example"
branch = "master"
service_name = "example"
ecs_cluster_name = "eg-staging-example-cluster"
privileged_mode = "true"
github_webhook_events = ["release"]
webhook_filter_json_path = "$.action"
webhook_filter_match_equals = "published"
}
(Thanks to Stack Overflow)
Examples
Complete usage can be seen in the terraform-aws-ecs-web-app module.
Example Buildspec
Here's an example buildspec.yaml
. Stick this in the root of your project repository.
version: 0.2
phases:
pre_build:
commands:
- echo Logging in to Amazon ECR...
- aws --version
- eval $(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)
- REPOSITORY_URI=$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$IMAGE_REPO_NAME
- IMAGE_TAG=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
build:
commands:
- echo Build started on `date`
- echo Building the Docker image...
- REPO_URI=$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$IMAGE_REPO_NAME
- docker pull $REPO_URI:latest || true
- docker build --cache-from $REPO_URI:latest --tag $REPO_URI:latest --tag $REPO_URI:$IMAGE_TAG .
post_build:
commands:
- echo Build completed on `date`
- echo Pushing the Docker images...
- REPO_URI=$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$IMAGE_REPO_NAME
- docker push $REPO_URI:latest
- docker push $REPO_URI:$IMAGE_TAG
- echo Writing image definitions file...
- printf '[{"name":"%s","imageUri":"%s"}]' "$CONTAINER_NAME" "$REPO_URI:$IMAGE_TAG" | tee imagedefinitions.json
artifacts:
files: imagedefinitions.json
Variables
Required Variables
branch
(string
) requiredBranch of the GitHub repository, e.g.
master
ecs_cluster_name
(string
) requiredECS Cluster Name
image_repo_name
(string
) requiredECR repository name to store the Docker image built by this module. Used as CodeBuild ENV variable when building Docker images. For more info
region
(string
) requiredAWS Region, e.g. us-east-1. Used as CodeBuild ENV variable when building Docker images. For more info
repo_name
(string
) requiredGitHub repository name of the application to be built and deployed to ECS
repo_owner
(string
) requiredGitHub Organization or Username
service_name
(string
) requiredECS Service Name
Optional Variables
aws_account_id
(string
) optionalAWS Account ID. Used as CodeBuild ENV variable when building Docker images. For more info
Default value:
""
badge_enabled
(bool
) optionalGenerates a publicly-accessible URL for the projects build badge. Available as badge_url attribute when enabled
Default value:
false
build_compute_type
(string
) optionalCodeBuild
instance size. Possible values are:BUILD_GENERAL1_SMALL
BUILD_GENERAL1_MEDIUM
BUILD_GENERAL1_LARGE
Default value:
"BUILD_GENERAL1_SMALL"
build_image
(string
) optionalDocker image for build environment, https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-available.html
Default value:
"aws/codebuild/amazonlinux2-x86_64-standard:5.0"
build_timeout
(number
) optionalHow long in minutes, from 5 to 480 (8 hours), for AWS CodeBuild to wait until timing out any related build that does not get marked as completed
Default value:
60
build_type
(string
) optionalThe type of build environment, e.g. 'LINUX_CONTAINER' or 'WINDOWS_CONTAINER' or 'ARM_CONTAINER'
Default value:
"LINUX_CONTAINER"
buildspec
(string
) optionalDeclaration to use for building the project. For more info
Default value:
""
cache_bucket_suffix_enabled
(bool
) optionalThe cache bucket generates a random 13 character string to generate a unique bucket name. If set to false it uses terraform-null-label's id value. It only works when cache_type is 'S3'
Default value:
true
cache_type
(string
) optionalThe type of storage that will be used for the AWS CodeBuild project cache. Valid values: NO_CACHE, LOCAL, and S3. Defaults to S3. If cache_type is S3, it will create an S3 bucket for storing codebuild cache inside
Default value:
"S3"
codebuild_extra_policy_arns
(list(string)
) optionalList of ARNs of extra policies to attach to the CodeBuild role
Default value:
[ ]
codebuild_vpc_config
(any
) optionalConfiguration for the builds to run inside a VPC.
Default value:
{ }
codestar_connection_arn
(string
) optionalCodeStar connection ARN required for Bitbucket integration with CodePipeline
Default value:
""
codestar_output_artifact_format
(string
) optionalOutput artifact type for Source stage in pipeline. Valid values are "CODE_ZIP" (default) and "CODEBUILD_CLONE_REF". See https://docs.aws.amazon.com/codepipeline/latest/userguide/action-reference-CodestarConnectionSource.html
Default value:
"CODE_ZIP"
environment_variables
optionalA list of maps, that contain the keys 'name', 'value', and 'type' to be used as additional environment variables for the build. Valid types are 'PLAINTEXT', 'PARAMETER_STORE', or 'SECRETS_MANAGER'
Type:
list(object(
{
name = string
value = string
type = string
}))Default value:
[ ]
github_oauth_token
(string
) optionalGitHub OAuth Token with permissions to access private repositories
Default value:
""
github_webhook_events
(list(string)
) optionalA list of events which should trigger the webhook. See a list of available events
Default value:
[
"push"
]image_tag
(string
) optionalDocker image tag in the ECR repository, e.g. 'latest'. Used as CodeBuild ENV variable when building Docker images. For more info
Default value:
"latest"
local_cache_modes
(list(string)
) optionalSpecifies settings that AWS CodeBuild uses to store and reuse build dependencies. Valid values: LOCAL_SOURCE_CACHE, LOCAL_DOCKER_LAYER_CACHE, and LOCAL_CUSTOM_CACHE
Default value:
[ ]
poll_source_changes
(bool
) optionalPeriodically check the location of your source content and run the pipeline if changes are detected
Default value:
false
privileged_mode
(bool
) optionalIf set to true, enables running the Docker daemon inside a Docker container on the CodeBuild instance. Used when building Docker images
Default value:
false
s3_bucket_force_destroy
(bool
) optionalA boolean that indicates all objects should be deleted from the CodePipeline artifact store S3 bucket so that the bucket can be destroyed without error
Default value:
false
secondary_artifact_bucket_id
(string
) optionalOptional bucket for secondary artifact deployment. If specified, the buildspec must include a secondary artifacts section which controls the artifacts deployed to the bucket For more info
Default value:
null
secondary_artifact_encryption_enabled
(bool
) optionalIf set to true, enable encryption on the secondary artifact bucket
Default value:
false
secondary_artifact_identifier
(string
) optionalIdentifier for optional secondary artifact deployment. If specified, the identifier must appear in the buildspec as the name of the section which controls the artifacts deployed to the secondary artifact bucket For more info
Default value:
null
webhook_authentication
(string
) optionalThe type of authentication to use. One of IP, GITHUB_HMAC, or UNAUTHENTICATED
Default value:
"GITHUB_HMAC"
webhook_enabled
(bool
) optionalSet to false to prevent the module from creating any webhook resources
Default value:
true
webhook_filter_json_path
(string
) optionalThe JSON path to filter on
Default value:
"$.ref"
webhook_filter_match_equals
(string
) optionalThe value to match on (e.g. refs/heads/{Branch})
Default value:
"refs/heads/{Branch}"
webhook_target_action
(string
) optionalThe name of the action in a pipeline you want to connect to the webhook. The action must be from the source (first) stage of the pipeline
Default value:
"Source"
Context Variables
The following variables are defined in the context.tf
file of this module and part of the terraform-null-label pattern.
context.tf
file of this module and part of the terraform-null-label pattern.additional_tag_map
(map(string)
) optionalAdditional key-value pairs to add to each map in
tags_as_list_of_maps
. Not added totags
orid
.
This is for some rare cases where resources want additional configuration of tags
and therefore take a list of maps with tag key, value, and additional configuration.Required: No
Default value:
{ }
attributes
(list(string)
) optionalID element. Additional attributes (e.g.
workers
orcluster
) to add toid
,
in the order they appear in the list. New attributes are appended to the
end of the list. The elements of the list are joined by thedelimiter
and treated as a single ID element.Required: No
Default value:
[ ]
context
(any
) optionalSingle object for setting entire context at once.
See description of individual variables for details.
Leave string and numeric variables asnull
to use default value.
Individual variable settings (non-null) override settings in context object,
except for attributes, tags, and additional_tag_map, which are merged.Required: No
Default value:
{
"additional_tag_map": {},
"attributes": [],
"delimiter": null,
"descriptor_formats": {},
"enabled": true,
"environment": null,
"id_length_limit": null,
"label_key_case": null,
"label_order": [],
"label_value_case": null,
"labels_as_tags": [
"unset"
],
"name": null,
"namespace": null,
"regex_replace_chars": null,
"stage": null,
"tags": {},
"tenant": null
}delimiter
(string
) optionalDelimiter to be used between ID elements.
Defaults to-
(hyphen). Set to""
to use no delimiter at all.Required: No
Default value:
null
descriptor_formats
(any
) optionalDescribe additional descriptors to be output in the
descriptors
output map.
Map of maps. Keys are names of descriptors. Values are maps of the form
\{<br/> format = string<br/> labels = list(string)<br/> \}
(Type isany
so the map values can later be enhanced to provide additional options.)
format
is a Terraform format string to be passed to theformat()
function.
labels
is a list of labels, in order, to pass toformat()
function.
Label values will be normalized before being passed toformat()
so they will be
identical to how they appear inid
.
Default is{}
(descriptors
output will be empty).Required: No
Default value:
{ }
enabled
(bool
) optionalSet to false to prevent the module from creating any resources
Required: NoDefault value:
null
environment
(string
) optionalID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'
Required: NoDefault value:
null
id_length_limit
(number
) optionalLimit
id
to this many characters (minimum 6).
Set to0
for unlimited length.
Set tonull
for keep the existing setting, which defaults to0
.
Does not affectid_full
.Required: No
Default value:
null
label_key_case
(string
) optionalControls the letter case of the
tags
keys (label names) for tags generated by this module.
Does not affect keys of tags passed in via thetags
input.
Possible values:lower
,title
,upper
.
Default value:title
.Required: No
Default value:
null
label_order
(list(string)
) optionalThe order in which the labels (ID elements) appear in the
id
.
Defaults to ["namespace", "environment", "stage", "name", "attributes"].
You can omit any of the 6 labels ("tenant" is the 6th), but at least one must be present.Required: No
Default value:
null
label_value_case
(string
) optionalControls the letter case of ID elements (labels) as included in
id
,
set as tag values, and output by this module individually.
Does not affect values of tags passed in via thetags
input.
Possible values:lower
,title
,upper
andnone
(no transformation).
Set this totitle
and setdelimiter
to""
to yield Pascal Case IDs.
Default value:lower
.Required: No
Default value:
null
labels_as_tags
(set(string)
) optionalSet of labels (ID elements) to include as tags in the
tags
output.
Default is to include all labels.
Tags with empty values will not be included in thetags
output.
Set to[]
to suppress all generated tags.
Notes:
The value of thename
tag, if included, will be theid
, not thename
.
Unlike othernull-label
inputs, the initial setting oflabels_as_tags
cannot be
changed in later chained modules. Attempts to change it will be silently ignored.Required: No
Default value:
[
"default"
]name
(string
) optionalID element. Usually the component or solution name, e.g. 'app' or 'jenkins'.
This is the only ID element not also included as atag
.
The "name" tag is set to the fullid
string. There is no tag with the value of thename
input.Required: No
Default value:
null
namespace
(string
) optionalID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique
Required: NoDefault value:
null
regex_replace_chars
(string
) optionalTerraform regular expression (regex) string.
Characters matching the regex will be removed from the ID elements.
If not set,"/[^a-zA-Z0-9-]/"
is used to remove all characters other than hyphens, letters and digits.Required: No
Default value:
null
stage
(string
) optionalID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'
Required: NoDefault value:
null
tags
(map(string)
) optionalAdditional tags (e.g.
{'BusinessUnit': 'XYZ'}
).
Neither the tag keys nor the tag values will be modified by this module.Required: No
Default value:
{ }
tenant
(string
) optionalID element (Rarely used, not included by default). A customer identifier, indicating who this instance of a resource is for
Required: NoDefault value:
null
Outputs
badge_url
The URL of the build badge when badge_enabled is enabled
codebuild_badge_url
The URL of the build badge when badge_enabled is enabled
codebuild_cache_bucket_arn
CodeBuild cache S3 bucket ARN
codebuild_cache_bucket_name
CodeBuild cache S3 bucket name
codebuild_project_id
CodeBuild project ID
codebuild_project_name
CodeBuild project name
codebuild_role_arn
CodeBuild IAM Role ARN
codebuild_role_id
CodeBuild IAM Role ID
codepipeline_arn
CodePipeline ARN
codepipeline_id
CodePipeline ID
codepipeline_resource
CodePipeline resource
webhook_id
The CodePipeline webhook's ID
webhook_url
The CodePipeline webhook's URL. POST events to this endpoint to trigger the target
Dependencies
Requirements
terraform
, version:>= 1.3
aws
, version:>= 5.0
random
, version:>= 2.1
Providers
aws
, version:>= 5.0
random
, version:>= 2.1
Modules
Name | Version | Source | Description |
---|---|---|---|
codebuild | 2.0.2 | cloudposse/codebuild/aws | n/a |
codebuild_label | 0.25.0 | cloudposse/label/null | n/a |
codepipeline_assume_role_label | 0.25.0 | cloudposse/label/null | n/a |
codepipeline_label | 0.25.0 | cloudposse/label/null | n/a |
codepipeline_s3_policy_label | 0.25.0 | cloudposse/label/null | n/a |
codestar_label | 0.25.0 | cloudposse/label/null | n/a |
github_webhooks | 0.14.0 | cloudposse/repository-webhooks/github | n/a |
this | 0.25.0 | cloudposse/label/null | n/a |
Resources
The following resources are used by this module:
aws_codepipeline.bitbucket
(resource)aws_codepipeline.default
(resource)aws_codepipeline_webhook.webhook
(resource)aws_iam_policy.codebuild
(resource)aws_iam_policy.codestar
(resource)aws_iam_policy.default
(resource)aws_iam_policy.s3
(resource)aws_iam_role.default
(resource)aws_iam_role_policy_attachment.codebuild
(resource)aws_iam_role_policy_attachment.codebuild_codestar
(resource)aws_iam_role_policy_attachment.codebuild_extras
(resource)aws_iam_role_policy_attachment.codebuild_s3
(resource)aws_iam_role_policy_attachment.codestar
(resource)aws_iam_role_policy_attachment.default
(resource)aws_iam_role_policy_attachment.s3
(resource)aws_s3_bucket.default
(resource)random_string.webhook_secret
(resource)
Data Sources
The following data sources are used by this module:
aws_caller_identity.default
(data source)aws_iam_policy_document.assume_role
(data source)aws_iam_policy_document.codebuild
(data source)aws_iam_policy_document.codestar
(data source)aws_iam_policy_document.default
(data source)aws_iam_policy_document.s3
(data source)aws_region.default
(data source)