Friday, February 4, 2022

[SOLVED] Terraform one EC2 instance with two subnets

Issue

I need to create one EC2 and associate 2 subnets to it.

variables.tf

variable "aws_subnet_id_this" {
  description = "Subnet ID"
  default = ["subnet-09df122a4faee8882", "subnet-2fcc756f02ddb4b62"]
}

main.tf

resource "aws_instance" "test" {
  ami                         = var.ami_id
  instance_type               = var.ec2_instance_type
  subnet_id                   = var.aws_subnet_id_this
  key_name                    = var.pki_name
  vpc_security_group_ids      = [aws_security_group.Allow_SSH_in.id]
}

Error:

Error: Incorrect attribute value type

on main_count_data.tf line 57, in resource "aws_instance" "test": 57: subnet_id = var.aws_subnet_id_this |---------------- | var.aws_subnet_id_eks is tuple with 2 elements

Inappropriate value for attribute "subnet_id": string required.

So I tried this:

main.tf

resource "aws_instance" "prueba" {
  ami                         = var.ami_id
  instance_type               = var.ec2_instance_type
  #subnet_id                   = var.aws_subnet_id_this
  count = 2
  subnet_id = "${element(var.aws_subnet_id_this, count.index)}"
  key_name                    = var.pki_name
  vpc_security_group_ids      = [aws_security_group.Allow_SSH_in.id]
  }
}

but this last portion of code tries to create a new EC2 instance with the second subnet and this is not what I expect tough.

To sum up: I need 1 EC2 containing 2 subnets defined in the variables.tf file.

How can I do this?


Solution

Below is an example of how you can create one instance with two NICs in different subnets. The NICs must be in same AZ. So instance can have two NICs in different subnets as long as they are in same AZ:

variable "aws_subnet_id_this" {
  description = "Subnet ID"
  default = ["subnet-09df122a4faee8882", "subnet-2fcc756f02ddb4b62"]
}

resource "aws_network_interface" "nic1" {
  subnet_id       = var.aws_subnet_id_this[0]
}

resource "aws_network_interface" "nic2" {
  subnet_id       = var.aws_subnet_id_this[1]
}


resource "aws_instance" "prueba" {
  ami                         = var.ami_id
  instance_type               = var.ec2_instance_type
  key_name                    = var.pki_name

  network_interface {
      device_index = 0
      network_interface_id = aws_network_interface.nic1.id
  }
        
  network_interface {
      device_index = 1
      network_interface_id = aws_network_interface.nic2.id
  }  
  
}



Answered By - Marcin
Answer Checked By - Marie Seifert (WPSolving Admin)