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?
New Info
I think i was able to re-use existing SG using datasources by referring @Marcin's comment. here is my simple .tf code :
data "aws_security_group" "testsg" {
id = "sg-0f9fb8b59aebac240"
}
resource "aws_instance" "myec2" {
ami = "ami-033b95fb8079dc481"
instance_type = "t2.micro"
tags = {
"Name" = "terra"
}
key_name = aws_key_pair.sshkey.id
vpc_security_group_ids = [data.aws_security_group.testsg.id]
}
resource "aws_key_pair" "sshkey" {
public_key = file("C:/Users/admin/key.pub")
}
i manually created an SG on aws console as "sg-0f9fb8b59aebac240". this is completely outside the scope of TF as TF has no way of knowing its existence. then i used datasources to read it and input the info from it to TF. the instance got launched correctly and the proper SG got attached to it.
hope what i did above is right, else i am all ears :)
FYI, i also tried @Ash Blake's approach. it worked out perfectly when i created files under a same directory. for diff directories, i think datasources is the right way.