How to Create AWS EC2 by Terraform

2023/2/32 min read
bookmark this
Responsive image
  • 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 AWS account and create user and have the access key, secret configured, so we can run the terraform with the correct configured aws later.

Install AWS Cli

This blog is skipping how to install AWS Cli at your local, but you can reference here for (how to getting start with AWS Cli)['https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html'].

Verify AWS Cli

Checking AWS Cli is working or not by typing below command.

aws --version

Retrieve AWS access keys

If you don't have a AWS user created, you can login in to AWS and create a new user, once create a new user then go to the Security Credentials section and retrieve access key and secret key.

  • Create a AWS User
  • Create Security Credentials by retrieve AWS access keys
  • Add Role to the AWS User (to make it simple at this blog, here adding the AmazonEC2FullAccess for testing.)

Once have the Access and Secret key, then use the aws configure to set access and secret key.

Now, for the below steps once run the terraform, will create resource under this AWS account.

Visual Code Extension for HashiCorp Terraform

THis blog use VS Code to modify terraform, and use the VS Code extension HashiCorp Terraform for terraform editing. It is great tool, providing intellisense for editing Terraform.

  • VS Code Extension: HashiCorp Terraform

List all the available commands for execute terraform.

terraform -help

The command to run, prepare the local directory for other commands.

terraform init
terraform validate
terraform fmt
terraform apply
terraform destroy
terraform show
terraform state list

Other

Get public key by key pair name

aws ec2 describe-key-pairs --key-names test --include-public-key