diff --git a/builtin/providers/azurerm/config.go b/builtin/providers/azurerm/config.go index acd66ce49..497a7afce 100644 --- a/builtin/providers/azurerm/config.go +++ b/builtin/providers/azurerm/config.go @@ -422,6 +422,25 @@ func (armClient *ArmClient) getBlobStorageClientForStorageAccount(resourceGroupN blobClient := storageClient.GetBlobService() return &blobClient, true, nil } + +func (armClient *ArmClient) getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.FileServiceClient, bool, error) { + key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) + if err != nil { + return nil, accountExists, err + } + if accountExists == false { + return nil, false, nil + } + + storageClient, err := mainStorage.NewBasicClient(storageAccountName, key) + if err != nil { + return nil, true, fmt.Errorf("Error creating storage client for storage account %q: %s", storageAccountName, err) + } + + fileClient := storageClient.GetFileService() + return &fileClient, true, nil +} + func (armClient *ArmClient) getTableServiceClientForStorageAccount(resourceGroupName, storageAccountName string) (*mainStorage.TableServiceClient, bool, error) { key, accountExists, err := armClient.getKeyForStorageAccount(resourceGroupName, storageAccountName) if err != nil { diff --git a/builtin/providers/azurerm/provider.go b/builtin/providers/azurerm/provider.go index ed74f849d..e6aec8034 100644 --- a/builtin/providers/azurerm/provider.go +++ b/builtin/providers/azurerm/provider.go @@ -75,6 +75,7 @@ func Provider() terraform.ResourceProvider { "azurerm_storage_account": resourceArmStorageAccount(), "azurerm_storage_blob": resourceArmStorageBlob(), "azurerm_storage_container": resourceArmStorageContainer(), + "azurerm_storage_share": resourceArmStorageShare(), "azurerm_storage_queue": resourceArmStorageQueue(), "azurerm_storage_table": resourceArmStorageTable(), "azurerm_subnet": resourceArmSubnet(), diff --git a/builtin/providers/azurerm/resource_arm_storage_share.go b/builtin/providers/azurerm/resource_arm_storage_share.go new file mode 100644 index 000000000..62d572210 --- /dev/null +++ b/builtin/providers/azurerm/resource_arm_storage_share.go @@ -0,0 +1,193 @@ +package azurerm + +import ( + "fmt" + "log" + // "strings" + "regexp" + "strconv" + + "github.com/Azure/azure-sdk-for-go/storage" + "github.com/hashicorp/terraform/helper/schema" +) + +func resourceArmStorageShare() *schema.Resource { + return &schema.Resource{ + Create: resourceArmStorageShareCreate, + Read: resourceArmStorageShareRead, + Exists: resourceArmStorageShareExists, + Delete: resourceArmStorageShareDelete, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateArmStorageShareName, + }, + "resource_group_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "storage_account_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "quota": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Default: 0, + }, + "url": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} +func resourceArmStorageShareCreate(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + + resourceGroupName := d.Get("resource_group_name").(string) + storageAccountName := d.Get("storage_account_name").(string) + + fileClient, accountExists, err := armClient.getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName) + if err != nil { + return err + } + if !accountExists { + return fmt.Errorf("Storage Account %q Not Found", storageAccountName) + } + + name := d.Get("name").(string) + + log.Printf("[INFO] Creating share %q in storage account %q", name, storageAccountName) + err = fileClient.CreateShare(name) + + log.Printf("[INFO] Setting share %q properties in storage account %q", name, storageAccountName) + fileClient.SetShareProperties(name, storage.ShareHeaders{Quota: strconv.Itoa(d.Get("quota").(int))}) + + d.SetId(name) + return resourceArmStorageShareRead(d, meta) +} + +func resourceArmStorageShareRead(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + + resourceGroupName := d.Get("resource_group_name").(string) + storageAccountName := d.Get("storage_account_name").(string) + + fileClient, accountExists, err := armClient.getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName) + if err != nil { + return err + } + if !accountExists { + log.Printf("[DEBUG] Storage account %q not found, removing file %q from state", storageAccountName, d.Id()) + d.SetId("") + return nil + } + + exists, err := resourceArmStorageShareExists(d, meta) + if err != nil { + return err + } + + if !exists { + // Exists already removed this from state + return nil + } + + name := d.Get("name").(string) + + url := fileClient.GetShareURL(name) + if url == "" { + log.Printf("[INFO] URL for %q is empty", name) + } + d.Set("url", url) + + return nil +} + +func resourceArmStorageShareExists(d *schema.ResourceData, meta interface{}) (bool, error) { + armClient := meta.(*ArmClient) + + resourceGroupName := d.Get("resource_group_name").(string) + storageAccountName := d.Get("storage_account_name").(string) + + fileClient, accountExists, err := armClient.getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName) + if err != nil { + return false, err + } + if !accountExists { + log.Printf("[DEBUG] Storage account %q not found, removing share %q from state", storageAccountName, d.Id()) + d.SetId("") + return false, nil + } + + name := d.Get("name").(string) + + log.Printf("[INFO] Checking for existence of share %q.", name) + exists, err := fileClient.ShareExists(name) + if err != nil { + return false, fmt.Errorf("Error testing existence of share %q: %s", name, err) + } + + if !exists { + log.Printf("[INFO] Share %q no longer exists, removing from state...", name) + d.SetId("") + } + + return exists, nil +} + +func resourceArmStorageShareDelete(d *schema.ResourceData, meta interface{}) error { + armClient := meta.(*ArmClient) + + resourceGroupName := d.Get("resource_group_name").(string) + storageAccountName := d.Get("storage_account_name").(string) + + fileClient, accountExists, err := armClient.getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName) + if err != nil { + return err + } + if !accountExists { + log.Printf("[INFO]Storage Account %q doesn't exist so the file won't exist", storageAccountName) + return nil + } + + name := d.Get("name").(string) + + log.Printf("[INFO] Deleting storage file %q", name) + if _, err = fileClient.DeleteShareIfExists(name); err != nil { + return fmt.Errorf("Error deleting storage file %q: %s", name, err) + } + + d.SetId("") + return nil +} + +//Following the naming convention as laid out in the docs https://msdn.microsoft.com/library/azure/dn167011.aspx +func validateArmStorageShareName(v interface{}, k string) (ws []string, errors []error) { + value := v.(string) + if !regexp.MustCompile(`^[0-9a-z-]+$`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "only lowercase alphanumeric characters and hyphens allowed in %q: %q", + k, value)) + } + if len(value) < 3 || len(value) > 63 { + errors = append(errors, fmt.Errorf( + "%q must be between 3 and 63 characters: %q", k, value)) + } + if regexp.MustCompile(`^-`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "%q cannot begin with a hyphen: %q", k, value)) + } + if regexp.MustCompile(`[-]{2,}`).MatchString(value) { + errors = append(errors, fmt.Errorf( + "%q does not allow consecutive hyphens: %q", k, value)) + } + return +} diff --git a/builtin/providers/azurerm/resource_arm_storage_share_test.go b/builtin/providers/azurerm/resource_arm_storage_share_test.go new file mode 100644 index 000000000..b8880e556 --- /dev/null +++ b/builtin/providers/azurerm/resource_arm_storage_share_test.go @@ -0,0 +1,241 @@ +package azurerm + +import ( + "fmt" + "log" + "strings" + "testing" + + "github.com/Azure/azure-sdk-for-go/storage" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" +) + +func TestAccAzureRMStorageShare_basic(t *testing.T) { + var sS storage.Share + + ri := acctest.RandInt() + rs := strings.ToLower(acctest.RandString(11)) + config := fmt.Sprintf(testAccAzureRMStorageShare_basic, ri, rs) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMStorageShareDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMStorageShareExists("azurerm_storage_share.test", &sS), + ), + }, + }, + }) +} + +func TestAccAzureRMStorageShare_disappears(t *testing.T) { + var sS storage.Share + + ri := acctest.RandInt() + rs := strings.ToLower(acctest.RandString(11)) + config := fmt.Sprintf(testAccAzureRMStorageShare_basic, ri, rs) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMStorageShareDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMStorageShareExists("azurerm_storage_share.test", &sS), + testAccARMStorageShareDisappears("azurerm_storage_share.test", &sS), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + +func testCheckAzureRMStorageShareExists(name string, sS *storage.Share) resource.TestCheckFunc { + return func(s *terraform.State) error { + + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + name := rs.Primary.Attributes["name"] + storageAccountName := rs.Primary.Attributes["storage_account_name"] + resourceGroupName, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for share: %s", name) + } + + armClient := testAccProvider.Meta().(*ArmClient) + fileClient, accountExists, err := armClient.getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName) + if err != nil { + return err + } + if !accountExists { + return fmt.Errorf("Bad: Storage Account %q does not exist", storageAccountName) + } + + shares, err := fileClient.ListShares(storage.ListSharesParameters{ + Prefix: name, + Timeout: 90, + }) + + if len(shares.Shares) == 0 { + return fmt.Errorf("Bad: Share %q (storage account: %q) does not exist", name, storageAccountName) + } + + var found bool + for _, share := range shares.Shares { + if share.Name == name { + found = true + *sS = share + } + } + + if !found { + return fmt.Errorf("Bad: Share %q (storage account: %q) does not exist", name, storageAccountName) + } + + return nil + } +} + +func testAccARMStorageShareDisappears(name string, sS *storage.Share) resource.TestCheckFunc { + return func(s *terraform.State) error { + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %s", name) + } + + armClient := testAccProvider.Meta().(*ArmClient) + + storageAccountName := rs.Primary.Attributes["storage_account_name"] + resourceGroupName, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for storage share: %s", sS.Name) + } + + fileClient, accountExists, err := armClient.getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName) + if err != nil { + return err + } + if !accountExists { + log.Printf("[INFO]Storage Account %q doesn't exist so the share won't exist", storageAccountName) + return nil + } + + _, err = fileClient.DeleteShareIfExists(sS.Name) + if err != nil { + return err + } + + return nil + } +} + +func testCheckAzureRMStorageShareDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_storage_share" { + continue + } + + name := rs.Primary.Attributes["name"] + storageAccountName := rs.Primary.Attributes["storage_account_name"] + resourceGroupName, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for share: %s", name) + } + + armClient := testAccProvider.Meta().(*ArmClient) + fileClient, accountExists, err := armClient.getFileServiceClientForStorageAccount(resourceGroupName, storageAccountName) + if err != nil { + //If we can't get keys then the blob can't exist + return nil + } + if !accountExists { + return nil + } + + shares, err := fileClient.ListShares(storage.ListSharesParameters{ + Prefix: name, + Timeout: 90, + }) + + if err != nil { + return nil + } + + var found bool + for _, share := range shares.Shares { + if share.Name == name { + found = true + } + } + + if found { + return fmt.Errorf("Bad: Share %q (storage account: %q) still exists", name, storageAccountName) + } + } + + return nil +} + +func TestValidateArmStorageShareName(t *testing.T) { + validNames := []string{ + "valid-name", + "valid02-name", + } + for _, v := range validNames { + _, errors := validateArmStorageShareName(v, "name") + if len(errors) != 0 { + t.Fatalf("%q should be a valid Share Name: %q", v, errors) + } + } + + invalidNames := []string{ + "InvalidName1", + "-invalidname1", + "invalid_name", + "invalid!", + "double-hyphen--invalid", + "ww", + strings.Repeat("w", 65), + } + for _, v := range invalidNames { + _, errors := validateArmStorageShareName(v, "name") + if len(errors) == 0 { + t.Fatalf("%q should be an invalid Share Name", v) + } + } +} + +var testAccAzureRMStorageShare_basic = ` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "westus" +} + +resource "azurerm_storage_account" "test" { + name = "acctestacc%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "westus" + account_type = "Standard_LRS" + + tags { + environment = "staging" + } +} + +resource "azurerm_storage_share" "test" { + name = "testshare" + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_name = "${azurerm_storage_account.test.name}" +} +` diff --git a/website/source/docs/providers/azurerm/r/storage_share.html.markdown b/website/source/docs/providers/azurerm/r/storage_share.html.markdown new file mode 100644 index 000000000..667533001 --- /dev/null +++ b/website/source/docs/providers/azurerm/r/storage_share.html.markdown @@ -0,0 +1,58 @@ +--- +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_storage_share" +sidebar_current: "docs-azurerm-resource-storage-share" +description: |- + Create an Azure Storage Share. +--- + +# azurerm\_storage\_share + +Create an Azure Storage File Share. + +## Example Usage + +``` +resource "azurerm_resource_group" "test" { + name = "acctestrg-%d" + location = "westus" +} + +resource "azurerm_storage_account" "test" { + name = "acctestacc%s" + resource_group_name = "${azurerm_resource_group.test.name}" + location = "westus" + account_type = "Standard_LRS" +} + +resource "azurerm_storage_share" "testshare" { + name = "sharename" + + resource_group_name = "${azurerm_resource_group.test.name}" + storage_account_name = "${azurerm_storage_account.test.name}" + + quota = 50 +} +``` + +## Argument Reference + +The following arguments are supported: + +* `name` - (Required) The name of the share. Must be unique within the storage account where the share is located. + +* `resource_group_name` - (Required) The name of the resource group in which to + create the share. Changing this forces a new resource to be created. + +* `storage_account_name` - (Required) Specifies the storage account in which to create the share. + Changing this forces a new resource to be created. + +* `quota` - (Optional) The maximum size of the share, in gigabytes. Must be greater than 0, and less than or equal to 5 TB (5120 GB). Default this is set to 0 which results in setting the quota to 5 TB. + + +## Attributes Reference + +The following attributes are exported in addition to the arguments listed above: + +* `id` - The storage share Resource ID. +* `url` - The URL of the share