ik005
ik005

Reputation: 53

Use existing AWS security group in terraform

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.

Upvotes: 5

Views: 7197

Answers (2)

Chuong Nguyen
Chuong Nguyen

Reputation: 1162

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

Upvotes: 0

Marcin
Marcin

Reputation: 238209

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.

Upvotes: 3

Related Questions