-
Notifications
You must be signed in to change notification settings - Fork 131
/
Copy pathstate-file-on-s3
121 lines (95 loc) · 2.42 KB
/
state-file-on-s3
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
116
117
118
119
120
121
Create a separate directory under the location you are working
# mkdir remote-state
# cd remote-state
#########
Step #1 - Create a .tf file that will create s3 bucket aws
#########
vim s3-setup.tf
# with these contents
# ----- file s3-setup.tf STARTS here
resource "aws_s3_bucket" "terraform-state-storage-s3" {
bucket = "networknuts-terraform-state-s3"
region = "ap-south-1"
versioning {
# enable with caution, makes deleting S3 buckets tricky
enabled = false
}
lifecycle {
prevent_destroy = true
}
tags = {
name = "S3 Remote Terraform State Store"
proj = "networknuts"
env = "prod"
}
}
# create a DynamoDB table for locking the state file
resource "aws_dynamodb_table" "dynamodb-terraform-state-lock" {
name = "networknuts-iac-terraform-state-lock-dynamo"
hash_key = "LockID"
read_capacity = 20
write_capacity = 20
attribute {
name = "LockID"
type = "S"
}
tags = {
name = "DynamoDB Terraform State Lock Table"
proj = "networknuts"
env = "prod"
}
}
# --- file s3-setup.tf ENDS here
Run:
# terraform plan
# terraform init
# terraform apply
#########
Step #2 - Create a file state-location.tf, which will change state file location from local to s3
#########
vim state-location.tf
# --- file state-location.tf STARTS here
provider "aws" {
region = "ap-south-1"
}
# store tfstate in s3 and locking information in DynamoDB
terraform {
backend "s3" {
encrypt = true
# cannot contain interpolations
bucket = "networknuts-terraform-state-s3"
region = "ap-south-1"
#first run terraform init and terraform apply with comment against dynamodb_table
#then run it again after removing the comment
#dynamodb_table = "networknuts-iac-terraform-state-lock-dynamo"
key = "terraform-state/terraform.tfstate"
}
}
# --- file state-location.tf ENDS here
Run:
# terraform plan
# terraform init
# terraform apply
# --- now go and uncomment the dynanodb_table line
Run:
# terraform plan
# terraform init
# terraform apply
#########
Step #3 - Create a resource and check the .tfstate file on AWS S3
#########
vim webserver.tf
# --- file webserver.tf STARTS here
resource "aws_instance" "webserver" {
ami = "ami-0b5bff6d9495eff69"
instance_type = "t2.micro"
tags = {
Owner = "serverterra"
}
}
# --- file webserver.tf ENDS here
Run:
# terraform plan
# terraform init (if prompted)
# terraform apply
#GO TO AWS dashboard and check .tfstate file