I am trying to assign Storage account lifecycle management policy using terraform. The lists of more than 30 containers are defined in the input.tfvars file as lists of strings which needs to be called in main.tf in "resource azurerm_storage_management_policy lifecycle". But it is giving error. Please guide how should I call the variable.
The code details in my git is given below.
input.tfvars –
containername = ["a", "b", "c", "d", "e", "f", "g".................................]
This list includes more than 30 container names.
variables.tf —
variable "containername" {
type = list(string)
default = []
}
main.tf —
locals {
folderlist1 = var.containername
list1 = [ for a in local.folderlist1: a ]
}
output "result1" {
value = local.list1
}
resource "azurerm_storage_management_policy" "lifecycle" {
storage_account_id = azurerm_storage_account.sa.id
rule{
name = "Rule1"
enabled = true
filters {
prefix_match = local.list1
blob_types = ["blockBlob"]
}
actions {
base_blob {
delete_after_days_since_modification_greater_than = 15
}
snapshot {
delete_after_days_since_creation_greater_than = 15
}
}
}
}
Giving error as "prefix_match": element 0: string required.
2
Answers
For this to work, you would need to use the
dynamic
block withfor_each
meta-argument:The lifecycle management policy to multiple containers specified in the
containername
variable, you’ll need to iterate over each container name and create a separate rule for each one.Here is the updated Terraform code to create a
lifecycle management policy
for all the containers in the storage account.terraform.tfvars
variables.tf
storage.tf
Output:
After running the script, rules are created in the management policy of the storage account for all containers specified in
variables.tf
.