Terraform:如何读取一个实例的卷 ID?

Terraform: How to read the volume ID of one instance?

我使用默认的 CentOS 7 AMI 创建实例。此 AMI 会自动创建一个卷并附加到实例。是否可以使用 terraform 读取那个卷 ID?我使用下一个代码创建实例:

resource "aws_instance" "DCOS-master3" {
    ami = "${var.aws_centos_ami}"
    availability_zone = "eu-west-1b"
    instance_type = "t2.medium"
    key_name = "${var.aws_key_name}"
    security_groups = ["${aws_security_group.bastion.id}"]
    associate_public_ip_address = true
    private_ip = "10.0.0.13"
    source_dest_check = false
    subnet_id = "${aws_subnet.eu-west-1b-public.id}"

    tags {
            Name = "master3"
        }
}

您将无法从 aws_instance 中提取 EBS 详细信息,因为它是 AWS 端为资源提供 EBS 卷。

但是您可以使用一些过滤器定义 EBS data source

data "aws_ebs_volume" "ebs_volume" {
  most_recent = true

  filter {
    name   = "attachment.instance-id"
    values = ["${aws_instance.DCOS-master3.id}"]
  }
}

output "ebs_volume_id" {
  value = "${data.aws_ebs_volume.ebs_volume.id}"
}

您可以在这里参考 EBS 过滤器: http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-volumes.html

您可以:aws_instance.DCOS-master3.root_block_device.0.volume_id

Terraform docs所述:

For any root_block_device and ebs_block_device the volume_id is exported. e.g. aws_instance.web.root_block_device.0.volume_id

output "volume-id-C" {
  description = "root volume-id"
  #get the root volume id form the instance
     value       =  element(tolist(data.aws_instance.DCOS-master3.root_block_device.*.volume_id),0)
}

output "volume-id-D" {
   description = "ebs-volume-id"
    #get the 1st esb volume id form the instance
        value       =  element(tolist(data.aws_instance.DCOS-master3.ebs_block_device.*.volume_id),0)
}

您可以获取 aws_instance 的卷名称,如下所示:

output "instance" {
    value = aws_instance.ec2_instance.volume_tags["Name"]
}

您可以设置如下:

resource "aws_instance" "ec2_instance" {
  ami                   = var.instance_ami
  instance_type         = var.instance_type
  key_name              = var.instance_key
  ...
  tags = {
    Name = "${var.server_name}_${var.instance_name[count.index]}"
  }
  volume_tags = {
    Name = "local_${var.instance_name[count.index]}"
  } 
}