Search code examples
regexazureterraformvirtual-machineazure-rm

RegEx for filtering in Azure using Terraform


The Terraform azurerm_image data source lets you use a RegEx to identify a machine image whose ID matches the regular expression.

What RegEx should be used to retrieve an image that includes the string MyImageName and that takes the complete form /subscriptions/abc-123-def-456-ghi-789-jkl/resourceGroups/MyResourceGroupName/providers/Microsoft.Compute/images/MyImageName1618954096 ?

The following version of the RegEx is throwing an error because it will not accept two * characters. However, when we only used the trailing *, the image was not retrieved.

data "azurerm_image" "search" {
  name_regex          = "*MyImageName*"
  resource_group_name = var.resourceGroupName
}

Note that the results only return a single image so you do not need to worry about multiple images being returned. There is a flag that can be set to specify either ascending or descending sorting to retrieve the oldest or the newest match.

The precise error we are getting is:

Error: "name_regex": error parsing regexp: missing argument to repetition operator: `*`  

Nick's Suggestion

Per @Nick's suggestion, we tried:

data "azurerm_image" "search" {
  name_regex          = "/MyImageName[^/]+$"
  resource_group_name = 
var.resourceGroupName
}

But the result is:

Error: No Images were found for Resource Group "MyResourceGroupName"  

We checked in the Azure Portal and there is an image that includes MyImageName in its name within the resource group named MyResourceGroupName. We also confirmed that Terraform is running as the subscription owner, so we imagine that the subscription owner has sufficient authorization to filter image names.

What else can we try?


Solution

  • After my validation, it seems that it works when name_regex includes only one trailing *. If with one prefix *, it will generate that error message.

    For example, I have an image name rrr-image-20210421150018 in my resource group.

    The following works:

    r*
    -*
    8*
    rrr*
    image*
    2021*
    

    The following does not work:

    *r
    *-
    *8
    *image*
    *rrr*
    

    Also, verify if you have the latest azurerm provider.

    Result

    enter image description here