DevOps Classroom Series – 27/May/2020

Scenario: Create a EC2 instance in AWS

  • Creating EC2 instance in AWS Watch Here
  • For creating Ec2 instance. For any resource have a habit of knowing inputs and outputs before you create/provision in terraform
    • Inputs:
      1. Image ID
      2. Region
      3. Security Group
      4. Key Value Pair
      5. Subnet-id (VPC and AZ)
      6. instance type (size) => t2.micro
    • Outputs
      1. Id
      2. Ipaddress
      3. DNS Name
  • Navigate to the docs page over here
  • Created a new directory with provider.tf and computeresources.tf. In computeresoruces.tf
resource "aws_instance" "firstec2" {
    ami                             = "ami-003634241a8fcdec0"
    instance_type                   = "t2.micro"
    key_name                        = "ansible"
    vpc_security_group_ids          = [ "sg-003772772f5073f26" ]
    associate_public_ip_address     = true
    tags                            = {
        Name                        = "firstec2"
    }
}

  • Provider.tf will have
provider "aws" {

}
  • Now apply terraform to create ec2 instance which will work.
  • This way is not suggestable as reusing this template on other aws accounts might not workout as this template is specific Preview
  • Lets try to make this template generic, by adding input variables
  • Lets add a new file inputs.tf with the following content
variable "securitygroupid" {
    type    = string
}

variable "keyname" { 
    type    = string
}

  • And the main.tf looks like
provider "aws" {
    
}

resource "aws_instance" "firstec2" {
    ami                             = "ami-003634241a8fcdec0"
    instance_type                   = "t2.micro"
    key_name                        = var.keyname
    vpc_security_group_ids          = [ var.securitygroupid ]
    associate_public_ip_address     = true
    tags                            = {
        Name                        = "firstec2"
    }
}

Preview Preview

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin