LoginSignup
10
5

More than 5 years have passed since last update.

terraformでEC2を作ると同時にprivate_ipをRoute53 Internal DNSで俺の考えた最強にイケてるしやばい名前をつける方法

Posted at

俺です。

EC2のPrivate IPに自分で考えた名前をつける乙なことをしてみたい時のメモです。
countとelementを使うことでterraformでLaunchするEC2の台数が変動してもいい感じにDNS登録されます

以下例

前提: VPC DNS hostnameは有効にすること

EC2

  • variables
variable "unko" {
  default = {
    name = "unko"
    ami = "ami-XXXXXXXX"
    instance_type = "c4.2xlarge"
    iam_instance_profile = "unko"
    source_dest_check = true
    ebs_optimized = true
    root_block_device = "gp2"
    root_block_device_size = 100
    count = 2
  }
}
  • ec2.tf
resource "aws_instance" "unko" {
..省略..
  count = "${lookup(var.unko, "count")}"
}

Route53

resource "aws_route53_zone" "unko" {
  name = "unko"
  vpc_id = "${aws_vpc.unko.id}"
  vpc_region = "ap-northeast-1"
  tags {
    Type = "Internal DNS"
  }
}

resource "aws_route53_record" "unko" {
  zone_id = "${aws_route53_zone.unko.zone_id}"
  name = "unko-${count.index + 1}-${element(aws_instance.unko.*.availability_zone, count.index)}"
  type = "A"
  ttl = "5"
  count = "${lookup(var.unko, "count")}"
  records = [
    "${element(aws_instance.unko.*.private_ip, count.index)}"
  ]
}
$ terraform apply

これでOK

10
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5