Terraform Template to Create AWS VPC
- Create a folder ‘vpcinaws’
- In this folder create a file called as main.tf (<anyname>.tf). This file main.tf will be our template in this example
- Since we want to create vpc on AWS, lets see how to configure AWS Provider Refer Here
- Provider syntax
provider '<name>' { <arg1> = <value1> .. .. <argn> = <valuen> }
- Navigate to Argument Reference
- Connecting Terraform to your AWS Account (Authentication)
- In this example we will be using static credentials and to create IAM user Refer Here
- Make a note of access key id and secret
- Since we need to create a vpc in mumbai note the region code ‘ap-south-1’
- Add the following block to main.tf
provider "aws" {
region = "ap-south-1"
access_key = "<your access key>"
secret_key = "<your secret key>"
}
- Resource Syntax
resource "<type of resource>" "<name of resource>" {
<arg1> = <value1>
..
..
<argn> = <valuen>
}
- Now google for
terraform <provider> <resource name> resource
now in this case i would google withterraform aws vpc resource
and open resource documentation and navigate to argument reference - After navigating to here and adding resource section to main.tf
provider "aws" {
region = "ap-south-1"
access_key = "<your access key>"
secret_key = "<your secret key>"
}
resource "aws_vpc" "myvpc" {
cidr_block = "10.10.0.0/16"
tags = {
Name = "from terraform"
}
}
- Basic Terraform Workflow
- Now open terminal and cd in to the folder and execute the following
cd ./vpcinaws/
terraform --help
11. Initialize the terraform to download providers
terraform init
- Lets validate our terraform template
terraform validate --help
terraform validate .
13. Lets apply to create the resources
terraform apply --help
terraform apply .
-
Now navigate to AWS VPC to manually verify
-
Now lets try to reexecute apply
-
Now change the tag Name in UI and re execute apply, Terraform tries to set the state to what ever is written in template.
-
Now we can delete this by executing
terraform destroy --help
terraform destroy .
- Experiment count with VPC
provider "aws" {
region = "ap-south-1"
access_key = "<your access key>"
secret_key = "<your secret key>"
}
resource "aws_vpc" "myvpc" {
count = 3
cidr_block = "10.10.0.0/16"
tags = {
Name = "My VPC ${count.index}"
}
}
Terms in Terraform which we used in this Series
- Provider
- Resource
- Argument => input to the Providers/Resources
- init
- apply
- validate
- destroy
- count in resource => number of resources to be created.