100-Days-Of-DevOps-Challenge-KodeKloud

Create EC2 Instance Using Terraform

The Nautilus DevOps team is strategizing the migration of a portion of their infrastructure to the AWS cloud. Recognizing the scale of this undertaking, they have opted to approach the migration in incremental steps rather than as a single massive transition. To achieve this, they have segmented large tasks into smaller, more manageable units.

For this task, create an EC2 instance using Terraform with the following requirements:

  1. The name of the instance must be xfusion-ec2.

  2. Use the Amazon Linux ami-0c101f26f147fa7fd to launch this instance.

  3. The Instance type must be t2.micro.

  4. Create a new RSA key named xfusion-kp.

  5. Attach the default (available by default) security group.

The Terraform working directory is /home/bob/terraform. Create the main.tf file (do not create a different .tf file) to provision the instance.

Note: Right-click under the EXPLORER section in VS Code and select Open in Integrated Terminal to launch the terminal.

Steps

  1. Let’s create the main.tf file copy paste the contents from this terraform file. In our main.tf file, we have used some resource block to generate ssh key, create key pair in aws and launch ec2 instance.

    • tls_private_key resource block to generate an RSA private key
    • aws_key_pair resource block to create key pair at aws cloud.
    • aws_instance to launch the ec2 instance
  2. For this main.tf file, we need some variables. Let’s create variables.tf and add following variables:

     variable "prefix" {
         default = "xfusion"
     }
    
     variable "ami_id" {
         default = "ami-0c101f26f147fa7fd"
     }
    
     variable "instance_type" {
         default = "t2.micro"
     }
    

    Make sure you have updated prefix default value according to your task.

  3. This is optional. You can create a outputs.tf file to display the ec2 instance information.

     output "ec2_info" {
         value = {
             public_ip = aws_instance.ec2.public_ip
             private_ip = aws_instance.ec2.private_ip
         }
     }
    
  4. Let’s run the terraform commands:

     terraform init
     terraform plan
     terraform apply -auto-approve
    

Video Tutorial

Referrences

Good To Know