How Do You Use Terraform to Create AWS Servers?

Problem scenario
You want to use Terraform to deploy EC-2 instances (VMs in AWS).  How do you do this?

Solution
These directions can work on a Linux server in your enterprise, a Linux server in Azure or a Linux server in AWS.

1.  Install Terraform.  See this link if you do not know how.

2.  Create a file like this called contint.tf with this as the content:

provider "aws" {
  access_key = "accessKeyHere"
  secret_key = "secretKeyHere"
  region     = "us-east-2"
}

resource "aws_instance" "example" {
  ami           = "ami-0b1e356e"
  instance_type = "t2.micro"
}

3.  Replace accessKeyHere with your AWS account's access key.  Replace secretKeyHere with your AWS account's secret key.  (You may also change the Amazon Machine ID if you desire.)

To find the AWS Access Key ID and AWS Secret Access Key, in the AWS console, click on your name in the upper right hand corner. Click on "My Security Credentials."  Click "Create New Access Key."  Then click "Show Access Key."   

Save the changes to the .tf file.

4.  From the directory with the .tf file, run these commands one at a time:

terraform init
terraform apply

5.  You are done.  The above steps will create an server (EC2 instance) in the "Ohio" region (also known as the us-east-2 region).  After the server is created you can create another server and delete the one you just created by changing the word "example" of basic.tf, then running the command "terraform apply" with no quotes.  Invoking "terraform apply" in a directory with a .tf file that is the same except the word "example" will do two things: delete the server that was created and create a new one.  If you want to delete the AWS server, you can run this command:

terraform destroy

# The above command will destroy terraform-provisioned infrastructure.

Leave a comment

Your email address will not be published. Required fields are marked *