How can I retrieve all the VPC custom images that have a specific tag with terraform?

64 Views Asked by At

I have a list of custom images in my account.

In my terraform template, I'd like to retrieve an image with a specific tag. I don't want to hardcode or pass the image ID to the terraform template, I want to reference a tag like version:1.0 instead. I could not find how to do it with data ibm_is_image.

1

There are 1 best solutions below

1
Frederic Lavigne On

Using a combination of ibm_is_images to retrieve all images and ibm_resource_tag to retrieve the tags associated to one image, you can filter to find the image you are looking for.

Here is an example. It assumes that you have several images in your custom image library and that these images have been tagged version:1.0 and version:2.0

variable "ibmcloud_api_key" {}
variable "region" { default = "us-south" }

terraform {
  required_providers {
    ibm = {
      source = "IBM-Cloud/ibm"
    }
  }
  required_version = ">= 1.1.8"
}

provider "ibm" {
  ibmcloud_api_key = var.ibmcloud_api_key
  region           = var.region
}

data "ibm_is_images" "images" {
  visibility = "private"
}

data "ibm_resource_tag" "image_tag" {
  for_each = { for image in data.ibm_is_images.images.images : image.id => image.crn }

  resource_id = each.value
}

locals {
  // create an array with all images and their tags
  all_images = [ for image in data.ibm_is_images.images.images : {
    id: image.id,
    name: image.name
    crn: image.crn
    tags: data.ibm_resource_tag.image_tag[image.id].tags
  }
  ]
}

output "all_images" {
  value = local.all_images
}

output "all_v1_images" {
  value = [ for image in local.all_images: image if contains(image.tags, "version:1.0") ]
}

output "all_v2_images" {
  value = [ for image in local.all_images: image if contains(image.tags, "version:2.0") ]
}