Reputation: 2002
I am trying explore terraform to create automate infra in AWS. I am not clear on how to attach a security group to aws instance in terraform.
For example, Is there any property to specify the security groups like here below
resource "aws_instance" "web" {
ami = "ami-a1b2c3d4"
instance_type = "t2.micro"
}
Upvotes: 1
Views: 30095
Reputation: 33
You can include aws_security_group like:
resource "aws_security_group" "sg" {
name = "sg"
description = "Web Security Group for HTTP"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
Upvotes: -3
Reputation: 498
Leveraging from Ay0's answer: you can include vpc_security_group_ids
rule like:
resource "aws_security_group" "basic_security" {
ingress {...}
egress {...}
}
resource "aws_instance" "web" {
ami = "ami-a1b2c3d4"
instance_type = "t2.nano"
vpc_security_group_ids = [aws_security_group.basic_security.id]
}
Upvotes: 4
Reputation: 717
resource "aws_instance" "web" {
ami = "ami-a1b2c3d4"
instance_type = "t2.micro"
}
resource "aws_security_group" "sec_group" {
name = "sec_group"
vpc_id = "vpc-3324nnrvdl"
}
resource "aws_network_interface_sg_attachment" "sg_attachment" {
security_group_id = "${data.aws_security_group.sec_group.id}"
network_interface_id = "${aws_instance.web.primary_network_interface_id}"
}
This way you will be able to attach a SG to EC2 instance and both will be in decouple state.
Upvotes: 6
Reputation:
Use the argument vpc_security_group_ids
. This argument accepts a list of N security group IDs
Upvotes: 8