Asier Gomez
Asier Gomez

Reputation: 6578

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

I create instances with a default CentOS 7 AMI. This AMI creates automatically a volume and attached to the instance. Is it possible to read thats volume ID using terraform? I create the instance using the next code:

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"
        }
}

Upvotes: 3

Views: 2638

Answers (4)

Mostafa Wael
Mostafa Wael

Reputation: 3838

You can get the volume name of an aws_instance like this:

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

And you can set it as follows:

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]}"
  } 
}

Upvotes: 0

Helen Paterson
Helen Paterson

Reputation: 11

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)
}

Upvotes: 1

forzagreen
forzagreen

Reputation: 2683

You can: aws_instance.DCOS-master3.root_block_device.0.volume_id

As described in 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

Upvotes: 1

Leon
Leon

Reputation: 465

You won't be able to extract EBS details from aws_instance since it's AWS side that provides an EBS volume to the resource.

But you can define a EBS data source with some filter.

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}"
}

You can refer EBS filters here: http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-volumes.html

Upvotes: 5

Related Questions