github.com/bradfeehan/terraform@v0.7.0-rc3.0.20170529055808-34b45c5ad841/builtin/providers/azurerm/resource_arm_managed_disk.go (about)

     1  package azurerm
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net/http"
     7  	"strings"
     8  
     9  	"github.com/Azure/azure-sdk-for-go/arm/disk"
    10  	"github.com/hashicorp/terraform/helper/schema"
    11  	"github.com/hashicorp/terraform/helper/validation"
    12  )
    13  
    14  func resourceArmManagedDisk() *schema.Resource {
    15  	return &schema.Resource{
    16  		Create: resourceArmManagedDiskCreate,
    17  		Read:   resourceArmManagedDiskRead,
    18  		Update: resourceArmManagedDiskCreate,
    19  		Delete: resourceArmManagedDiskDelete,
    20  		Importer: &schema.ResourceImporter{
    21  			State: schema.ImportStatePassthrough,
    22  		},
    23  
    24  		Schema: map[string]*schema.Schema{
    25  			"name": {
    26  				Type:     schema.TypeString,
    27  				Required: true,
    28  				ForceNew: true,
    29  			},
    30  
    31  			"location": locationSchema(),
    32  
    33  			"resource_group_name": {
    34  				Type:     schema.TypeString,
    35  				Required: true,
    36  				ForceNew: true,
    37  			},
    38  
    39  			"storage_account_type": {
    40  				Type:     schema.TypeString,
    41  				Required: true,
    42  				ValidateFunc: validation.StringInSlice([]string{
    43  					string(disk.PremiumLRS),
    44  					string(disk.StandardLRS),
    45  				}, true),
    46  			},
    47  
    48  			"create_option": {
    49  				Type:     schema.TypeString,
    50  				Required: true,
    51  				ForceNew: true,
    52  				ValidateFunc: validation.StringInSlice([]string{
    53  					string(disk.Import),
    54  					string(disk.Empty),
    55  					string(disk.Copy),
    56  				}, true),
    57  			},
    58  
    59  			"source_uri": {
    60  				Type:     schema.TypeString,
    61  				Optional: true,
    62  				Computed: true,
    63  				ForceNew: true,
    64  			},
    65  
    66  			"source_resource_id": {
    67  				Type:     schema.TypeString,
    68  				Optional: true,
    69  				ForceNew: true,
    70  			},
    71  
    72  			"os_type": {
    73  				Type:     schema.TypeString,
    74  				Optional: true,
    75  				ValidateFunc: validation.StringInSlice([]string{
    76  					string(disk.Windows),
    77  					string(disk.Linux),
    78  				}, true),
    79  			},
    80  
    81  			"disk_size_gb": {
    82  				Type:         schema.TypeInt,
    83  				Required:     true,
    84  				ValidateFunc: validateDiskSizeGB,
    85  			},
    86  
    87  			"tags": tagsSchema(),
    88  		},
    89  	}
    90  }
    91  
    92  func validateDiskSizeGB(v interface{}, k string) (ws []string, errors []error) {
    93  	value := v.(int)
    94  	if value < 1 || value > 4095 {
    95  		errors = append(errors, fmt.Errorf(
    96  			"The `disk_size_gb` can only be between 1 and 4095"))
    97  	}
    98  	return
    99  }
   100  
   101  func resourceArmManagedDiskCreate(d *schema.ResourceData, meta interface{}) error {
   102  	client := meta.(*ArmClient)
   103  	diskClient := client.diskClient
   104  
   105  	log.Printf("[INFO] preparing arguments for Azure ARM Managed Disk creation.")
   106  
   107  	name := d.Get("name").(string)
   108  	location := d.Get("location").(string)
   109  	resGroup := d.Get("resource_group_name").(string)
   110  	tags := d.Get("tags").(map[string]interface{})
   111  	expandedTags := expandTags(tags)
   112  
   113  	createDisk := disk.Model{
   114  		Name:     &name,
   115  		Location: &location,
   116  		Tags:     expandedTags,
   117  	}
   118  
   119  	storageAccountType := d.Get("storage_account_type").(string)
   120  	osType := d.Get("os_type").(string)
   121  
   122  	createDisk.Properties = &disk.Properties{
   123  		AccountType: disk.StorageAccountTypes(storageAccountType),
   124  		OsType:      disk.OperatingSystemTypes(osType),
   125  	}
   126  
   127  	if v := d.Get("disk_size_gb"); v != 0 {
   128  		diskSize := int32(v.(int))
   129  		createDisk.Properties.DiskSizeGB = &diskSize
   130  	}
   131  	createOption := d.Get("create_option").(string)
   132  
   133  	creationData := &disk.CreationData{
   134  		CreateOption: disk.CreateOption(createOption),
   135  	}
   136  
   137  	if strings.EqualFold(createOption, string(disk.Import)) {
   138  		if sourceUri := d.Get("source_uri").(string); sourceUri != "" {
   139  			creationData.SourceURI = &sourceUri
   140  		} else {
   141  			return fmt.Errorf("[ERROR] source_uri must be specified when create_option is `%s`", disk.Import)
   142  		}
   143  	} else if strings.EqualFold(createOption, string(disk.Copy)) {
   144  		if sourceResourceId := d.Get("source_resource_id").(string); sourceResourceId != "" {
   145  			creationData.SourceResourceID = &sourceResourceId
   146  		} else {
   147  			return fmt.Errorf("[ERROR] source_resource_id must be specified when create_option is `%s`", disk.Copy)
   148  		}
   149  	}
   150  
   151  	createDisk.CreationData = creationData
   152  
   153  	_, diskErr := diskClient.CreateOrUpdate(resGroup, name, createDisk, make(chan struct{}))
   154  	if diskErr != nil {
   155  		return diskErr
   156  	}
   157  
   158  	read, err := diskClient.Get(resGroup, name)
   159  	if err != nil {
   160  		return err
   161  	}
   162  	if read.ID == nil {
   163  		return fmt.Errorf("[ERROR] Cannot read Managed Disk %s (resource group %s) ID", name, resGroup)
   164  	}
   165  
   166  	d.SetId(*read.ID)
   167  
   168  	return resourceArmManagedDiskRead(d, meta)
   169  }
   170  
   171  func resourceArmManagedDiskRead(d *schema.ResourceData, meta interface{}) error {
   172  	diskClient := meta.(*ArmClient).diskClient
   173  
   174  	id, err := parseAzureResourceID(d.Id())
   175  	if err != nil {
   176  		return err
   177  	}
   178  	resGroup := id.ResourceGroup
   179  	name := id.Path["disks"]
   180  
   181  	resp, err := diskClient.Get(resGroup, name)
   182  	if err != nil {
   183  		if resp.StatusCode == http.StatusNotFound {
   184  			d.SetId("")
   185  			return nil
   186  		}
   187  		return fmt.Errorf("[ERROR] Error making Read request on Azure Managed Disk %s (resource group %s): %s", name, resGroup, err)
   188  	}
   189  
   190  	d.Set("name", resp.Name)
   191  	d.Set("resource_group_name", resGroup)
   192  	d.Set("location", resp.Location)
   193  
   194  	if resp.Properties != nil {
   195  		flattenAzureRmManagedDiskProperties(d, resp.Properties)
   196  	}
   197  
   198  	if resp.CreationData != nil {
   199  		flattenAzureRmManagedDiskCreationData(d, resp.CreationData)
   200  	}
   201  
   202  	flattenAndSetTags(d, resp.Tags)
   203  
   204  	return nil
   205  }
   206  
   207  func resourceArmManagedDiskDelete(d *schema.ResourceData, meta interface{}) error {
   208  	diskClient := meta.(*ArmClient).diskClient
   209  
   210  	id, err := parseAzureResourceID(d.Id())
   211  	if err != nil {
   212  		return err
   213  	}
   214  	resGroup := id.ResourceGroup
   215  	name := id.Path["disks"]
   216  
   217  	if _, err = diskClient.Delete(resGroup, name, make(chan struct{})); err != nil {
   218  		return err
   219  	}
   220  
   221  	return nil
   222  }
   223  
   224  func flattenAzureRmManagedDiskProperties(d *schema.ResourceData, properties *disk.Properties) {
   225  	d.Set("storage_account_type", string(properties.AccountType))
   226  	if properties.DiskSizeGB != nil {
   227  		d.Set("disk_size_gb", *properties.DiskSizeGB)
   228  	}
   229  	if properties.OsType != "" {
   230  		d.Set("os_type", string(properties.OsType))
   231  	}
   232  }
   233  
   234  func flattenAzureRmManagedDiskCreationData(d *schema.ResourceData, creationData *disk.CreationData) {
   235  	d.Set("create_option", string(creationData.CreateOption))
   236  	if creationData.SourceURI != nil {
   237  		d.Set("source_uri", *creationData.SourceURI)
   238  	}
   239  }