Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New resource azurerm_managed_disk_sas_token to manage disk exports #15558

Merged
merged 12 commits into from
May 9, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions internal/services/compute/disk_export_data_source.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package compute

import (
"crypto/sha256"
"encoding/hex"
"fmt"
"time"

"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-07-01/compute"
"github.com/hashicorp/terraform-provider-azurerm/helpers/azure"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/compute/parse"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/suppress"
"github.com/hashicorp/terraform-provider-azurerm/internal/timeouts"
)

func dataSourceManagedDiskExport() *pluginsdk.Resource {
return &pluginsdk.Resource{
Read: dataSourceManagedDiskExportRead,

Timeouts: &pluginsdk.ResourceTimeout{
Read: pluginsdk.DefaultTimeout(5 * time.Minute),
},

Schema: map[string]*pluginsdk.Schema{
"managed_disk_id": {
Type: pluginsdk.TypeString,
Required: true,
DiffSuppressFunc: suppress.CaseDifference,
ValidateFunc: azure.ValidateResourceID,
},

"duration_in_seconds": {
Type: pluginsdk.TypeInt,
Required: true,
},

"access": {
Type: pluginsdk.TypeString,
Optional: true,
Default: "Read",
},

"sas": {
Type: pluginsdk.TypeString,
Computed: true,
Sensitive: true,
},
},
}
}

func dataSourceManagedDiskExportRead(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Compute.DisksClient
ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d)
defer cancel()

managedDiskId := d.Get("managed_disk_id").(string)
durationInSeconds := int32(d.Get("duration_in_seconds").(int))
access := d.Get("access").(string)

parsedManagedDiskId, err := parse.ManagedDiskID(managedDiskId)
if err != nil {
return fmt.Errorf("parsing Managed Disk ID %q: %+v", parsedManagedDiskId.ID(), err)
}

diskName := parsedManagedDiskId.DiskName
resourceGroupName := parsedManagedDiskId.ResourceGroup

grantAccessData := compute.GrantAccessData{
Access: compute.AccessLevel(access),
DurationInSeconds: &durationInSeconds,
}

// Request to Grant Access for Disk
diskGrantFuture, err := client.GrantAccess(ctx, resourceGroupName, diskName, grantAccessData)
if err != nil {
return fmt.Errorf("Error while granting access for disk export %q: %+v", parsedManagedDiskId.ID(), err)
}

// Wait until the Grant Request is complete
err = diskGrantFuture.WaitForCompletionRef(ctx, client.Client)
if err != nil {
return fmt.Errorf("Grant access operation failed %q (Resource Group %q): %+v", diskName, resourceGroupName, err)
}

// Fetch the SAS token from the response
diskGrantResponse, err := diskGrantFuture.Result(*client)
if err != nil {
return fmt.Errorf("Error while fetching the response %q: %+v", parsedManagedDiskId.ID(), err)
}

sasToken := diskGrantResponse.AccessSAS

d.Set("sas", *sasToken)
tokenHash := sha256.Sum256([]byte(*sasToken))
d.SetId(hex.EncodeToString(tokenHash[:]))

return nil

}
52 changes: 52 additions & 0 deletions internal/services/compute/disk_export_data_source_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package compute_test

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance"
"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check"
)

type DataSourceManagedDiskExportDataSource struct{}

func TestAccDataSourceDiskExportSas_basic(t *testing.T) {
data := acceptance.BuildTestData(t, "data.azurerm_managed_disk_export", "test")

data.DataSourceTest(t, []acceptance.TestStep{
{
Config: DataSourceManagedDiskExportDataSource{}.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).Key("managed_disk_id").HasValue("/subscriptions/42cbb0b8a331-abaf-4e69-8d8f-14b86a40/resourceGroups/disksrg/providers/Microsoft.Compute/disks/disk1"),
check.That(data.ResourceName).Key("access").HasValue("Write"),
check.That(data.ResourceName).Key("duration_in_seconds").HasValue("30"),
check.That(data.ResourceName).Key("sas").Exists(),
),
},
})
}

func (d DataSourceManagedDiskExportDataSource) basic(data acceptance.TestData) string {
return fmt.Sprintf(`
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "rg" {
name = "acctestRG-disk-%d"
location = "%s"
}
resource "azurerm_managed_disk" "disk" {
name = "acctestsads%s"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
storage_account_type = "Standard_LRS"
create_option = "Empty"
disk_size_gb = "1"
}
data "azurerm_managed_disk_export" "test" {
managed_disk_id = azurerm_managed_disk.disk.id
duration_in_seconds = 300
access = "Read"
}
`, data.RandomInteger, data.Locations.Primary, data.RandomString)
}
1 change: 1 addition & 0 deletions internal/services/compute/registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ func (r Registration) SupportedDataSources() map[string]*pluginsdk.Resource {
"azurerm_virtual_machine": dataSourceVirtualMachine(),
"azurerm_virtual_machine_scale_set": dataSourceVirtualMachineScaleSet(),
"azurerm_ssh_public_key": dataSourceSshPublicKey(),
"azurerm_managed_disk_export": dataSourceManagedDiskExport(),
}
}

Expand Down
67 changes: 67 additions & 0 deletions website/docs/d/managed_disk_export.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
---
subcategory: "Compute"
layout: "azurerm"
page_title: "Azure Resource Manager: azurerm_managed_disk_export"
description: |-
Gets a Shared Access Signature (SAS Token) for an existing Managed Disk.

---

# Data Source: azurerm_managed_disk_export

Use this data source to obtain a Shared Access Signature (SAS Token) for an existing Managed Disk.

Shared access signatures allow fine-grained, ephemeral access control to various aspects of Managed Disk similar to blob/storage account container.

## Example Usage

```hcl
resource "azurerm_resource_group" "rg" {
name = "resourceGroupName"
location = "West Europe"
}

resource "azurerm_managed_disk" "disk" {
name = "azureManagedDisk"
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
storage_account_type = "Standard_LRS"
create_option = "Empty"
disk_size_gb = "1"

tags = {
environment = "staging"
}
}

data "azurerm_managed_disk_export" "disk" {
managed_disk_id = azurerm_managed_disk.disk.id
duration_in_seconds = 300
access = "Read"
}

output "sas_url_query_string" {
value = data.azurerm_managed_disk_export.disk.sas
}
```

## Argument Reference

* `managed_disk_id` - The ID of an existing Managed Disk which should be exported. Changing this forces a new resource to be created.

* `duration_in_seconds` - The duration for which the export should be allowed. Should be greater than 30 seconds.

* `access` - (Optional) The level of access required on the disk. Supported are Read, Write. Defaults to Read.

Refer to the [SAS creation reference from Azure](https://docs.microsoft.com/en-us/rest/api/compute/disks/grant-access)
for additional details on the fields above.

## Attributes Reference

* `sas` - The computed Shared Access Signature (SAS) of the Managed Disk.

## Timeouts

The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions:

* `read` - (Defaults to 5 minutes) Used when retrieving the Blob Container.