├── .gitignore ├── LICENSE ├── README.md ├── examples └── fresh-start │ ├── README.md │ ├── conf.tfvars │ ├── main.tf │ └── versions.tf ├── main.tf ├── outputs.tf ├── variables.tf └── versions.tf /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled files 2 | *.tfstate 3 | *.tfstate.backup 4 | 5 | # Module directory 6 | .terraform/ 7 | 8 | # Plans 9 | *.plan 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # terraform-aws-backend 2 | A Terraform module which enables you to create and manage your [Terraform AWS Backend resources](https://www.terraform.io/docs/backends/types/s3.html), _with terraform_ to achieve a best practice setup. 3 | 4 | More info on the aws (s3/dynamo) backend supported by this module is found here: 5 | 6 | https://www.terraform.io/docs/backends/types/s3.html 7 | 8 | 9 | # Bootstrapping your project 10 | 11 | This terraform module helps you bootstrap any project which uses terraform for infrastructure management. [This module has a few options which are documented below. They allow you to change the behavior of this module.](#module-options) 12 | 13 | **_Why does this exist?_** 14 | 15 | One of the most popular backend options for terraform is AWS (S3 for state, and DynamoDB for the lock table). If your project [specifies an AWS/S3 backend](https://www.terraform.io/docs/backends/types/s3.html), Terraform requires the existence of an S3 bucket in which to store _state_ information about your project, and a DynamoDB table to use for locking (this prevents you, your collaborators, and CI from stepping on each other with terraform commands which either modify your state or the infrastructure itself). 16 | 17 | This terraform module creates/manages those resources: 18 | 19 | * Versioned S3 bucket for state 20 | * Properly configured DynamoDB lock table 21 | 22 | **If you follow this README carefully, you should be able to avoid the circular dependency which is inherent to the problem at hand.** 23 | 24 | **_What circular dependency?_** 25 | 26 | Your resulting terraform configuration block will refer to the resources created by this module. You wouldn't be able to `plan` or `apply` if your state bucket and lock table don't exist. The details which make this work can be seen under [the section which encourages you to postpone writing your terraform configuration block](#postpone-writing-your-terraform-configuration-block) and the [specific options used in the commands section below](#commands-are-the-fun-part). 27 | 28 | ### a note on state bucket and s3 key naming 29 | 30 | For the purposes of this intro, we'll use a bucket named `terraform-state-bucket`, but you'll want to choose an appropriate name for the s3 bucket in which terraform will store your infrastructure state. Perhaps something like `terraform-state-`, or, if you store all of your terraform state for all projects in a single bucket, `bucket-with-all-of-my-tf-states` along with a `key` that defines a path/key name which is more project specific such as `states/project-x-terraform.tfstate`. 31 | 32 | ### postpone writing your terraform configuration block 33 | 34 | In order to bootstrap your project with this module/setup, you will need to wait until **after** Step 4 (below) to write your [terraform configuration block](https://www.terraform.io/docs/configuration/terraform.html) into one of your `.tf` files. (Your "terraform configuration block" is the one that looks like this `terraform {}`.) 35 | 36 | If you are updating an existing terraform-managed project, or you already wrote your `terraform {...}` block into one of your `.tf` files, you will run into the following error on Step 3 (`terraform plan`): 37 | 38 | ![reinit required error](http://g.samstav.xyz/av5vyblbwq.png) 39 | 40 | 41 | ### describe your terraform backend resources 42 | 43 | ```hcl 44 | module "backend" { 45 | source = "github.com/samstav/terraform-aws-backend" 46 | backend_bucket = "terraform-state-bucket" 47 | # using options, e.g. if you dont want a dynamodb lock table, uncomment this: 48 | # dynamodb_lock_table_enabled = false 49 | } 50 | ``` 51 | 52 | ### if using _existing_ backend resources (instead of creating new ones) 53 | 54 | #### re-using a DynamoDB lock table across multiple terraform-managed projects 55 | 56 | One of the resources created and managed by this module is the DynamoDB Table for [terraform locking](https://www.terraform.io/docs/state/locking.html). This module provides a default name: `terraform-lock`. This table may actually be re-used across multiple different projects. In the case that you already have a DynamoDB table you would like to use for locking (or perhaps you are already using this module in another project), you can simply import that dynamodb table: 57 | 58 | ```bash 59 | # If you are running Terraform at >=0.12.*... 60 | $ terraform import module.backend.aws_dynamodb_table.tf_backend_state_lock_table terraform-lock 61 | 62 | # ...or if you are running it at <0.12.* 63 | $ terraform import module.backend.aws_dynamodb_table.tf_backend_state_lock_table[0] terraform-lock 64 | ``` 65 | 66 | _(The `[0]` is needed in <0.12.* because it is a "conditional resource" and you must refer to the 'count' index when importing, which is always `[0]`)_ 67 | 68 | Where `backend` is your chosen `terraform-aws-backend` module instance name, and `terraform-lock` is the DynamoDB table name you use for tf state locking. 69 | 70 | If you attempt to apply this module without importing the existing DynamoDB table with the same name, you will run into the following error: 71 | 72 | ``` 73 | Error: Error applying plan: 74 | 75 | 1 error(s) occurred: 76 | 77 | * module.backend.aws_dynamodb_table.tf_backend_state_lock_table: 1 error(s) occurred: 78 | 79 | * aws_dynamodb_table.tf_backend_state_lock_table: ResourceInUseException: Table already exists: terraform-lock 80 | status code: 400, request id: F35KO0U78JJOIWEJFNJNJHSLDBFF66Q9ASUAAJG 81 | ``` 82 | 83 | ### commands are the fun part 84 | 85 | The following commands will get you up and running: 86 | ```bash 87 | # Step 1: Download modules 88 | terraform get -update 89 | # Step 2: Initialize your directory/project for use with terraform 90 | # The use of -backend=false here is important: it avoids backend configuration 91 | # on our first call to init since we havent created our backend resources yet 92 | terraform init -backend=false 93 | # Step 3: Create infrastructure plan for just the tf backend resources 94 | # Target only the resources needed for our aws backend for terraform state/locking 95 | terraform plan -out=backend.plan -target=module.backend 96 | # Step 4: Apply the infrastructure plan 97 | terraform apply backend.plan 98 | # Step 5: Only after applying (building) the backend resources, write our terraform config. 99 | # Now we can write the terraform backend configuration into our project 100 | # Instead of this command, you can write the terraform config block into any of your .tf files 101 | # Please see "writing your terraform configuration" below for more info 102 | echo 'terraform { backend "s3" {} }' > conf.tf 103 | # Step 6: Reinitialize terraform to use your newly provisioned backend 104 | terraform init -reconfigure \ 105 | -backend-config="bucket=terraform-state-bucket" \ 106 | -backend-config="key=states/terraform.tfstate" \ 107 | -backend-config="encrypt=1" \ 108 | # leave this next line out if you dont want to use a tf lock 109 | -backend-config="dynamodb_table=terraform-lock" 110 | ``` 111 | 112 | ### writing your terraform configuration 113 | 114 | https://www.terraform.io/docs/configuration/terraform.html 115 | 116 | Instead of using the `echo` command above in Step 5 (provided only for proof of concept), you can just write your terraform config into one of your \*.tf files. Otherwise you'll end up needing to provide the `-backend-config` [parameters partial configuration](https://www.terraform.io/docs/backends/config.html#partial-configuration) every single time you run `terraform init` (which might be often). 117 | 118 | ```hcl 119 | terraform { 120 | backend "s3" { 121 | bucket = "terraform-state-bucket" 122 | key = "states/terraform.tfstate" 123 | dynamodb_table = "terraform-lock" 124 | encrypt = "true" 125 | } 126 | } 127 | ``` 128 | 129 | ### reconfiguring terraform after building your backend resources 130 | 131 | Terraform might ask you if you want to copy your existing state. You probably do: 132 | 133 | ![yes](http://g.samstav.xyz/bgs7hwsiqa.png) 134 | 135 | ## Module options 136 | 137 | Options and configuration for this module are exposed via terraform variables. 138 | 139 | 140 | #### `backend_bucket` 141 | 142 | This is the only variable which has no default but is required. You will need to define this value in your terraform-aws-backend module block. There are a few ways to do this, here's a couple: 143 | 144 | ```hcl 145 | module "backend" { 146 | source = "github.com/samstav/terraform-aws-backend" 147 | backend_bucket = "terraform-state-bucket" 148 | } 149 | ``` 150 | 151 | OR 152 | 153 | ```hcl 154 | variable "backend_bucket" { 155 | default = "terraform-state-bucket" 156 | } 157 | 158 | module "backend" { 159 | source = "github.com/samstav/terraform-aws-backend" 160 | backend_bucket = "${var.backend_bucket}" 161 | } 162 | ``` 163 | 164 | #### `dynamodb_lock_table_enabled` 165 | 166 | _Defaults to `true`._ 167 | 168 | - Set to false or 0 to prevent this module from creating the DynamoDB table to use for terraform state locking and consistency. More info on locking for aws/s3 backends: https://www.terraform.io/docs/backends/types/s3.html. More information about how terraform handles booleans here: https://www.terraform.io/docs/configuration/variables.html" 169 | } 170 | 171 | #### `dynamodb_lock_table_stream_enabled` 172 | 173 | _Defaults to `false`._ 174 | 175 | Affects terraform-aws-backend module behavior. Set to false or 0 to disable DynamoDB Streams for the table. More info on DynamoDB streams: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html. More information about how terraform handles booleans here: https://www.terraform.io/docs/configuration/variables.html 176 | 177 | 178 | #### `dynamodb_lock_table_stream_view_type` 179 | 180 | _Defaults to `NEW_AND_OLD_IMAGES`_ 181 | 182 | Only applies if `dynamodb_lock_table_stream_enabled` is true. 183 | 184 | #### `dynamodb_lock_table_name` 185 | 186 | _Defaults to `terraform-lock`_ 187 | 188 | The name of your [terraform state locking](https://www.terraform.io/docs/state/locking.html) DynamoDB Table. 189 | 190 | #### `lock_table_read_capacity` 191 | 192 | _Defaults to `1` Read Capacity Unit._ 193 | 194 | More on DynamoDB Capacity Units: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/CapacityUnitCalculations.html 195 | 196 | 197 | #### `lock_table_write_capacity` 198 | _Defaults to `1` Write Capacity Unit._ 199 | 200 | More on DynamoDB Capacity Units: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/CapacityUnitCalculations.html 201 | 202 | #### `kms_key_id` 203 | _Defaults to ``._ 204 | 205 | Encryption key to use for encrypting the terraform remote state s3 bucket. If not specified, then AWS-S3 encryption key management method will be used, which uses keys derived from the account master kms key. If specified, then AWS-KMS encryption key management method will be used. If the kms_key_id is specified, then you must specify the backend config option `kms_key_id`. More on s3 bucket server side encryption: https://docs.aws.amazon.com/AmazonS3/latest/dev/serv-side-encryption.html and https://docs.aws.amazon.com/AmazonS3/latest/dev/bucket-encryption.html 206 | 207 | ### terraform-aws-backend terraform variables 208 | 209 | See variables available for module configuration 210 | 211 | https://github.com/samstav/terraform-aws-backend/blob/master/variables.tf 212 | -------------------------------------------------------------------------------- /examples/fresh-start/README.md: -------------------------------------------------------------------------------- 1 | ## terraform-aws-backend fresh start example 2 | 3 | In this example, we assume no existing backend resources. That is, 4 | we will create our s3 bucket(s) and dynamodb lock table from 5 | scratch without doing any `terraform import`s. 6 | 7 | To run this example: 8 | 9 | ``` 10 | terraform init -backend=false 11 | terraform plan -out=backend.plan -target=module.backend -var 'backend_bucket=tf-backend-aws-example' 12 | terraform apply backend.plan 13 | echo 'terraform { backend "s3" {} }' > conf.tf 14 | terraform init -reconfigure -backend-config=conf.tfvars 15 | 16 | # Now 'show' should show your terraform backend resource attributes 17 | terraform show 18 | ``` 19 | -------------------------------------------------------------------------------- /examples/fresh-start/conf.tfvars: -------------------------------------------------------------------------------- 1 | bucket = "tf-backend-aws-example" 2 | key = "states/example" 3 | region = "us-east-1" 4 | dynamodb_table = "terraform-lock" 5 | encrypt = true 6 | -------------------------------------------------------------------------------- /examples/fresh-start/main.tf: -------------------------------------------------------------------------------- 1 | variable "backend_bucket" { 2 | } 3 | 4 | provider "aws" { 5 | version = "~> 2.39" 6 | region = "us-west-2" 7 | } 8 | 9 | module "backend" { 10 | /* 11 | * Since this example lives in the module repository, 12 | * we use a relative path '../', but typically we would use 13 | * the github url, like so: 14 | * 15 | * source = "github.com/samstav/terraform-aws-backend" 16 | */ 17 | 18 | source = "../../" 19 | backend_bucket = var.backend_bucket 20 | } 21 | 22 | # 23 | # Just to demonstrate... 24 | # 25 | 26 | output "s3_backend_bucket_name" { 27 | value = module.backend.s3_backend_bucket_name 28 | } 29 | 30 | output "dynamodb_lock_table_name" { 31 | value = module.backend.dynamodb_lock_table_name 32 | } 33 | 34 | output "dynamodb_lock_table_arn" { 35 | value = module.backend.dynamodb_lock_table_arn 36 | } 37 | 38 | output "dynamodb_lock_stream_arn" { 39 | value = module.backend.dynamodb_lock_stream_arn 40 | } 41 | 42 | output "dynamodb_lock_stream_label" { 43 | value = module.backend.dynamodb_lock_stream_label 44 | } 45 | -------------------------------------------------------------------------------- /examples/fresh-start/versions.tf: -------------------------------------------------------------------------------- 1 | 2 | terraform { 3 | required_version = ">= 0.12" 4 | } 5 | -------------------------------------------------------------------------------- /main.tf: -------------------------------------------------------------------------------- 1 | /* 2 | * Module: terraform-aws-backend 3 | * 4 | * Bootstrap your terraform backend on AWS. 5 | * 6 | * This module configures resources for state locking for terraform >= 0.9.0 7 | * https://github.com/hashicorp/terraform/blob/master/CHANGELOG.md#090-march-15-2017 8 | * 9 | * This template creates and/or manages the following resources 10 | * - An S3 Bucket for storing terraform state 11 | * - An S3 Bucket for storing logs from the state bucket 12 | * - A DynamoDB table to be used for state locking and consistency 13 | * 14 | * The DynamoDB state locking table is optional: to disable, 15 | * set the 'dynamodb_lock_table_enabled' variable to false. 16 | * For more info on how terraform handles boolean variables: 17 | * - https://www.terraform.io/docs/configuration/variables.html 18 | * 19 | * If using an existing S3 Bucket, perform a terraform import on your bucket 20 | * into your terraform-aws-backend module instance: 21 | * 22 | * $ terraform import module.backend.aws_s3_bucket.tf_backend_bucket 23 | * 24 | * where the 'backend' portion is the name you choose: 25 | * 26 | * module "backend" { 27 | * source = "github.com/samstav/terraform-aws-backend" 28 | * } 29 | * 30 | */ 31 | 32 | data "aws_caller_identity" "current" { 33 | } 34 | 35 | resource "aws_dynamodb_table" "tf_backend_state_lock_table" { 36 | count = var.dynamodb_lock_table_enabled ? 1 : 0 37 | name = var.dynamodb_lock_table_name 38 | read_capacity = var.lock_table_read_capacity 39 | write_capacity = var.lock_table_write_capacity 40 | hash_key = "LockID" 41 | stream_enabled = var.dynamodb_lock_table_stream_enabled 42 | stream_view_type = var.dynamodb_lock_table_stream_enabled ? var.dynamodb_lock_table_stream_view_type : "" 43 | 44 | attribute { 45 | name = "LockID" 46 | type = "S" 47 | } 48 | tags = { 49 | Description = "Terraform state locking table for account ${data.aws_caller_identity.current.account_id}." 50 | ManagedByTerraform = "true" 51 | TerraformModule = "terraform-aws-backend" 52 | } 53 | 54 | lifecycle { 55 | prevent_destroy = true 56 | } 57 | } 58 | 59 | resource "aws_s3_bucket" "tf_backend_bucket" { 60 | bucket = var.backend_bucket 61 | acl = "private" 62 | versioning { 63 | enabled = true 64 | } 65 | logging { 66 | target_bucket = aws_s3_bucket.tf_backend_logs_bucket.id 67 | target_prefix = "log/" 68 | } 69 | tags = { 70 | Description = "Terraform S3 Backend bucket which stores the terraform state for account ${data.aws_caller_identity.current.account_id}." 71 | ManagedByTerraform = "true" 72 | TerraformModule = "terraform-aws-backend" 73 | } 74 | server_side_encryption_configuration { 75 | rule { 76 | apply_server_side_encryption_by_default { 77 | kms_master_key_id = var.kms_key_id 78 | sse_algorithm = var.kms_key_id == "" ? "AES256" : "aws:kms" 79 | } 80 | } 81 | } 82 | lifecycle { 83 | prevent_destroy = true 84 | } 85 | } 86 | 87 | data "aws_iam_policy_document" "tf_backend_bucket_policy" { 88 | statement { 89 | sid = "RequireEncryptedTransport" 90 | effect = "Deny" 91 | actions = [ 92 | "s3:*", 93 | ] 94 | resources = [ 95 | "${aws_s3_bucket.tf_backend_bucket.arn}/*", 96 | ] 97 | condition { 98 | test = "Bool" 99 | variable = "aws:SecureTransport" 100 | values = [ 101 | false, 102 | ] 103 | } 104 | principals { 105 | type = "*" 106 | identifiers = ["*"] 107 | } 108 | } 109 | 110 | statement { 111 | sid = "RequireEncryptedStorage" 112 | effect = "Deny" 113 | actions = [ 114 | "s3:PutObject", 115 | ] 116 | resources = [ 117 | "${aws_s3_bucket.tf_backend_bucket.arn}/*", 118 | ] 119 | condition { 120 | test = "StringNotEquals" 121 | variable = "s3:x-amz-server-side-encryption" 122 | values = [ 123 | var.kms_key_id == "" ? "AES256" : "aws:kms", 124 | ] 125 | } 126 | principals { 127 | type = "*" 128 | identifiers = ["*"] 129 | } 130 | } 131 | } 132 | 133 | resource "aws_s3_bucket_policy" "tf_backend_bucket_policy" { 134 | bucket = aws_s3_bucket.tf_backend_bucket.id 135 | policy = data.aws_iam_policy_document.tf_backend_bucket_policy.json 136 | } 137 | 138 | resource "aws_s3_bucket" "tf_backend_logs_bucket" { 139 | bucket = "${var.backend_bucket}-logs" 140 | acl = "log-delivery-write" 141 | versioning { 142 | enabled = true 143 | } 144 | server_side_encryption_configuration { 145 | rule { 146 | apply_server_side_encryption_by_default { 147 | kms_master_key_id = var.kms_key_id 148 | sse_algorithm = var.kms_key_id == "" ? "AES256" : "aws:kms" 149 | } 150 | } 151 | } 152 | tags = { 153 | Purpose = "Logging bucket for ${var.backend_bucket}" 154 | ManagedByTerraform = "true" 155 | TerraformModule = "terraform-aws-backend" 156 | } 157 | lifecycle { 158 | prevent_destroy = true 159 | } 160 | } 161 | 162 | -------------------------------------------------------------------------------- /outputs.tf: -------------------------------------------------------------------------------- 1 | /* 2 | * Module: terraform-aws-backend 3 | * 4 | * Outputs: 5 | * - s3_backend_bucket_name 6 | * - dynamodb_lock_table_name 7 | * - dynamodb_lock_table_arn 8 | * - dynamodb_lock_table_stream_arn 9 | * - dynamodb_lock_table_stream_label 10 | * - s3_kms_key_id 11 | * 12 | */ 13 | 14 | output "s3_backend_bucket_name" { 15 | value = join( 16 | "", 17 | aws_s3_bucket.tf_backend_bucket.*.id, 18 | aws_s3_bucket.tf_backend_bucket.*.id, 19 | ) 20 | } 21 | 22 | output "dynamodb_lock_table_name" { 23 | value = aws_dynamodb_table.tf_backend_state_lock_table.*.id 24 | } 25 | 26 | output "dynamodb_lock_table_arn" { 27 | value = aws_dynamodb_table.tf_backend_state_lock_table.*.arn 28 | } 29 | 30 | output "dynamodb_lock_stream_arn" { 31 | value = aws_dynamodb_table.tf_backend_state_lock_table.*.stream_arn 32 | } 33 | 34 | output "dynamodb_lock_stream_label" { 35 | value = aws_dynamodb_table.tf_backend_state_lock_table.*.stream_label 36 | } 37 | 38 | -------------------------------------------------------------------------------- /variables.tf: -------------------------------------------------------------------------------- 1 | variable "backend_bucket" { 2 | } 3 | 4 | variable "dynamodb_lock_table_enabled" { 5 | type = bool 6 | default = true 7 | description = "Affects terraform-aws-backend module behavior. Set to false or 0 to prevent this module from creating the DynamoDB table to use for terraform state locking and consistency. More info on locking for aws/s3 backends: https://www.terraform.io/docs/backends/types/s3.html. More information about how terraform handles booleans here: https://www.terraform.io/docs/configuration/variables.html" 8 | } 9 | 10 | variable "dynamodb_lock_table_stream_enabled" { 11 | type = bool 12 | default = false 13 | description = "Affects terraform-aws-backend module behavior. Set to false or 0 to disable DynamoDB Streams for the table. More info on DynamoDB streams: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html. More information about how terraform handles booleans here: https://www.terraform.io/docs/configuration/variables.html" 14 | } 15 | 16 | variable "dynamodb_lock_table_stream_view_type" { 17 | default = "NEW_AND_OLD_IMAGES" 18 | } 19 | 20 | variable "dynamodb_lock_table_name" { 21 | default = "terraform-lock" 22 | } 23 | 24 | variable "lock_table_read_capacity" { 25 | type = number 26 | default = 1 27 | } 28 | 29 | variable "lock_table_write_capacity" { 30 | type = number 31 | default = 1 32 | } 33 | 34 | variable "kms_key_id" { 35 | # Default to absent/blank to use the default aws/s3 aws kms master key 36 | default = "" 37 | description = "The AWS KMS master key ID used for the SSE-KMS encryption on the tf state s3 bucket. If the kms_key_id is specified, the bucket default encryption key management method will be set to aws-kms. If the kms_key_id is not specified (the default), then the default encryption key management method will be set to aes-256 (also known as aws-s3 key management). The default aws/s3 AWS KMS master key is used if this element is absent (the default)." 38 | } 39 | 40 | -------------------------------------------------------------------------------- /versions.tf: -------------------------------------------------------------------------------- 1 | 2 | terraform { 3 | required_version = ">= 0.12" 4 | } 5 | --------------------------------------------------------------------------------