From 20c1b29e65f2d2fd752afd53abc0445b977cb88e Mon Sep 17 00:00:00 2001
From: Mason Cole <117116981+bt-macole@users.noreply.github.com>
Date: Thu, 22 Feb 2024 16:51:30 -0800
Subject: [PATCH] feat: custom policy + hardened trust relationship (#132)
* feat: add condition to trust policy
adding a condition on the trust policy for the codebuild project arn ensures
the iam role can not be used by any other codebuild project.
codebuild projects could be extremely permissive, even when least privileged
so enforcing the role can only be used by the intended codebuild project
limits to ability for a threat actor to quietly take control of a powerful
role and do threat actory things.
* feat: support custom iam policy
the default permissions are good for getting up and running, however, they are far more
permissive than any least privileged policy would like, being `*` for all resources for
anything in the default list + any and all additional_permissions.
this allows users to still utilize the quick up and running policy, while also being able
to disable it and replace it with a least privileged custom policy.
the lifecycle rule ensure that users don't get confused by additional permissions and custom
policy variables, failing on a plan if they attempt to use additional_permissions with
default_permissions_enabled set to `false`.
* test: update tests for new functionality
```terraform
--- PASS: TestExamplesCustom (62.77s)
--- PASS: TestExamplesComplete (62.87s)
--- PASS: TestExamplesVPC (78.32s)
PASS
ok github.com/cloudposse/terraform-aws-codebuild 78.790s
```
* docs: update
---
README.md | 251 +++++++-----------
docs/terraform.md | 4 +-
examples/complete/fixtures.us-east-2.tfvars | 2 +-
examples/custom/context.tf | 279 ++++++++++++++++++++
examples/custom/fixtures.us-east-2.tfvars | 34 +++
examples/custom/main.tf | 18 ++
examples/custom/outputs.tf | 34 +++
examples/custom/variables.tf | 49 ++++
examples/custom/versions.tf | 14 +
examples/vpc/fixtures.us-east-2.tfvars | 2 +-
main.tf | 81 ++++--
test/src/examples_complete_test.go | 4 +-
test/src/examples_custom_test.go | 41 +++
test/src/examples_vpc_test.go | 3 +-
variables.tf | 21 +-
15 files changed, 643 insertions(+), 194 deletions(-)
create mode 100644 examples/custom/context.tf
create mode 100644 examples/custom/fixtures.us-east-2.tfvars
create mode 100644 examples/custom/main.tf
create mode 100644 examples/custom/outputs.tf
create mode 100644 examples/custom/variables.tf
create mode 100644 examples/custom/versions.tf
create mode 100644 test/src/examples_custom_test.go
diff --git a/README.md b/README.md
index 5e45884..43b5da9 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,8 @@
-
-# terraform-aws-codebuild [![Latest Release](https://img.shields.io/github/release/cloudposse/terraform-aws-codebuild.svg)](https://github.com/cloudposse/terraform-aws-codebuild/releases) [![Slack Community](https://slack.cloudposse.com/badge.svg)](https://slack.cloudposse.com)
+# terraform-aws-codebuild
+
-[![README Header][readme_header_img]][readme_header_link]
-
-[![Cloud Posse][logo]](https://cpco.io/homepage)
-
-
-## Share the Love
-
-Like this project? Please give it a β
on [our GitHub](https://github.com/cloudposse/terraform-aws-codebuild)! (it helps us **a lot**)
-
-
-
## Related Projects
Check out these related projects.
- [terraform-aws-ecs-codepipeline](https://github.com/cloudposse/terraform-aws-ecs-codepipeline) - Terraform Module for CI/CD with AWS Code Pipeline and Code Build for ECS
-## Help
-
-**Got a question?** We got answers.
-
-File a GitHub [issue](https://github.com/cloudposse/terraform-aws-codebuild/issues), send us an [email][email] or join our [Slack Community][slack].
-
-[![README Commercial Support][readme_commercial_support_img]][readme_commercial_support_link]
-
-## DevOps Accelerator for Startups
-
-
-We are a [**DevOps Accelerator**][commercial_support]. 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](https://img.shields.io/badge/learn%20more-success.svg?style=for-the-badge)][commercial_support]
-
-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][slack] 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.
-
-## Newsletter
-
-Sign up for [our newsletter][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.
+## β¨ Contributing
-## Office Hours
+This project is under active development, and we encourage contributions from our community.
+Many thanks to our outstanding contributors:
-[Join us every Wednesday via Zoom][office_hours] for our weekly "Lunch & Learn" sessions. It's **FREE** for everyone!
+
+
+
-[![zoom](https://img.cloudposse.com/fit-in/200x200/https://cloudposse.com/wp-content/uploads/2019/08/Powered-by-Zoom.png")][office_hours]
+### π Bug Reports & Feature Requests
-## β¨ Contributing
+Please use the [issue tracker](https://github.com/cloudposse/terraform-aws-codebuild/issues) 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 Cloud Posse's other projects, we would love to hear from you!
+Hit us up in [Slack](https://cpco.io/slack?utm_source=github&utm_medium=readme&utm_campaign=cloudposse/terraform-aws-codebuild&utm_content=slack), in the `#cloudposse` channel.
-This project is under active development, and we encourage contributions from our community.
-Many thanks to our outstanding contributors:
+In general, PRs are welcome. We follow the typical "fork-and-pull" Git workflow.
+ 1. Review our [Code of Conduct](https://github.com/cloudposse/terraform-aws-codebuild/?tab=coc-ov-file#code-of-conduct) and [Contributor Guidelines](https://github.com/cloudposse/.github/blob/main/CONTRIBUTING.md).
+ 2. **Fork** the repo on GitHub
+ 3. **Clone** the project to your own machine
+ 4. **Commit** changes to your own branch
+ 5. **Push** your work back up to your fork
+ 6. 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!
+### π Slack Community
+Join our [Open Source Community](https://cpco.io/slack?utm_source=github&utm_medium=readme&utm_campaign=cloudposse/terraform-aws-codebuild&utm_content=slack) 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.
-### Bug Reports & Feature Requests
+### π° Newsletter
-Please use the [issue tracker](https://github.com/cloudposse/terraform-aws-codebuild/issues) to report any bugs or file feature requests.
+Sign up for [our newsletter](https://cpco.io/newsletter?utm_source=github&utm_medium=readme&utm_campaign=cloudposse/terraform-aws-codebuild&utm_content=newsletter) and join 3,000+ DevOps engineers, CTOs, and founders who get insider access to the latest DevOps trends, so you can always stay in the know.
+Dropped straight into your Inbox every week β and usually a 5-minute read.
-### Developing
+### π Office Hours
-If you are interested in being a contributor and want to get involved in developing this project or [help out](https://cpco.io/help-out) with our other projects, we would love to hear from you! Shoot us an [email][email].
+[Join us every Wednesday via Zoom](https://cloudposse.com/office-hours?utm_source=github&utm_medium=readme&utm_campaign=cloudposse/terraform-aws-codebuild&utm_content=office_hours) for your weekly dose of insider DevOps trends, AWS news and Terraform insights, all sourced from our SweetOps community, plus a _live Q&A_ that you canβt find anywhere else.
+It's **FREE** for everyone!
-In general, PRs are welcome. We follow the typical "fork-and-pull" Git workflow.
+## About
- 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
+This project is maintained by Cloud Posse, LLC.
+
-**NOTE:** Be sure to merge the latest changes from "upstream" before making a pull request!
+We are a [**DevOps Accelerator**](https://cpco.io/commercial-support?utm_source=github&utm_medium=readme&utm_campaign=cloudposse/terraform-aws-codebuild&utm_content=commercial_support) for funded startups and enterprises.
+Use our ready-to-go terraform architecture blueprints for AWS to get up and running quickly.
+We build it with you. You own everything. Your team wins. Plus, we stick around until you succeed.
+
-## Copyright
+*Your team can operate like a pro today.*
-Copyright Β© 2017-2023 [Cloud Posse, LLC](https://cpco.io/copyright)
+Ensure that your team succeeds by using our proven process and turnkey blueprints. Plus, we stick around until you succeed.
+π See What's Included
+- **Reference Architecture.** You'll get everything you need from the ground up built using 100% infrastructure as code.
+- **Deployment Strategy.** You'll have a battle-tested deployment strategy using GitHub Actions that's automated and repeatable.
+- **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.
+Preamble to the Apache License, Version 2.0
+
+
-See [LICENSE](LICENSE) for full details.
+Complete license is available in the [`LICENSE`](LICENSE) file.
```text
Licensed to the Apache Software Foundation (ASF) under one
@@ -406,52 +376,15 @@ KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
```
-
-
-
-
-
-
-
-
+
See description of individual variables for details.
Leave string and numeric variables as `null` 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. | `any` |
{| no | +| [custom\_policy](#input\_custom\_policy) | JSON encoded IAM policy to add to the IAM service account permissions. | `list(string)` | `[]` | no | +| [default\_permissions\_enabled](#input\_default\_permissions\_enabled) | When 'true' default base IAM permissions to get up and running with CodeBuild are attached. Those who want a least privileged policy can instead set to `false` and use the `custom_policy` variable. | `bool` | `true` | no | | [delimiter](#input\_delimiter) | Delimiter to be used between ID elements.
"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
}
list(object(|
{
name = string
value = string
type = string
}
))
[| no | -| [extra\_permissions](#input\_extra\_permissions) | List of action strings which will be added to IAM service account permissions. | `list(any)` | `[]` | no | +| [extra\_permissions](#input\_extra\_permissions) | List of action strings which will be added to IAM service account permissions. Only used if `default_permissions_enabled` is set to true. | `list(string)` | `[]` | no | | [fetch\_git\_submodules](#input\_fetch\_git\_submodules) | If set to true, fetches Git submodules for the AWS CodeBuild build project. | `bool` | `false` | no | | [file\_system\_locations](#input\_file\_system\_locations) | A set of file system locations to to mount inside the build. File system locations are documented below. | `any` | `{}` | no | | [git\_clone\_depth](#input\_git\_clone\_depth) | Truncate git history to this many commits. | `number` | `null` | no | diff --git a/examples/complete/fixtures.us-east-2.tfvars b/examples/complete/fixtures.us-east-2.tfvars index a82d6f3..98be75a 100644 --- a/examples/complete/fixtures.us-east-2.tfvars +++ b/examples/complete/fixtures.us-east-2.tfvars @@ -4,7 +4,7 @@ namespace = "eg" stage = "test" -name = "codebuild-test" +name = "codebuild-complete" cache_bucket_suffix_enabled = true diff --git a/examples/custom/context.tf b/examples/custom/context.tf new file mode 100644 index 0000000..5e0ef88 --- /dev/null +++ b/examples/custom/context.tf @@ -0,0 +1,279 @@ +# +# ONLY EDIT THIS FILE IN github.com/cloudposse/terraform-null-label +# All other instances of this file should be a copy of that one +# +# +# Copy this file from https://github.com/cloudposse/terraform-null-label/blob/master/exports/context.tf +# and then place it in your Terraform module to automatically get +# Cloud Posse's standard configuration inputs suitable for passing +# to Cloud Posse modules. +# +# curl -sL https://raw.githubusercontent.com/cloudposse/terraform-null-label/master/exports/context.tf -o context.tf +# +# Modules should access the whole context as `module.this.context` +# to get the input variables with nulls for defaults, +# for example `context = module.this.context`, +# and access individual variables as `module.this.`, +# with final values filled in. +# +# For example, when using defaults, `module.this.context.delimiter` +# will be null, and `module.this.delimiter` will be `-` (hyphen). +# + +module "this" { + source = "cloudposse/label/null" + version = "0.25.0" # requires Terraform >= 0.13.0 + + enabled = var.enabled + namespace = var.namespace + tenant = var.tenant + environment = var.environment + stage = var.stage + name = var.name + delimiter = var.delimiter + attributes = var.attributes + tags = var.tags + additional_tag_map = var.additional_tag_map + label_order = var.label_order + regex_replace_chars = var.regex_replace_chars + id_length_limit = var.id_length_limit + label_key_case = var.label_key_case + label_value_case = var.label_value_case + descriptor_formats = var.descriptor_formats + labels_as_tags = var.labels_as_tags + + context = var.context +} + +# Copy contents of cloudposse/terraform-null-label/variables.tf here + +variable "context" { + type = any + default = { + enabled = true + namespace = null + tenant = null + environment = null + stage = null + name = null + delimiter = null + attributes = [] + tags = {} + additional_tag_map = {} + regex_replace_chars = null + label_order = [] + id_length_limit = null + label_key_case = null + label_value_case = null + descriptor_formats = {} + # Note: we have to use [] instead of null for unset lists due to + # https://github.com/hashicorp/terraform/issues/28137 + # which was not fixed until Terraform 1.0.0, + # but we want the default to be all the labels in `label_order` + # and we want users to be able to prevent all tag generation + # by setting `labels_as_tags` to `[]`, so we need + # a different sentinel to indicate "default" + labels_as_tags = ["unset"] + } + description = <<-EOT + Single object for setting entire context at once. + See description of individual variables for details. + Leave string and numeric variables as `null` 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. + EOT + + validation { + condition = lookup(var.context, "label_key_case", null) == null ? true : contains(["lower", "title", "upper"], var.context["label_key_case"]) + error_message = "Allowed values: `lower`, `title`, `upper`." + } + + validation { + condition = lookup(var.context, "label_value_case", null) == null ? true : contains(["lower", "title", "upper", "none"], var.context["label_value_case"]) + error_message = "Allowed values: `lower`, `title`, `upper`, `none`." + } +} + +variable "enabled" { + type = bool + default = null + description = "Set to false to prevent the module from creating any resources" +} + +variable "namespace" { + type = string + default = null + description = "ID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique" +} + +variable "tenant" { + type = string + default = null + description = "ID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is for" +} + +variable "environment" { + type = string + default = null + description = "ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'" +} + +variable "stage" { + type = string + default = null + description = "ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'" +} + +variable "name" { + type = string + default = null + description = <<-EOT + ID element. Usually the component or solution name, e.g. 'app' or 'jenkins'. + This is the only ID element not also included as a `tag`. + The "name" tag is set to the full `id` string. There is no tag with the value of the `name` input. + EOT +} + +variable "delimiter" { + type = string + default = null + description = <<-EOT + Delimiter to be used between ID elements. + Defaults to `-` (hyphen). Set to `""` to use no delimiter at all. + EOT +} + +variable "attributes" { + type = list(string) + default = [] + description = <<-EOT + ID element. Additional attributes (e.g. `workers` or `cluster`) to add to `id`, + 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 the `delimiter` + and treated as a single ID element. + EOT +} + +variable "labels_as_tags" { + type = set(string) + default = ["default"] + description = <<-EOT + Set 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 the `tags` output. + Set to `[]` to suppress all generated tags. + **Notes:** + The value of the `name` tag, if included, will be the `id`, not the `name`. + Unlike other `null-label` inputs, the initial setting of `labels_as_tags` cannot be + changed in later chained modules. Attempts to change it will be silently ignored. + EOT +} + +variable "tags" { + type = map(string) + default = {} + description = <<-EOT + Additional tags (e.g. `{'BusinessUnit': 'XYZ'}`). + Neither the tag keys nor the tag values will be modified by this module. + EOT +} + +variable "additional_tag_map" { + type = map(string) + default = {} + description = <<-EOT + Additional key-value pairs to add to each map in `tags_as_list_of_maps`. Not added to `tags` or `id`. + 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. + EOT +} + +variable "label_order" { + type = list(string) + default = null + description = <<-EOT + The 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. + EOT +} + +variable "regex_replace_chars" { + type = string + default = null + description = <<-EOT + Terraform 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. + EOT +} + +variable "id_length_limit" { + type = number + default = null + description = <<-EOT + Limit `id` to this many characters (minimum 6). + Set to `0` for unlimited length. + Set to `null` for keep the existing setting, which defaults to `0`. + Does not affect `id_full`. + EOT + validation { + condition = var.id_length_limit == null ? true : var.id_length_limit >= 6 || var.id_length_limit == 0 + error_message = "The id_length_limit must be >= 6 if supplied (not null), or 0 for unlimited length." + } +} + +variable "label_key_case" { + type = string + default = null + description = <<-EOT + Controls the letter case of the `tags` keys (label names) for tags generated by this module. + Does not affect keys of tags passed in via the `tags` input. + Possible values: `lower`, `title`, `upper`. + Default value: `title`. + EOT + + validation { + condition = var.label_key_case == null ? true : contains(["lower", "title", "upper"], var.label_key_case) + error_message = "Allowed values: `lower`, `title`, `upper`." + } +} + +variable "label_value_case" { + type = string + default = null + description = <<-EOT + Controls 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 the `tags` input. + Possible values: `lower`, `title`, `upper` and `none` (no transformation). + Set this to `title` and set `delimiter` to `""` to yield Pascal Case IDs. + Default value: `lower`. + EOT + + validation { + condition = var.label_value_case == null ? true : contains(["lower", "title", "upper", "none"], var.label_value_case) + error_message = "Allowed values: `lower`, `title`, `upper`, `none`." + } +} + +variable "descriptor_formats" { + type = any + default = {} + description = <<-EOT + Describe additional descriptors to be output in the `descriptors` output map. + Map of maps. Keys are names of descriptors. Values are maps of the form + `{ + format = string + labels = list(string) + }` + (Type is `any` so the map values can later be enhanced to provide additional options.) + `format` is a Terraform format string to be passed to the `format()` function. + `labels` is a list of labels, in order, to pass to `format()` function. + Label values will be normalized before being passed to `format()` so they will be + identical to how they appear in `id`. + Default is `{}` (`descriptors` output will be empty). + EOT +} + +#### End of copy of cloudposse/terraform-null-label/variables.tf diff --git a/examples/custom/fixtures.us-east-2.tfvars b/examples/custom/fixtures.us-east-2.tfvars new file mode 100644 index 0000000..0de2959 --- /dev/null +++ b/examples/custom/fixtures.us-east-2.tfvars @@ -0,0 +1,34 @@ +region = "us-east-2" + +namespace = "eg" + +stage = "test" + +name = "codebuild-custom-policy" + +cache_bucket_suffix_enabled = true + +environment_variables = [ + { + name = "APP_URL" + value = "https://app.example.com" + type = "PLAINTEXT" + }, + { + name = "COMPANY_NAME" + value = "Cloud Posse" + type = "PLAINTEXT" + }, + { + name = "TIME_ZONE" + value = "America/Los_Angeles" + type = "PLAINTEXT" + } +] + +cache_expiration_days = 7 + +cache_type = "S3" + +default_permissions_enabled = false +custom_policy = ["{\"Statement\":[{\"Action\":[\"secretsmanager:GetSecretValue\"],\"Condition\":{\"StringLike\":{\"aws:ResourceTag/used-by\":\"*my-team*\"}},\"Effect\":\"Allow\",\"Resource\":[\"arn:aws:secretsmanager:us-east-2:*:secret:some-secret-value\",\"arn:aws:secretsmanager:us-east-2:*:secret:some-other-secret-value\"],\"Sid\":\"ReadSecrets\"},{\"Action\":[\"logs:CreateLogGroup\",\"logs:CreateLogStream\",\"logs:PutLogEvents\"],\"Effect\":\"Allow\",\"Resource\":[\"*\"],\"Sid\":\"LoggingForTesting\"}],\"Version\":\"2012-10-17\"}"] diff --git a/examples/custom/main.tf b/examples/custom/main.tf new file mode 100644 index 0000000..2523683 --- /dev/null +++ b/examples/custom/main.tf @@ -0,0 +1,18 @@ +provider "aws" { + region = var.region +} + +module "codebuild" { + source = "../../" + description = "This is my awesome CodeBuild project" + concurrent_build_limit = 10 + cache_bucket_suffix_enabled = var.cache_bucket_suffix_enabled + environment_variables = var.environment_variables + cache_expiration_days = var.cache_expiration_days + cache_type = var.cache_type + + default_permissions_enabled = var.default_permissions_enabled + custom_policy = var.custom_policy + + context = module.this.context +} diff --git a/examples/custom/outputs.tf b/examples/custom/outputs.tf new file mode 100644 index 0000000..8b7c30a --- /dev/null +++ b/examples/custom/outputs.tf @@ -0,0 +1,34 @@ +output "project_name" { + description = "Project name" + value = module.codebuild.project_name +} + +output "project_id" { + description = "Project ID" + value = module.codebuild.project_id +} + +output "role_id" { + description = "IAM Role ID" + value = module.codebuild.role_id +} + +output "role_arn" { + description = "IAM Role ARN" + value = module.codebuild.role_arn +} + +output "cache_bucket_name" { + description = "Cache S3 bucket name" + value = module.codebuild.cache_bucket_name +} + +output "cache_bucket_arn" { + description = "Cache S3 bucket ARN" + value = module.codebuild.cache_bucket_arn +} + +output "badge_url" { + description = "The URL of the build badge when badge_enabled is enabled" + value = module.codebuild.badge_url +} diff --git a/examples/custom/variables.tf b/examples/custom/variables.tf new file mode 100644 index 0000000..42b4907 --- /dev/null +++ b/examples/custom/variables.tf @@ -0,0 +1,49 @@ +variable "region" { + type = string + description = "AWS region" +} + +variable "environment_variables" { + type = list(object( + { + name = string + value = string + type = string + })) + + default = [ + { + name = "NO_ADDITIONAL_BUILD_VARS" + value = "TRUE" + type = "PLAINTEXT" + }] + + description = "A 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'" +} + +variable "cache_expiration_days" { + type = number + description = "How many days should the build cache be kept. It only works when cache_type is 'S3'" +} + +variable "cache_bucket_suffix_enabled" { + type = bool + description = "The 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" +} + +variable "cache_type" { + type = string + description = "The type of storage that will be used for the AWS CodeBuild project cache. Valid values: NO_CACHE, LOCAL, and S3. Defaults to NO_CACHE. If cache_type is S3, it will create an S3 bucket for storing codebuild cache inside" +} + +variable "default_permissions_enabled" { + type = bool + default = true + description = "When 'true' default base iam permissions to get up and running with codebuild are attached. Those who want a least priveleged policy can instead set to `false` and use the `custom policy` variable." +} + +variable "custom_policy" { + type = list(string) + description = "JSON encoded IAM policy to add to the IAM service account permissions." + default = [] +} diff --git a/examples/custom/versions.tf b/examples/custom/versions.tf new file mode 100644 index 0000000..2bc15af --- /dev/null +++ b/examples/custom/versions.tf @@ -0,0 +1,14 @@ +terraform { + required_version = ">= 1.3" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 5.0" + } + random = { + source = "hashicorp/random" + version = ">= 2.1" + } + } +} diff --git a/examples/vpc/fixtures.us-east-2.tfvars b/examples/vpc/fixtures.us-east-2.tfvars index fcfd28c..94e0eae 100644 --- a/examples/vpc/fixtures.us-east-2.tfvars +++ b/examples/vpc/fixtures.us-east-2.tfvars @@ -4,7 +4,7 @@ namespace = "eg" stage = "test" -name = "codebuild-test" +name = "codebuild-vpc" availability_zones = ["us-east-2a", "us-east-2b"] diff --git a/main.tf b/main.tf index fab8a3c..4518229 100644 --- a/main.tf +++ b/main.tf @@ -106,6 +106,9 @@ locals { create_s3_cache_bucket = local.s3_cache_enabled && var.s3_cache_bucket_name == null s3_bucket_name = local.create_s3_cache_bucket ? join("", aws_s3_bucket.cache_bucket[*].bucket) : var.s3_cache_bucket_name + aws_region = signum(length(var.aws_region)) == 1 ? var.aws_region : data.aws_region.default.name + aws_account_id = signum(length(var.aws_account_id)) == 1 ? var.aws_account_id : data.aws_caller_identity.default.account_id + ## This is the magic where a map of a list of maps is generated ## and used to conditionally add the cache bucket option to the ## aws_codebuild_project @@ -150,6 +153,17 @@ data "aws_iam_policy_document" "role" { identifiers = ["codebuild.amazonaws.com"] } + condition { + test = "StringEquals" + variable = "aws:SourceArn" + + # to avoid cyclic dependencies with codebuild, we can't reference + # the resources arn directly instead we interpolate the arn using known values + values = [ + "arn:aws:codebuild:${local.aws_region}:${local.aws_account_id}:project/${module.this.id}" + ] + } + effect = "Allow" } } @@ -179,31 +193,35 @@ data "aws_s3_bucket" "secondary_artifact" { data "aws_iam_policy_document" "permissions" { count = module.this.enabled ? 1 : 0 - statement { - sid = "" + dynamic "statement" { + for_each = var.default_permissions_enabled ? [1] : [] - actions = compact(concat([ - "codecommit:GitPull", - "ecr:BatchCheckLayerAvailability", - "ecr:CompleteLayerUpload", - "ecr:GetAuthorizationToken", - "ecr:InitiateLayerUpload", - "ecr:PutImage", - "ecr:UploadLayerPart", - "ecs:RunTask", - "iam:PassRole", - "logs:CreateLogGroup", - "logs:CreateLogStream", - "logs:PutLogEvents", - "ssm:GetParameters", - "secretsmanager:GetSecretValue", - ], var.extra_permissions)) + content { + sid = "" - effect = "Allow" + actions = compact(concat([ + "codecommit:GitPull", + "ecr:BatchCheckLayerAvailability", + "ecr:CompleteLayerUpload", + "ecr:GetAuthorizationToken", + "ecr:InitiateLayerUpload", + "ecr:PutImage", + "ecr:UploadLayerPart", + "ecs:RunTask", + "iam:PassRole", + "logs:CreateLogGroup", + "logs:CreateLogStream", + "logs:PutLogEvents", + "ssm:GetParameters", + "secretsmanager:GetSecretValue", + ], var.extra_permissions)) - resources = [ - "*", - ] + effect = "Allow" + + resources = [ + "*", + ] + } } dynamic "statement" { @@ -225,6 +243,16 @@ data "aws_iam_policy_document" "permissions" { ] } } + + lifecycle { + precondition { + condition = length(var.extra_permissions) > 0 ? var.default_permissions_enabled : true + error_message = <<-EOT + Extra permissions can only be attached to the default permissions policy statement. + Either set `default_permissions_enabled` to true or use `custom_policy` to set a least privileged policy." + EOT + } + } } data "aws_iam_policy_document" "vpc_permissions" { @@ -256,14 +284,14 @@ data "aws_iam_policy_document" "vpc_permissions" { ] resources = [ - "arn:aws:ec2:${var.aws_region}:${var.aws_account_id}:network-interface/*" + "arn:aws:ec2:${local.aws_region}:${local.aws_account_id}:network-interface/*" ] condition { test = "StringEquals" variable = "ec2:Subnet" values = formatlist( - "arn:aws:ec2:${var.aws_region}:${var.aws_account_id}:subnet/%s", + "arn:aws:ec2:${local.aws_region}:${local.aws_account_id}:subnet/%s", var.vpc_config.subnets ) } @@ -281,6 +309,7 @@ data "aws_iam_policy_document" "vpc_permissions" { data "aws_iam_policy_document" "combined_permissions" { override_policy_documents = compact([ + join("", var.custom_policy), join("", data.aws_iam_policy_document.permissions[*].json), var.vpc_config != {} ? join("", data.aws_iam_policy_document.vpc_permissions[*].json) : null ]) @@ -385,12 +414,12 @@ resource "aws_codebuild_project" "default" { environment_variable { name = "AWS_REGION" - value = signum(length(var.aws_region)) == 1 ? var.aws_region : data.aws_region.default.name + value = local.aws_region } environment_variable { name = "AWS_ACCOUNT_ID" - value = signum(length(var.aws_account_id)) == 1 ? var.aws_account_id : data.aws_caller_identity.default.account_id + value = local.aws_account_id } dynamic "environment_variable" { diff --git a/test/src/examples_complete_test.go b/test/src/examples_complete_test.go index 9ee34f7..a35aa70 100644 --- a/test/src/examples_complete_test.go +++ b/test/src/examples_complete_test.go @@ -28,14 +28,14 @@ func TestExamplesComplete(t *testing.T) { // Run `terraform output` to get the value of an output variable projectName := terraform.Output(t, terraformOptions, "project_name") - expectedProjectName := "eg-test-codebuild-test" + expectedProjectName := "eg-test-codebuild-complete" // Verify we're getting back the outputs we expect assert.Equal(t, expectedProjectName, projectName) // Run `terraform output` to get the value of an output variable cacheS3BucketName := terraform.Output(t, terraformOptions, "cache_bucket_name") - expectedCacheS3BucketName := "eg-test-codebuild-test" + expectedCacheS3BucketName := "eg-test-codebuild-complete" // Verify we're getting back the outputs we expect assert.Contains(t, cacheS3BucketName, expectedCacheS3BucketName, "Bucket should contain prefix") } diff --git a/test/src/examples_custom_test.go b/test/src/examples_custom_test.go new file mode 100644 index 0000000..dd9c2e9 --- /dev/null +++ b/test/src/examples_custom_test.go @@ -0,0 +1,41 @@ +package test + +import ( + "testing" + + "github.com/gruntwork-io/terratest/modules/terraform" + "github.com/stretchr/testify/assert" +) + +// Test the Terraform module in examples/custom using Terratest. +func TestExamplesCustom(t *testing.T) { + t.Parallel() + + terraformOptions := &terraform.Options{ + // The path to where our Terraform code is located + TerraformDir: "../../examples/custom", + Upgrade: true, + // Variables to pass to our Terraform code using -var-file options + VarFiles: []string{"fixtures.us-east-2.tfvars"}, + } + + // At the end of the test, run `terraform destroy` to clean up any resources that were created + defer terraform.Destroy(t, terraformOptions) + + // This will run `terraform init` and `terraform apply` and fail the test if there are any errors + terraform.InitAndApply(t, terraformOptions) + + // Run `terraform output` to get the value of an output variable + projectName := terraform.Output(t, terraformOptions, "project_name") + + expectedProjectName := "eg-test-codebuild-custom-policy" + // Verify we're getting back the outputs we expect + assert.Equal(t, expectedProjectName, projectName) + + // Run `terraform output` to get the value of an output variable + cacheS3BucketName := terraform.Output(t, terraformOptions, "cache_bucket_name") + + expectedCacheS3BucketName := "eg-test-codebuild-custom-policy" + // Verify we're getting back the outputs we expect + assert.Contains(t, cacheS3BucketName, expectedCacheS3BucketName, "Bucket should contain prefix") +} diff --git a/test/src/examples_vpc_test.go b/test/src/examples_vpc_test.go index 85a6e20..f8819c0 100644 --- a/test/src/examples_vpc_test.go +++ b/test/src/examples_vpc_test.go @@ -28,8 +28,7 @@ func TestExamplesVPC(t *testing.T) { // Run `terraform output` to get the value of an output variable projectName := terraform.Output(t, terraformOptions, "project_name") - expectedProjectName := "eg-test-codebuild-test" + expectedProjectName := "eg-test-codebuild-vpc" // Verify we're getting back the outputs we expect assert.Equal(t, expectedProjectName, projectName) - } diff --git a/variables.tf b/variables.tf index 57c9bf2..8476981 100644 --- a/variables.tf +++ b/variables.tf @@ -254,10 +254,27 @@ variable "logs_config" { description = "Configuration for the builds to store log data to CloudWatch or S3." } +variable "default_permissions_enabled" { + type = bool + default = true + description = "When 'true' default base IAM permissions to get up and running with CodeBuild are attached. Those who want a least privileged policy can instead set to `false` and use the `custom_policy` variable." +} + variable "extra_permissions" { - type = list(any) + type = list(string) default = [] - description = "List of action strings which will be added to IAM service account permissions." + description = "List of action strings which will be added to IAM service account permissions. Only used if `default_permissions_enabled` is set to true." +} + +variable "custom_policy" { + type = list(string) + description = "JSON encoded IAM policy to add to the IAM service account permissions." + default = [] + + validation { + condition = length(var.custom_policy) <= 1 + error_message = "Only 1 custom policy can be included." + } } variable "iam_role_path" {
{
"name": "NO_ADDITIONAL_BUILD_VARS",
"type": "PLAINTEXT",
"value": "TRUE"
}
]