Skip to content

Instantly share code, notes, and snippets.

@devops-school
Created April 3, 2023 04:23
Show Gist options
  • Save devops-school/b80beae09629dadd6dd993eca9fbde12 to your computer and use it in GitHub Desktop.
Save devops-school/b80beae09629dadd6dd993eca9fbde12 to your computer and use it in GitHub Desktop.
write a terraform code which would create Security Group and new Key and create Ec2 instance and use newly created Security Group and Key.The security group should allow incoming traffic on port 22 (SSH) and port 80 (HTTP).
# Create a security group
resource "aws_security_group" "web" {
name_prefix = "web-sg"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "Web SG"
}
}
# Create a key pair
resource "aws_key_pair" "key" {
key_name = "my-key"
public_key = file("~/.ssh/id_rsa.pub")
}
# Launch an EC2 instance
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
key_name = aws_key_pair.key.key_name
vpc_security_group_ids = [aws_security_group.web.id]
tags = {
Name = "Web Instance"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment