-1

How to add an instance to an existing security group while creating in terraform instead of creating a new security group resource?

code in var.tf

variable "sg" {
 type =string
 default = "sg-111436g6535hc63xc"
}

code in resource.tf

resource "aws_instance" "web" {
 ami = var.ami
 key_name = var.key
 instance_type = var.itype
 security_groups =  var.sg 
 tags = {
  Name = "HelloWorld"
  } 
}

But I'm getting ->

│ Error: Incorrect attribute value type
│ 
│   on resource.tf line 5, in resource "aws_instance" "web":
│    5:   security_groups = var.sg
│     ├────────────────
│     │ var.sg is a string, known only after apply
│ 
│ Inappropriate value for attribute "security_groups": set of string required.

How to solve this error?

Manu
  • 51
  • 1
  • 8

2 Answers2

0

As mentioned in the comments it is expecting a list parameter, so the code would be;

resource "aws_instance" "web" {
 ami = var.ami
 key_name = var.key
 instance_type = var.itype
 security_groups =  [var.sg] 
 tags = {
  Name = "HelloWorld"
  } 
}
Alastair Montgomery
  • 1,756
  • 5
  • 21
  • 44
0

Generally, the security_groups argument only expects a list of security group names or IDs. So, it would be better to create a variable block type as list(string) as below

variable "sg" {
  description = "List of Security Group IDs"
  type        = list(string)
  default     = [ "sg-111436g6535hc63xc" ]
}

resource "aws_instance" "web" {
  ami              = var.ami
  key_name         = var.key
  instance_type    = var.itype
  security_groups  = var.sg 
  
  tags = {
    Name = "HelloWorld"
  } 
}

Optionally, you can use the data source to get the existing security group IDs by using the tags argument.

Reference link: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/security_groups#example-usage

Ravichandran
  • 427
  • 1
  • 3
  • 16