How to Create AWS EC2 by Terraform
Table of Contents
- Introduction
- Configure AWS
- Visual Studio Code Extension for HashiCorp Terraform
- Terraform Commands
- Other
- Conclusion
Introduction
Prerequisites:
- Terraform CLI
- AWS CLI
- AWS Account
- VS Code Extension: HashiCorp Terraform
Configure AWS
This will be the first step for this tutorial. You'll need to have an AWS account, create a user, and have the access key and secret configured so we can run Terraform with the correctly configured AWS credentials later.
Install AWS CLI
This blog skips how to install AWS CLI on your local machine, but you can reference how to get started with AWS CLI.
Verify AWS CLI
Check that AWS CLI is working by typing the below command.
aws --version
Retrieve AWS Access Keys
If you don't have an AWS user created, you can log in to AWS and create a new user. Once you create a new user, go to the Security Credentials section and retrieve the access key and secret key.
- Create an AWS user
- Create Security Credentials by retrieving the AWS access keys
- Add a role to the AWS user (to make it simple for this blog, we're adding the AmazonEC2FullAccess permission for testing)
Once you have the access and secret keys, use aws configure to set them.
Now, for the below steps, once you run Terraform, it will create resources under this AWS account.
Visual Studio Code Extension for HashiCorp Terraform
This blog uses VS Code to modify Terraform files and the VS Code extension HashiCorp Terraform for Terraform editing. It is a great tool that provides IntelliSense for editing Terraform.
- VS Code Extension: HashiCorp Terraform
Terraform Commands
List all the available commands for executing Terraform.
terraform -help
Prepare the local directory for other commands.
terraform init
terraform validate
terraform fmt
terraform apply
terraform destroy
terraform show
terraform state list
Other
Get the public key by key pair name:
aws ec2 describe-key-pairs --key-names test --include-public-key
Conclusion
With Terraform and the AWS CLI configured, you can easily create and manage AWS EC2 instances as infrastructure as code. Use terraform init, terraform apply, and terraform destroy to manage the lifecycle of your resources.