Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I launch an AWS EC2 instance using an AWS launch template with Terraform?

I am trying to build an AWS EC2 redhat instance using an AWS launch template with Terraform.

I can create an launch template with a call to Terraform's resource aws_launch_template. My question is how do I use Terraform to build an EC2 server with the created launch template?

What Terraform aws provider resource do I call?

Many thanks for your help!

like image 965
Johnson Avatar asked Dec 12 '18 19:12

Johnson


People also ask

What is the difference between AWS launch configuration and launch template?

However, defining a launch template instead of a launch configuration allows you to have multiple versions of a launch template. With versioning of launch templates, you can create a subset of the full set of parameters. Then, you can reuse it to create other versions of the same launch template.

Can we start and stop EC2 instance using terraform?

The first step is to create an IAM policy that allows the following actions: Start an EC2 instance, Stop an EC2 instance, and list EC2 instances. This policy can be created with the below terraform resource definition.


2 Answers

Welcome to Stack Overflow!

You can create an aws_autoscaling_group resource to make use of your new Launch Template. Please see the example here for more details.

Code:

resource "aws_launch_template" "foobar" {
  name_prefix   = "foobar"
  image_id      = "ami-1a2b3c"
  instance_type = "t2.micro"
}

resource "aws_autoscaling_group" "bar" {
  availability_zones = ["us-east-1a"]
  desired_capacity   = 1
  max_size           = 1
  min_size           = 1

  launch_template = {
    id      = "${aws_launch_template.foobar.id}"
    version = "$$Latest"
  }
}
like image 97
Adil B Avatar answered Oct 19 '22 00:10

Adil B


Here is the code I used to build an EC2 image with a launch template.

variable "aws_access_key" {}
variable "aws_secret_key" {}

provider "aws" {
    access_key = "${var.aws_access_key}"
    secret_key = "${var.aws_secret_key}"
    region     = "us-east-1"
}

resource "aws_launch_template" "foobar" {
    name_prefix   = "foobar"
    image_id      = "ami-0080e4c5bc078760e"
    instance_type = "t2.micro"
}

resource "aws_autoscaling_group" "bar" {
    availability_zones = ["us-east-1a"]
    desired_capacity   = 1
    max_size           = 1
    min_size           = 1

    launch_template = {
      id      = "${aws_launch_template.foobar.id}"
      version = "$$Latest"
    }
}

Many thanks Adil!

like image 36
Johnson Avatar answered Oct 19 '22 01:10

Johnson