1
votes

Have an AMI with additional volume and need to get device_name this additional volume.

My Terraform code:

data "aws_ami" "example" {

  owners = [270245543446]
}

output "example1" {
  value = data.aws_ami.example.block_device_mappings
}

and output is:

example1 = [
  {
    "device_name" = "/dev/sda1"
    "ebs" = {
      "delete_on_termination" = "false"
      "encrypted" = "false"
      "iops" = "0"
      "snapshot_id" = "snap-0b4eedb04c8976458"
      "volume_size" = "8"
      "volume_type" = "gp2"
    }
    "no_device" = ""
    "virtual_name" = ""
  },
  {
    "device_name" = "/dev/sde"
    "ebs" = {
      "delete_on_termination" = "false"
      "encrypted" = "false"
      "iops" = "0"
      "snapshot_id" = ""
      "volume_size" = "8"
      "volume_type" = "gp2"
    }
    "no_device" = ""
    "virtual_name" = ""
  },
]

In my case I need to get output - "/dev/sde". Please help to find the solution.

I have also tried value = data.aws_ami.example.block_device_mappings["/dev/sde"].device_name but in this case I should know needed device_name.

Can't fully understand what mean # here https://www.terraform.io/docs/providers/aws/d/ami.html#block_device_mappings-device_name

2

2 Answers

1
votes

My solution: If we use dynamic block with for_each we can prevent adding additional volumes to an AMI and make all of them encrypted.

  dynamic "ebs_block_device" {
    for_each = [
      for i in data.aws_ami.example.block_device_mappings: {
        device_name = i.device_name
      }
      if i.device_name != data.aws_ami.example.root_device_name
      ]
    content {
      device_name = ebs_block_device.value.device_name
      encrypted = true
    }
-1
votes

The '#' is a symbol for the index. You can use 0 or 1, in your example. Or you can use * to get a list of all names.

value = data.aws_ami.example.block_device_mappings[1].device_name

would give you the desired result.