Build EC2 Infrastructure using Terraform

We will use Infrastructure automation tool Terraform create an EC2 image in region ‘us-east-1’ with ami id as ‘ami-408c7f28’. If you need to create the ec2 instance in any other region you would need another AMI ID, since AMI’s are region specific.

1. Download and Install Terraform for Linux from the Terraform Website : https://www.terraform.io/downloads.html

Note : Install awscli and configure your AWS credentials before we begin

On Linux the download is a zip file containing only 1 file. Unzip to any directory and copy the file ‘terraform’ to /usr/bin


2. Create a Terraform configuration file in your current directory


$ vim ec2.tf

provider “aws” {
  region     = “us-east-1”
}
resource “aws_instance” “example” {
  ami           = “ami-2757f631”
  instance_type = “t2.micro”
  key_name      = “us-east-1-keypair”
}


3. Initiate Terraform

$ terraform init
Initializing modules…
– redshift in ../..
Downloading terraform-aws-modules/security-group/aws 3.0.1 for sg…
– sg in .terraform/modules/sg/terraform-aws-modules-terraform-aws-security-group-a332a3b/modules/redshift
– sg.sg in .terraform/modules/sg/terraform-aws-modules-terraform-aws-security-group-a332a3b
Downloading terraform-aws-modules/vpc/aws 2.5.0 for vpc…
– vpc in .terraform/modules/vpc/terraform-aws-modules-terraform-aws-vpc-6c31234

Initializing the backend…

Initializing provider plugins…
– Checking for available provider plugins…
– Downloading plugin for provider “aws” (terraform-providers/aws) 2.14.0…

The following providers do not have any version constraints in configuration,
so the latest version was installed.

To prevent automatic upgrades to new major versions that may contain breaking
changes, it is recommended to add version = “…” constraints to the
corresponding provider blocks in configuration, with the constraint strings
suggested below.

* provider.aws: version = “~> 2.14”

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running “terraform plan” to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.


4. Apply Terraform Configuration

Note 1: From Terraform 0.11 and above you do not have to run ‘terraform plan’ command

Note 2 : For security purpose it is not good practise to store access_key or secret_key in the .tf file. If you have installed awscli then Terraform will take your AWS credentials from ‘~/.aws/credentials’ or IAM credentials.

$ terraform apply

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_instance.example will be created
  + resource “aws_instance” “example” {
      + ami                          = “ami-2757f631”
      + arn                          = (known after apply)
      + associate_public_ip_address  = (known after apply)
      + availability_zone            = (known after apply)
      + cpu_core_count               = (known after apply)
      + cpu_threads_per_core         = (known after apply)
      + get_password_data            = false
      + host_id                      = (known after apply)
      + id                           = (known after apply)
      + instance_state               = (known after apply)
      + instance_type                = “t2.micro”
      + ipv6_address_count           = (known after apply)
      + ipv6_addresses               = (known after apply)
      + key_name                     = “us-east-1-keypair”
      + network_interface_id         = (known after apply)
      + password_data                = (known after apply)
      + placement_group              = (known after apply)
      + primary_network_interface_id = (known after apply)
      + private_dns                  = (known after apply)
      + private_ip                   = (known after apply)
      + public_dns                   = (known after apply)
      + public_ip                    = (known after apply)
      + security_groups              = (known after apply)
      + source_dest_check            = true
      + subnet_id                    = (known after apply)
      + tenancy                      = (known after apply)
      + volume_tags                  = (known after apply)
      + vpc_security_group_ids       = (known after apply)

      + ebs_block_device {
          + delete_on_termination = (known after apply)
          + device_name           = (known after apply)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + snapshot_id           = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }

      + ephemeral_block_device {
          + device_name  = (known after apply)
          + no_device    = (known after apply)
          + virtual_name = (known after apply)
        }

      + network_interface {
          + delete_on_termination = (known after apply)
          + device_index          = (known after apply)
          + network_interface_id  = (known after apply)
        }

      + root_block_device {
          + delete_on_termination = (known after apply)
          + iops                  = (known after apply)
          + volume_id             = (known after apply)
          + volume_size           = (known after apply)
          + volume_type           = (known after apply)
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only ‘yes’ will be accepted to approve.

  Enter a value: yes
 
  aws_instance.example: Creating…
aws_instance.example: Still creating… [10s elapsed]
aws_instance.example: Still creating… [20s elapsed]
aws_instance.example: Still creating… [30s elapsed]
aws_instance.example: Still creating… [40s elapsed]
aws_instance.example: Creation complete after 42s [id=i-0cf9d04e3e926b975]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.



5. Check the state of your infrastructure


You can go check in your AWS console > EC2 Dashboard and you will see the instance. To see it from terraform run the below command

$ terraform show

# aws_instance.example:
resource “aws_instance” “example” {
    ami                          = “ami-2757f631”
    arn                          = “arn:aws:ec2:us-east-1:775867435088:instance/i-0cf9d04e3e926b975”
    associate_public_ip_address  = true
    availability_zone            = “us-east-1c”
    cpu_core_count               = 1
    cpu_threads_per_core         = 1
    disable_api_termination      = false
    ebs_optimized                = false
    get_password_data            = false
    id                           = “i-0cf9d04e3e926b975”
    instance_state               = “running”
    instance_type                = “t2.micro”
    ipv6_address_count           = 0
    ipv6_addresses               = []
    key_name                     = “us-east-1-keypair”
    monitoring                   = false
    primary_network_interface_id = “eni-0f1f6798c37c9d210”
    private_dns                  = “ip-172-31-80-192.ec2.internal”
    private_ip                   = “172.31.80.192”
    public_dns                   = “ec2-100-24-2-45.compute-1.amazonaws.com”
    public_ip                    = “100.24.2.45”
    security_groups              = [
        “default”,
    ]
    source_dest_check            = true
    subnet_id                    = “subnet-e5790ecb”
    tenancy                      = “default”
    volume_tags                  = {}
    vpc_security_group_ids       = [
        “sg-55c2f911”,
    ]

    credit_specification {
        cpu_credits = “standard”
    }

    root_block_device {
        delete_on_termination = true
        iops                  = 100
        volume_id             = “vol-0b061617e365e8123”
        volume_size           = 8
        volume_type           = “gp2”
    }
}


6. Destroy the Ec2 instance
The beauty of terraform is it maintains state of your infrastructure. You can remove the ec2 instance by running just 1 simple command

$ terraform destroy

aws_instance.example: Refreshing state… [id=i-0cf9d04e3e926b975]

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  – destroy

Terraform will perform the following actions:

  # aws_instance.example will be destroyed
  – resource “aws_instance” “example” {
      – ami                          = “ami-2757f631” -> null
      – arn                          = “arn:aws:ec2:us-east-1:775867435088:instance/i-0cf9d04e3e926b975” -> null
      – associate_public_ip_address  = true -> null
      – availability_zone            = “us-east-1c” -> null
      – cpu_core_count               = 1 -> null
      – cpu_threads_per_core         = 1 -> null
      – disable_api_termination      = false -> null
      – ebs_optimized                = false -> null
      – get_password_data            = false -> null
      – id                           = “i-0cf9d04e3e926b975” -> null
      – instance_state               = “running” -> null
      – instance_type                = “t2.micro” -> null
      – ipv6_address_count           = 0 -> null
      – ipv6_addresses               = [] -> null
      – key_name                     = “us-east-1-keypair” -> null
      – monitoring                   = false -> null
      – primary_network_interface_id = “eni-0f1f6798c37c9d210” -> null
      – private_dns                  = “ip-172-31-80-192.ec2.internal” -> null
      – private_ip                   = “172.31.80.192” -> null
      – public_dns                   = “ec2-100-24-2-45.compute-1.amazonaws.com” -> null
      – public_ip                    = “100.24.2.45” -> null
      – security_groups              = [
          – “default”,
        ] -> null
      – source_dest_check            = true -> null
      – subnet_id                    = “subnet-e5790ecb” -> null
      – tags                         = {} -> null
      – tenancy                      = “default” -> null
      – volume_tags                  = {} -> null
      – vpc_security_group_ids       = [
          – “sg-55c2f911”,
        ] -> null

      – credit_specification {
          – cpu_credits = “standard” -> null
        }

      – root_block_device {
          – delete_on_termination = true -> null
          – iops                  = 100 -> null
          – volume_id             = “vol-0b061617e365e8123” -> null
          – volume_size           = 8 -> null
          – volume_type           = “gp2” -> null
        }
    }

Plan: 0 to add, 0 to change, 1 to destroy.

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only ‘yes’ will be accepted to confirm.

  Enter a value: yes

aws_instance.example: Destroying… [id=i-0cf9d04e3e926b975]
aws_instance.example: Still destroying… [id=i-0cf9d04e3e926b975, 10s elapsed]
aws_instance.example: Still destroying… [id=i-0cf9d04e3e926b975, 20s elapsed]
aws_instance.example: Still destroying… [id=i-0cf9d04e3e926b975, 30s elapsed]
aws_instance.example: Destruction complete after 34s

Destroy complete! Resources: 1 destroyed.

Category: AWS

Tags:

Leave a Reply

Article by: Shadab Mohammad