Wednesday, January 6, 2021

Terraform: Backend as S3

Instead of keeping the terraform state file locally we can store it on a remote location as well. In this blog we are going to store this state file in AWS S3 bucket.

Lets create a main.tf file:
Now lets run terraform init --> terraform plan --> terraform apply

If you look closely into your directory you will see terraform.tfstate still exist and upon opening it you will still see data inside it. In order to move this state file into remote location i.e in our case storing it on S3, we will need to create one bucket in S3. 
Eg: Bucket Name: abhaybuckets
Now lets add required permission to the bucket:

Now that we have created a bucket lets add the backend configuration to store the state file in S3. (Add the configuration in same main.tf file)
We will need to run terraform init again to reconfigure the state file location changes. While executing this command you will notice that terraform will prompt a question whether do you want to move the existing file to S3? Upon agreeing it will store the existing state file to S3 and the data inside the local terraform.tfstate file will be erased.

Please note: You can store your credentials either in profile or in environment variable. If you are storing your credentials inside provider block you may get the following error:

terraform backend s3 Error: NoCredentialProviders: no valid providers in chain. Deprecated.         For verbose messaging see aws.Config.CredentialsChainVerboseErrors 

No comments:

Post a Comment

Terraform Cheat Sheet [WIP]

Installing Terraform