Creating directory in azure and upload files using terraform

75 Views Asked by At

I have a directory locally with a set of files e.g.

/workload/test1.json
/workload/test2.json
/workload/test3.json
...

For each file in the directory I want to create a folder in Azure File Share, and then place each file inside.

e.g. azurefileshare/test1/test1.json azurefileshare/test2/test2.json azurefileshare/test3/test3.json

I dont know how to make it dynamic. I can create a directory using azurerm_storage_share_directory and then upload the file to the directory using azurerm_storage_share_file but i dont now how to make a dynamic iteration

Any examples / tips how to achieve this?

1

There are 1 best solutions below

0
Venkat V On

Here the terraform code that copies the files from the local directory to the Azure Fileshare with the correct structure.

    provider "azurerm" {
      features {}
    }
    
    resource "azurerm_resource_group" "example" {
      name     = "azuretest"
      location = "West Europe"
    }
    
    resource "azurerm_storage_account" "example" {
      name                     = "azureteststoragetemp"
      resource_group_name      = azurerm_resource_group.example.name
      location                 = azurerm_resource_group.example.location
      account_tier             = "Standard"
      account_replication_type = "LRS"
    }
    
    variable "local_directory" {
      description = "Local directory path"
      type        = string
      default     = "/home/user/Venkat"
    }
    
    variable "azure_file_share_name" {
      description = "Azure File Share name"
      type        = string
      default     = "infrafilesharevk"
    }
    
    resource "azurerm_storage_share" "example" {
      name                 = var.azure_file_share_name
      storage_account_name = azurerm_storage_account.example.name
      quota                = 50
    }
    
    data "local_file" "files" {
      for_each = fileset(var.local_directory, "**/*.json")
    
      filename = each.value
    }
    
    resource "azurerm_storage_share_directory" "directories" {
      for_each              = data.local_file.files
    
      name                  = replace(basename(each.value.filename), ".json", "")
      storage_account_name  = azurerm_storage_account.example.name
      share_name            = azurerm_storage_share.example.name
    }
    
    resource "azurerm_storage_share_file" "files" {
      for_each        = data.local_file.files
      name            = each.value.filename
      storage_share_id = azurerm_storage_share.example.id
      path            = replace(basename(each.value.filename), ".json", "")
      source          = each.value.filename
    }

Terraform apply:

After running the terraform code, all files has been copied to Azure File share from local directory.

enter image description here