简体   繁体   中英

Terraform Azurerm: Create blob if not exists

I got Terrafrom code that creates storage account, container and block blob. Is it possible to configure that block blob is created only if it doesn't already exist?

In case of re-running terraform I wouldn't like to replace blob if it is already there as the content might have been manually modified and i would like to keep it.

Any tips? Only alternative I could think of is running powershell/bash script during further deployment steps that would create file if needed, but I am curious if this can be done just with Terraform.

locals {
  storage_account_name_teast = format("%s%s", local.main_pw_prefix_short, "teast")
}

resource "azurerm_storage_account" "teaststorage" {
  name                            = local.storage_account_name_teast
  resource_group_name             = azurerm_resource_group.main.name
  location                        = var.location
  account_tier                    = var.account_tier
  account_replication_type        = var.account_replication_type
  allow_nested_items_to_be_public = false
  min_tls_version                 = "TLS1_2"

  network_rules {
    default_action = "Deny"
    bypass = [
      "AzureServices"
    ]
    virtual_network_subnet_ids = []
    ip_rules                   = local.ip_rules
  }
  tags = var.tags
}

resource "azurerm_storage_container" "teastconfig" {
  name                  = "config"
  storage_account_name  = azurerm_storage_account.teaststorage.name
  container_access_type = "private"
}


resource "azurerm_storage_blob" "teastfeaturetoggle" {
  name                   = "featureToggles.json"
  storage_account_name   = azurerm_storage_account.teaststorage.name
  storage_container_name = azurerm_storage_container.teastconfig.name
  type                   = "Block"
  source                 = "vars-pr-default-toggles.json"
}

After scanning through terraform plan I figured out it was forcing a blob replacement because of:

content_md5 = "9a95db04fb1ff3abcd7ff81fcfb96307" -> null # forces replacement

I added lifecycle hook to blob resource to prevent it:

resource "azurerm_storage_blob" "teastfeaturetoggle" {
  name                   = "featureToggles.json"
  storage_account_name   = azurerm_storage_account.teaststorage.name
  storage_container_name = azurerm_storage_container.teastconfig.name
  type                   = "Block"
  source                 = "vars-pr-default-toggles.json"

  lifecycle {     
    ignore_changes = [       
      content_md5,     
    ]   
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM