Create Simple EC2 Instance Using Terraform AWS
Tags: webdev, devops, aws, terraform
Published: 2021-11-08 03:44:46

Terraform is an open-source infrastructure as code software tool that enables you to safely and predictably create, change, and improve infrastructure.

### Prerequisites
To follow this tutorial you will need:
    - The [Terraform CLI (0.14.9+)](https://learn.hashicorp.com/tutorials/terraform/install-cli?in=terraform/aws-get-started) installed.
    - The [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed.
    - An AWS account.
    - Your AWS credentials. [You can create a new Access Key on this page](https://console.aws.amazon.com/iam/home?#/security_credentials).
    - Create "Key Pair" on your AWS instances and save .pem file

### Configure AWS Account
The AWS CLI supports using any of multiple named profiles that are stored in the config and credentials files. You can configure additional profiles by using aws configure with the --profile option, or by adding entries to the config and credentials files.

The following example shows a credentials file with two profiles. The first [default] is used when you run a AWS CLI command with no profile. The second is used when you run a AWS CLI command with the --profile user1 parameter.
```
    ~/.aws/credentials (Linux & Mac) or %USERPROFILE%\.aws\credentials (Windows)
```
Edit your aws credentials
```
[default]
aws_access_key_id=AKIAIOSFODNN7EXAMPLE
aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

[user1]
aws_access_key_id=AKIAI44QH8DHBEXAMPLE
aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY
```

Edit your aws config
```
[default]
region=us-west-2
output=json

[profile user1]
region=us-east-1
output=text
```

### Initialize Terraform
Create directory for your configuration.
```bash
mkdir learn-terraform-aws-instance
```
Change into directory.
```
cd learn-terraform-aws-instance
```
Create terraform file.
```
touch main.tf
```
Open main.tf in your text editor, paste in the configuration below, and save the file.
```
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }
}

### Provider
provider "aws" {
  profile = "your_aws_config_profile"
  region  =  "ap-southeast-1"
}

### ECS Security Group - ALB -> ECS, SSH -> ECS
resource "aws_security_group" "ecs_service_sg" {
  name        = "ecs_service_sg"
  description = "Allow HTTP, HTTPS and SSH traffic"

  ingress {
    description = "SSH"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    description = "HTTPS"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    description = "HTTP"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "global-ecs-service-sg-tf"
  }
}

### EC Instance
resource "aws_instance" "sample_instance_name" {
  ### Ami for ubuntu 18.x.x
  ami           = "ami-0907c2c44ea451f84"
  instance_type = "t2.micro"
  key_name      = "your_key_pair_name"

  ### Get From aws_security_group
  vpc_security_group_ids = [
    aws_security_group.ecs_service_sg.id
  ]

  tags = {
    Name = "SampleTagYourInstanceName"
  }
}


```
Initialize your terraform project.
```
terraform init
```
Deploy terraform
```
terraform apply
```
Destroy terraform
```
terraform destroy
```
Change Terraform infrastructure
- Change your configuration on your .tf file  & saved it.
- Reinit terraform
    ```
    terraform init
    ```
- Re apply
    ```
    terraform apply
    ```
- Your prev infrastructure will destroy , and terraform create the new one.
- Now Yout instance have been created, check your aws instance dashboard
- To access your instance use SSH , from your key pair

### Access Via SSH
Linux & MacOS usage
1. Open an SSH client.
2. Locate your private key file. The key used to launch this instance is your_key.pem
3. Run this command, if necessary, to ensure your key is not publicly viewable.
    ```
    chmod 400 your_key.pem
    ```
4. Connect to your instance using its Public DNS:
    ```
    your_public_ip4_dns or public_ip4_ip_address
    ```
5. Sample access.
    ```
        ssh -i "your_key.pem" ubuntu@your_public_ip4_dns
    ```
Windows usage
1. Download Termius
2. Create new host
3. Paste your_public_ip4_dns to "address"
4. Load your_key.pem
5. And Connect.

## Notes
Source:
* [Aws change config](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html)
* [Terraform Build](https://learn.hashicorp.com/tutorials/terraform/aws-change?in=terraform/aws-get-started)