如何使用 Terraform 将文件从本地计算机复制到存储帐户
How to copy a file from local machine to a storage account using Terraform
我已经使用 Terraform 创建了一个存储帐户并在其中创建了一个文件共享。我想使用 Terraform 将一些文件从我的本地计算机复制到该存储帐户。那可能吗?如果是,那又如何?
这是我的代码-
provider "azurerm" {
# whilst the `version` attribute is optional, we recommend pinning to a given version of the Provider
version = "=2.0.0"
subscription_id = "xxx-xxxx-xxxx-xxxx"
tenant_id = "xxxxx-xxxxx-xxxx-xxxx"
features {}
}
resource "azurerm_resource_group" "example" {
name = "azuretest"
location = "West Europe"
}
resource "azurerm_storage_account" "example" {
name = "asdfghjklteststorage"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
account_tier = "Standard"
account_replication_type = "LRS"
}
resource "azurerm_storage_share" "example" {
name = "sharename"
storage_account_name = azurerm_storage_account.example.name
quota = 50
acl {
id = "xxx-xxx-xxx-xxx"
access_policy {
permissions = "rwdl"
start = "2020-05-10T09:38:21.0000000Z"
expiry = "2020-07-02T10:38:21.0000000Z"
}
}
}
resource "null_resource" "uploadfile" {
provisioner "local-exec" {
command = <<-EOT
$storageAcct = Get-AzStorageAccount -ResourceGroupName "${azurerm_resource_group.example.name}" -Name "${azurerm_storage_account.example.name}"
Set-AzStorageFileContent `
-Context $storageAcct.Context `
-ShareName "${azurerm_storage_share.example.name}" `
-Source "C:\Users\xxx\xxx\xxx\Untitled.png" `
-Path "Untitled.png"
EOT
interpreter = ["PowerShell", "-Command"]
}
}
你可以使用 local-exec provisioner invokes a local executable after a resource is created. See upload a file to Azure file share with PowerShell.
例如,
resource "azurerm_storage_share" "example" {
name = "sharename"
storage_account_name = azurerm_storage_account.example.name
quota = 50
acl {
id = "xxxxxxxxxxxxxxx"
access_policy {
permissions = "rwdl"
start = "2020-05-10T09:38:21.0000000Z"
expiry = "2020-07-02T10:38:21.0000000Z"
}
}
}
resource "null_resource" "uploadfile" {
provisioner "local-exec" {
command = <<-EOT
$storageAcct = Get-AzStorageAccount -ResourceGroupName "${azurerm_resource_group.example.name}" -Name "${azurerm_storage_account.example.name}"
Set-AzStorageFileContent `
-Context $storageAcct.Context `
-ShareName "${azurerm_storage_share.example.name}" `
-Source "C:\Users\xxx\terraform\test.txt" `
-Path "test.txt"
EOT
interpreter = ["PowerShell", "-Command"]
}
}
结果
更多信息,您可以阅读this blog。
对于来自 Google 的任何人,值得指出的是,到 2022 年初,现在应该可以使用 azurerm_storage_share_file。这对我上传单个文件非常有用。要上传多个文件,您似乎需要多个资源
https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/storage_share_file
resource "azurerm_storage_share_file" "example" {
name = "test.txt"
storage_share_id = azurerm_storage_share.example.id
source = "${path.root}/TestFiles/test.txt"
}