Create AWS SG and use it
-
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 settingsterraform 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?
-
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 https://www.terraform.io/language/meta-arguments/depends_on :
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.