I am very new to terraform and have recently started learning it. I have managed to launch AWS ec2 instance. While creating it, I gave the following SG related info :
resource "aws_security_group" "forssh" {
name = "ssh-access"
ingress {
cidr_blocks = [ "0.0.0.0/0" ]
from_port = 22
protocol = "tcp"
to_port = 22
}
tags = {
"Name" = "terraform-create"
}
}
This created an SG and I can see it on the AWS console as well as "sg-000312648cb099634". Now, suppose I want to another entirely different EC2 instance but without re-declaring SG. I want to use this same existing SG in my new config. Is it possible to do so? How to achieve this?
CodePudding user response:
You can use Data Source called aws_security_group to get details of an existing SG:
data "aws_security_group" "selected" {
id ="sg-000312648cb099634"
}
Then you can use the data source to refer to all the information related to the given security group.
CodePudding user response:
If EC2 and SG tf files are in the same folder, you can declare the EC2 to get the ID from SG block. Documentation
resource "aws_instance" "web" {
...
security_groups = [aws_security_group.forssh.id]
...
}
If they are in different folders, you can do the hard code like above answer, or write outputs and then import through data sources. Documentation