-
Notifications
You must be signed in to change notification settings - Fork 130
/
Copy pathstate-file-s3-step-by-step
118 lines (82 loc) · 2.36 KB
/
state-file-s3-step-by-step
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
provider "aws" {
region = "ap-south-1"
}
resource "aws_s3_bucket" "terraform_state" {
bucket = "networknuts-terraform-state-file"
# Prevent accidental deletion of this S3 bucket
lifecycle {
prevent_destroy = true
}
}
#enabling versioning on bucket
resource "aws_s3_bucket_versioning" "enabled" {
bucket = aws_s3_bucket.terraform_state.id
versioning_configuration {
status = "Enabled"
}
}
#enabling encryption
resource "aws_s3_bucket_server_side_encryption_configuration" "default" {
bucket = aws_s3_bucket.terraform_state.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
#no one is allowed to make it public and block acl
resource "aws_s3_bucket_public_access_block" "public_access" {
bucket = aws_s3_bucket.terraform_state.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
# create dynamodb table for locking
resource "aws_dynamodb_table" "terraform_locks" {
name = "networknuts-terraform-state-file-locks"
billing_mode = "PAY_PER_REQUEST"
hash_key = "LockID"
attribute {
name = "LockID"
type = "S"
}
}
## now run - terraform init
## configure terraform to use s3 for state file - vim terrform.tf
terraform {
backend "s3" {
# Replace this with your bucket name!
bucket = "networknuts-terraform-state-file"
key = "global/s3/terraform.tfstate"
region = "ap-south-1"
# Replace this with your DynamoDB table name!
dynamodb_table = "networknuts-terraform-state-file-locks"
encrypt = true
}
}
## run - terraform init
## to check the state file pushing to s3 create
## these output variables
output "s3_bucket_arn" {
value = aws_s3_bucket.terraform_state.arn
description = "The ARN of the S3 bucket"
}
output "dynamodb_table_name" {
value = aws_dynamodb_table.terraform_locks.name
description = "The name of the DynamoDB table"
}
###
#### Partial backends
## create a file - vim backend.hcl
bucket = "networknuts-terraform-state-file"
region = "ap-south-1"
dynamodb_table = "networknuts-terraform-state-file-locks"
encrypt = true
## file ends
# now change the terraform.tf to this
terraform {
backend "s3" {}
}
## run
terraform init -backend-config=backend.hcl