AWS EC2 Instance with Security Group using Terraform


  1. Create tf script.
  2. flowchart TD; A[ssh-key]-->|login|B[EC2]; C[Security Group]-->|attach|B;
    
    provider "aws" {
        region = "${var.AWS_REGION}"
    }
    resource "aws_key_pair" "example_key" {
        key_name = "mykey"
        public_key = "${file("${var.PATH_TO_PUBLIC_KEY}")}"
    }
    
    resource "aws_instance" "example" {
        ami = "${lookup(var.AMIS,var.AWS_REGION)}"
        instance_type = "t2.micro"
        security_groups = [aws_security_group.example_sg.name]
        key_name = "${aws_key_pair.example_key.key_name}"
        provisioner "file" {
            source  = "script.sh"
            destination = "/tmp/script.sh"
        }
        provisioner "remote-exec"{
            inline = [
                "chmod +x /tmp/script.sh",
                "sudo /tmp/script.sh"
            ]
        }
        connection {
            host = self.public_ip
            user = "${var.INSTANCE_USERNAME}"
            private_key = "${file("${var.PATH_TO_PRIVATE_KEY}")}"
        }
        provisioner "local-exec"{
            command = "echo ${aws_instance.example.public_ip} >> public_ips.txt"
        }
        tags = {
            Name = "ec2 example terraform instance"
        }
    }
    
    resource "aws_security_group" "example_sg" {
        name = "security group for example ec2"
        ingress {
            description = "HTTPS"
            from_port = 443
            to_port = 443
            protocol = "tcp"
            cidr_blocks = ["0.0.0.0/0"]
            ipv6_cidr_blocks = ["::/0"]
        }
        ingress {
            description = "HTTP"
            from_port = 80
            to_port = 80
            protocol = "tcp"
            cidr_blocks = ["0.0.0.0/0"]
            ipv6_cidr_blocks = ["::/0"]
        }
        ingress {
            description = "SSH"
            from_port = 22
            to_port = 22
            protocol = "tcp"
            cidr_blocks = ["0.0.0.0/0"]
            ipv6_cidr_blocks = ["::/0"]
        }
    
        egress {
            from_port = 0
            to_port = 0
            protocol = "-1"
            cidr_blocks = ["0.0.0.0/0"]
            ipv6_cidr_blocks = ["::/0"]
        }
    
        tags = {
            Name = "sg"
        }
    }
    
    output "ip" {
        value = "${aws_instance.example.public_ip}"
    }
            
  3. Generate ssh key. ssh-keygen mykey
  4. Terraform apply.
  5. ssh -i mykey ubuntu@ip

References