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:
- Image ID
- Region
- Security Group
- Key Value Pair
- Subnet-id (VPC and AZ)
- instance type (size) => t2.micro
- Outputs
- Id
- Ipaddress
- DNS Name
- Inputs:
- 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
- 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"
}
}