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 5 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

}
55 changes: 55 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,55 @@
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", "export")

data.DataSourceTest(t, []acceptance.TestStep{
{
Config: DataSourceManagedDiskExportDataSource{}.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).Key("access").HasValue("Read"),
check.That(data.ResourceName).Key("duration_in_seconds").HasValue("300"),
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-exportdisk-%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" "export" {
managed_disk_id = azurerm_managed_disk.disk.id
duration_in_seconds = 300
access = "Read"
}
data "azurerm_managed_disk_export_revoke" "revoke" {
depends_on = [data.azurerm_managed_disk_export.export]
managed_disk_id = azurerm_managed_disk.disk.id
}
`, data.RandomInteger, data.Locations.Primary, data.RandomString)
}
65 changes: 65 additions & 0 deletions internal/services/compute/disk_export_revoke_data_source.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package compute

import (
"fmt"
"time"

"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 dataSourceManagedDiskExportRevoke() *pluginsdk.Resource {
return &pluginsdk.Resource{
Read: dataSourceManagedDiskExportCancel,

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,
},
},
}
}

func dataSourceManagedDiskExportCancel(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)

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

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

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

d.SetId(time.Now().UTC().String())

return nil

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

import (
"fmt"
"testing"

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

type DataSourceManagedDiskExportRevokeDataSource struct{}

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

data.DataSourceTest(t, []acceptance.TestStep{
{
Config: DataSourceManagedDiskExportRevokeDataSource{}.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).Key("id").Exists(),
),
},
})
}

func (d DataSourceManagedDiskExportRevokeDataSource) basic(data acceptance.TestData) string {
return fmt.Sprintf(`
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "rg" {
name = "acctestRG-revokedisk-%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" "export" {
managed_disk_id = azurerm_managed_disk.disk.id
duration_in_seconds = 300
access = "Read"
}
data "azurerm_managed_disk_export_revoke" "revoke" {
depends_on = [data.azurerm_managed_disk_export.export]
managed_disk_id = azurerm_managed_disk.disk.id
}
`, data.RandomInteger, data.Locations.Primary, data.RandomString)
}
38 changes: 20 additions & 18 deletions internal/services/compute/registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,26 @@ func (r Registration) WebsiteCategories() []string {
// SupportedDataSources returns the supported Data Sources supported by this Service
func (r Registration) SupportedDataSources() map[string]*pluginsdk.Resource {
return map[string]*pluginsdk.Resource{
"azurerm_availability_set": dataSourceAvailabilitySet(),
"azurerm_dedicated_host": dataSourceDedicatedHost(),
"azurerm_dedicated_host_group": dataSourceDedicatedHostGroup(),
"azurerm_disk_encryption_set": dataSourceDiskEncryptionSet(),
"azurerm_managed_disk": dataSourceManagedDisk(),
"azurerm_image": dataSourceImage(),
"azurerm_images": dataSourceImages(),
"azurerm_disk_access": dataSourceDiskAccess(),
"azurerm_platform_image": dataSourcePlatformImage(),
"azurerm_proximity_placement_group": dataSourceProximityPlacementGroup(),
"azurerm_shared_image_gallery": dataSourceSharedImageGallery(),
"azurerm_shared_image_version": dataSourceSharedImageVersion(),
"azurerm_shared_image_versions": dataSourceSharedImageVersions(),
"azurerm_shared_image": dataSourceSharedImage(),
"azurerm_snapshot": dataSourceSnapshot(),
"azurerm_virtual_machine": dataSourceVirtualMachine(),
"azurerm_virtual_machine_scale_set": dataSourceVirtualMachineScaleSet(),
"azurerm_ssh_public_key": dataSourceSshPublicKey(),
"azurerm_availability_set": dataSourceAvailabilitySet(),
"azurerm_dedicated_host": dataSourceDedicatedHost(),
"azurerm_dedicated_host_group": dataSourceDedicatedHostGroup(),
"azurerm_disk_encryption_set": dataSourceDiskEncryptionSet(),
"azurerm_managed_disk": dataSourceManagedDisk(),
"azurerm_image": dataSourceImage(),
"azurerm_images": dataSourceImages(),
"azurerm_disk_access": dataSourceDiskAccess(),
"azurerm_platform_image": dataSourcePlatformImage(),
"azurerm_proximity_placement_group": dataSourceProximityPlacementGroup(),
"azurerm_shared_image_gallery": dataSourceSharedImageGallery(),
"azurerm_shared_image_version": dataSourceSharedImageVersion(),
"azurerm_shared_image_versions": dataSourceSharedImageVersions(),
"azurerm_shared_image": dataSourceSharedImage(),
"azurerm_snapshot": dataSourceSnapshot(),
"azurerm_virtual_machine": dataSourceVirtualMachine(),
"azurerm_virtual_machine_scale_set": dataSourceVirtualMachineScaleSet(),
"azurerm_ssh_public_key": dataSourceSshPublicKey(),
"azurerm_managed_disk_export": dataSourceManagedDiskExport(),
"azurerm_managed_disk_export_revoke": dataSourceManagedDiskExportRevoke(),
}
}

Expand Down
Loading