1

I am trying to create a security group (SG) using Terraform and then use it for an AWS instance.

My config looks like

resource "aws_security_group" "my_sq" {
  vpc_id = aws_vpc.mainvpc.id
  name = "my_sg"
  ingress {
    cidr_blocks = [
      "0.0.0.0/0"
    ]
    from_port = 22
    to_port = 22
    protocol = "tcp"
  }

}

resource "aws_instance" "my_new_instance" {
  ami = "AMI-ID"
  instance_type = "t2.micro"
  security_groups = ["my_sg"]
  }
}

I tried assigning the SG by name and id. When I ran terraform plan everything is all right. When I tried to apply settings terraform apply I see this error:

│ Error: Error launching instance, possible mismatch of Security Group IDs and Names.

How do I use the new SG which I created in the config file?

1 Answer 1

3

You may not create those two things in the right order, since there is no dependency declared between them. Terraform doesn't know that the security group with name "my-sg" is the same as the security group that it is creating with that name.

You could use a reference to the sg resource in your instance declaration:

resource "aws_security_group" "my_sg" {
  vpc_id = aws_vpc.mainvpc.id
  name = "my_sg"
  ingress {
    cidr_blocks = [
      "0.0.0.0/0"
    ]
    from_port = 22
    to_port = 22
    protocol = "tcp"
  }

}

resource "aws_instance" "my_new_instance" {
  ami = "AMI-ID"
  instance_type = "t2.micro"
  security_groups = [aws_security_group.my_sg.name]
  }
}

or you can declare a dependency:

resource "aws_security_group" "my_sg" {
  vpc_id = aws_vpc.mainvpc.id
  name = "my_sg"
  ingress {
    cidr_blocks = [
      "0.0.0.0/0"
    ]
    from_port = 22
    to_port = 22
    protocol = "tcp"
  }

}

resource "aws_instance" "my_new_instance" {
  ami = "AMI-ID"
  instance_type = "t2.micro"
  security_groups = ["my-sg"]
  }
  depends_on = [aws_security_group.my_sg,]
}

If you make the reference to another resource (example 1), then Terraform can itself determine the dependency, and wait for the creation of the security group before creating the instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.