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 

Friday, January 1, 2021

Terraform : Working with modules

Terraform modules is the best way to reuse your terraform resources. 

Create a following folder structure:

  • terraform-app
  • terraform-app/modules
  • terraform-app/dev
  • terraform-app/prod
So terraform-app/modules will have the template kind of code which you can reuse it in your dev environment & prod environment.

In this example we will create a VPC & Subnet template which can be reused in dev & prod.

lets create network.tf file inside terraform/modules, which will have VPC & Subnet templates, Will be using output to print and to associate it with Subnet.

Now lets create variables.tfvars file

Lets switch the directory and create a main.tf file inside terraform-app/dev which will make use of the modules which we have created above.

Also lets create another main.tf file inside terraform-app/prod

So the main.tf file under dev will create a VPC with CIDR block 192.168.0.0/16 and the main.tf file under prod will create a VPC with default CIDR block 10.0.0.0/16 which is defined under variables.tfvars 

Terraform Cheat Sheet [WIP]

Installing Terraform