DeriveVpcFromSubnet

nicolaw 22nd May 2019 at 3:31pm
AWS CodeSnippets Terraform
provider "aws" {
  region = "us-east-1"
}

variable "vpc_id" {
  default = "vpc-0123456789"
}

data "aws_subnet_ids" "public" {
  vpc_id = "${var.vpc_id}"

  tags = {
    tier = "public"
  }
}

locals {
  name = "Nicola-Test-DeleteMe"
}

data "aws_subnet" "public" {
  count = "${length(data.aws_subnet_ids.public.ids)}"
  id    = "${data.aws_subnet_ids.public.ids[count.index]}"
}

locals {
  invalid_vpc_ids = ["vpc-blahblah", "${data.aws_subnet.public.*.vpc_id}"]
  valid_vpc_ids   = ["${data.aws_subnet.public.*.vpc_id}"]
}

resource "aws_security_group" "test" {
  name        = "test"
  description = "test"

  #  vpc_id = "${join("!DERIVED_TOO_MANY_VPC_IDS!",distinct(local.valid_vpc_ids))}"
  vpc_id = "${join("!DERIVED_TOO_MANY_VPC_IDS!",distinct(local.invalid_vpc_ids))}"

  tags = {
    Name = "${local.name}"
  }
}

resource "random_shuffle" "subnet_id" {
  input        = ["${data.aws_subnet_ids.public.ids}"]
  result_count = 1
}

resource "aws_instance" "test" {
  ami                         = "${data.aws_ami.amzn2.id}"
  key_name                    = "mykeypair"
  instance_type               = "t2.micro"
  vpc_security_group_ids      = ["${aws_security_group.test.id}"]
  subnet_id                   = "${element(random_shuffle.subnet_id.result, 0)}"
  associate_public_ip_address = true

  user_data = <<EOM
#!/bin/bash
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Hello world!</h1>" > /var/www/html/index.html
EOM

  tags = {
    Name = "${local.name}"
  }

  volume_tags = {
    Name = "${local.name}"
  }
}

resource "aws_security_group_rule" "allow_http_egress" {
  type              = "ingress"
  to_port           = 80
  from_port         = 80
  protocol          = "-1"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = "${aws_security_group.test.id}"
}

resource "aws_security_group_rule" "allow_all_egress" {
  type              = "egress"
  to_port           = 0
  from_port         = 0
  protocol          = "-1"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = "${aws_security_group.test.id}"
}

data "aws_ami" "amzn2" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-2.*"]
  }

  filter {
    name   = "root-device-type"
    values = ["ebs"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  filter {
    name   = "architecture"
    values = ["x86_64"]
  }
}

output "url" {
  value = "http://${aws_instance.test.public_dns}"
}