Elastic Cloud Compute (EC2)

The resource type “aws_instance” is used to create, update, and delete EC2 instances on AWS cloud.

resource "aws_instance" "baston-host" {
  ami = "ami-02e680c4540db351e"
  instance_type = "t2.micro"
  tags = {
    Name = "Baston Host"
  }
}

To create an EC2 instance “ami” and “instance_type” are the mandatory arguments. There are other arguments such as 

  • availability_zone
  • key_name
  • security_group
  • subnet_id
  • user_data
  • tenancy
  • associate_public_ip_address
  • network_interface
  • tags and etc.. are the optional arguments and we have to add to customize the instance as per requirement.

Also, it has block device arguments such as

  • volume_type
  • volume_size
  • iops
  • delete_on_termination
  • encrypted and etc.. to attach the additional disks or customize root device properties.

Requirement :

  1. Attach public IP address.
  2. Root device size is 30 GB.
  3. On termination, disk cloud not delete.
  4. Add Baston-Key as Key Name.
provider "aws" {
  region ="us-east-1"
}

resource "aws_instance" "baston" {
  ami ="ami-009d6802948d06e52"
  instance_type ="t2.micro"
  key_name = "baston-key"
  associate_public_ip_address = true
  root_block_device {
    volume_type = "gp2"
    volume_size = "30"
    delete_on_termination = false
  }
  tags = {
    Name = "BastonHost"
  }
}

output "IPAddress" {
  value = "${aws_instance.baston.public_ip}"
}

Make sure have Baston-Key already created and .pem file available with you. If not create it manually and download for now.

Once instance created successfully, the output will display the IP Address.

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

Outputs:

IPAddress = 3.80.169.59

You can now connect to your EC2 instance via ssh as follows :

ssh -i "baston-key.pem" ec2-user@3.80.169.59

If you got connect timeout error, go to EC2 console and allow ssh (port 22) in the security_group inbound rules. We will see about the security_groups in VPC concept.

After destroyed the EC2 instance, make sure to delete the disks manually from the EC2 console. Because we have disable delete on termination property. If you forgot to delete, It will cost to you.

Advertisements

Learn Technology

%d bloggers like this: