How To Create AWS Ec2 Instance Using Terraform | Terraform Ec2 Module

Steps to Create AWS Ec2 Instance Using Terraform

As everyone knows terraform is infrastructure as code tool so using terraform scripts or templates we can deploy resources in aws or any other cloud. In this post we are going to see how to create or launch aws ec2 instance using terraform script or template.

Create a Directory for Terraform Scripts

Before going to create terraform templates, Create one directory to keep all your terraform scripts. Here i am going to create devops directory to keep all my terraform scripts. In this directory only i will store or place my terraform scripts.

root@ip-172-31-37-35:~# mkdir devops

root@ip-172-31-37-35:~# cd devops/

root@ip-172-31-37-35:~/devops# pwd

/root/devops

Establish a Connection Between Terraform to Your Aws Account

To establish a connection between terraform and your aws account we have to create one file and place your aws account accesskey and secret key in that file with the below format. You can create the file with any name but the file extension should be .tf only. Since terraform will find the scripts with .tf extension only.

root@ip-172-31-37-35:~/devops# 

cat provider.tf


provider "aws" {
  access_key = "DFNIAERUNJRIHNFOJXFK"
  secret_key = "J6nd8dODNWYDNJMkfXINEYNyBBJDNFbwbqa+FFFjg"
  region     = "us-east-1"
}

follow the same format when you are creating provider.tf and replace the accesskey and secretekeys with your aws acoount keys. You can find here How to create aws access key and secret key  In above file i mentioned region as us-east-1, so the ec2 instance which we are going to create in this demo, will be created in this region only. After creating ec2 instance using terraform script or teamplate, login to your aws console and you can find the ec2 instance in the region which you mentioned in the above provider.tf template.

Initialize The Terrraform

Execute terraform init command, it will download and install aws provider for your terraform scripts.

root@ip-172-31-37-35:~/devops# terraform init

Initializing the backend...

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "aws" (hashicorp/aws) 2.44.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.44"

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.

Now we have successfully initialized the terraform in devops directory. Now we can execute terraform scripts and create ec2 instance in aws using terraform.

Create AWS Ec2 Instance Terraform Template

To lunch or deploy ec2 instance in aws with terraform we have to create aws ec2 terraform template or script. Here i created a terrafrom temaplate to lunch aws ec2 instance and named it as ec2.tf. You can create the file with any name but extension should be .tf only.

root@ip-172-31-37-35:~/devops# cat ec2.tf


resource "aws_instance" "web" {
  ami           = "ami-00068cd7555f543d5"
  instance_type = "t2.micro"

  tags = {
    Name = "HelloWorld"
  }
}

using this terraform template we can create aws ec2 instance in your aws account.

Terraform apply

To create aws ec2 instance using terraform script we have we have to execute terraform apply command. This command will read your terraform scripts and it will create the resources whatever you mentioned in the terraform scipts. in above file you can see we mentioned only aws_instance so it will create only ec2 instance in aws.

if you enter the terraform apply command it will ask/prompt you to enter ‘yes’ to create reources in aws. if you enter yes it will create aws ec2 instance.

root@ip-172-31-37-35:~/devops# 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.web will be created
  + resource "aws_instance" "web" {
      + ami                          = "ami-00068cd7555f543d5"
      + 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                     = (known after apply)
      + 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)
      + tags                         = {
          + "Name" = "HelloWorld"
        }
      + 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)
          + kms_key_id            = (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)
          + encrypted             = (known after apply)
          + iops                  = (known after apply)
          + kms_key_id            = (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.web: Creating...
aws_instance.web: Still creating... [10s elapsed]
aws_instance.web: Still creating... [20s elapsed]
aws_instance.web: Still creating... [30s elapsed]
aws_instance.web: Creation complete after 33s [id=i-070936b9abf6110bc]

That’s it we have successfully created or launched aws ec2 instance using terraform template or script.  you can verify the ec2 instance by logging to aws console ec2 dashboard.

after applying terraform, How terraform will know the state of our infrastructure, that’s where Terraform state comes into picture. terraform will store all the state of our infrastructure in a file called terraform.tfstate.

Destroy Your Resources in AWS

Just now we have seen how to launch ec2 instance in aws with terraform script. Now let’s see How To Remove or terminate ec2 instance in aws. To remove resources in aws with terraform we use terraform destroy command. This command will remove your entire aws resources that we created with terraform. Once you execute this command in command prompt it will ask/prompt you for yes to destroy the resources in aws, write yes and hit enter your resources in aws will be removed.

root@ip-172-31-37-35:~/devops# terraform destroy
aws_instance.web: Refreshing state... [id=i-070936b9abf6110bc]

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.web will be destroyed
  - resource "aws_instance" "web" {
      - ami                          = "ami-00068cd7555f543d5" -> null
      - arn                          = "arn:aws:ec2:us-east-1:787645912603:instance/i-070936b9abf6110bc" -> null
      - associate_public_ip_address  = true -> null
      - availability_zone            = "us-east-1b" -> 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-070936b9abf6110bc" -> null
      - instance_state               = "running" -> null
      - instance_type                = "t2.micro" -> null
      - ipv6_address_count           = 0 -> null
      - ipv6_addresses               = [] -> null
      - monitoring                   = false -> null
      - primary_network_interface_id = "eni-05bbd42eadb14678b" -> null
      - private_dns                  = "ip-172-31-37-183.ec2.internal" -> null
      - private_ip                   = "172.31.37.183" -> null
      - public_dns                   = "ec2-3-84-90-145.compute-1.amazonaws.com" -> null
      - public_ip                    = "3.84.90.145" -> null
      - security_groups              = [
          - "default",
        ] -> null
      - source_dest_check            = true -> null
      - subnet_id                    = "subnet-1ecf9e42" -> null
      - tags                         = {
          - "Name" = "HelloWorld"
        } -> null
      - tenancy                      = "default" -> null
      - volume_tags                  = {} -> null
      - vpc_security_group_ids       = [
          - "sg-5184d50a",
        ] -> null

      - credit_specification {
          - cpu_credits = "standard" -> null
        }

      - root_block_device {
          - delete_on_termination = true -> null
          - encrypted             = false -> null
          - iops                  = 100 -> null
          - volume_id             = "vol-03ca5733fc67130fb" -> 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.web: Destroying... [id=i-070936b9abf6110bc]
aws_instance.web: Still destroying... [id=i-070936b9abf6110bc, 10s elapsed]
aws_instance.web: Still destroying... [id=i-070936b9abf6110bc, 20s elapsed]
aws_instance.web: Destruction complete after 29s

Destroy complete! Resources: 1 destroyed.

 

 

  • terraform ec2 example github
  • create aws ec2 instance using terraform
  • terraform create ec2 instance
  • deploy ec2 insatnce using terraform
  • terraform ec2 instance example
  • terraform-aws-modules/ec2-instance/aws
  • launch ec2 insatnce using terraform
  • terraform ec2 module

Leave a Reply

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