github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/azurerm/resource_arm_key_vault.go (about)

     1  package azurerm
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net/http"
     7  
     8  	"github.com/Azure/azure-sdk-for-go/arm/keyvault"
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  	"github.com/hashicorp/terraform/helper/validation"
    11  	"github.com/satori/uuid"
    12  )
    13  
    14  // As can be seen in the API definition, the Sku Family only supports the value
    15  // `A` and is a required field
    16  // https://github.com/Azure/azure-rest-api-specs/blob/master/arm-keyvault/2015-06-01/swagger/keyvault.json#L239
    17  var armKeyVaultSkuFamily = "A"
    18  
    19  func resourceArmKeyVault() *schema.Resource {
    20  	return &schema.Resource{
    21  		Create: resourceArmKeyVaultCreate,
    22  		Read:   resourceArmKeyVaultRead,
    23  		Update: resourceArmKeyVaultCreate,
    24  		Delete: resourceArmKeyVaultDelete,
    25  		Importer: &schema.ResourceImporter{
    26  			State: schema.ImportStatePassthrough,
    27  		},
    28  
    29  		Schema: map[string]*schema.Schema{
    30  			"name": {
    31  				Type:     schema.TypeString,
    32  				Required: true,
    33  				ForceNew: true,
    34  			},
    35  
    36  			"location": locationSchema(),
    37  
    38  			"resource_group_name": {
    39  				Type:     schema.TypeString,
    40  				Required: true,
    41  				ForceNew: true,
    42  			},
    43  
    44  			"sku": {
    45  				Type:     schema.TypeSet,
    46  				Required: true,
    47  				Elem: &schema.Resource{
    48  					Schema: map[string]*schema.Schema{
    49  						"name": {
    50  							Type:     schema.TypeString,
    51  							Required: true,
    52  							ValidateFunc: validation.StringInSlice([]string{
    53  								string(keyvault.Standard),
    54  								string(keyvault.Premium),
    55  							}, false),
    56  						},
    57  					},
    58  				},
    59  			},
    60  
    61  			"vault_uri": {
    62  				Type:     schema.TypeString,
    63  				Computed: true,
    64  			},
    65  
    66  			"tenant_id": {
    67  				Type:         schema.TypeString,
    68  				Required:     true,
    69  				ValidateFunc: validateUUID,
    70  			},
    71  
    72  			"access_policy": {
    73  				Type:     schema.TypeList,
    74  				Optional: true,
    75  				MinItems: 1,
    76  				Elem: &schema.Resource{
    77  					Schema: map[string]*schema.Schema{
    78  						"tenant_id": {
    79  							Type:         schema.TypeString,
    80  							Required:     true,
    81  							ValidateFunc: validateUUID,
    82  						},
    83  						"object_id": {
    84  							Type:         schema.TypeString,
    85  							Required:     true,
    86  							ValidateFunc: validateUUID,
    87  						},
    88  						"key_permissions": {
    89  							Type:     schema.TypeList,
    90  							Required: true,
    91  							Elem: &schema.Schema{
    92  								Type: schema.TypeString,
    93  								ValidateFunc: validation.StringInSlice([]string{
    94  									string(keyvault.KeyPermissionsAll),
    95  									string(keyvault.KeyPermissionsBackup),
    96  									string(keyvault.KeyPermissionsCreate),
    97  									string(keyvault.KeyPermissionsDecrypt),
    98  									string(keyvault.KeyPermissionsDelete),
    99  									string(keyvault.KeyPermissionsEncrypt),
   100  									string(keyvault.KeyPermissionsGet),
   101  									string(keyvault.KeyPermissionsImport),
   102  									string(keyvault.KeyPermissionsList),
   103  									string(keyvault.KeyPermissionsRestore),
   104  									string(keyvault.KeyPermissionsSign),
   105  									string(keyvault.KeyPermissionsUnwrapKey),
   106  									string(keyvault.KeyPermissionsUpdate),
   107  									string(keyvault.KeyPermissionsVerify),
   108  									string(keyvault.KeyPermissionsWrapKey),
   109  								}, false),
   110  							},
   111  						},
   112  						"secret_permissions": {
   113  							Type:     schema.TypeList,
   114  							Required: true,
   115  							Elem: &schema.Schema{
   116  								Type: schema.TypeString,
   117  								ValidateFunc: validation.StringInSlice([]string{
   118  									string(keyvault.SecretPermissionsAll),
   119  									string(keyvault.SecretPermissionsDelete),
   120  									string(keyvault.SecretPermissionsGet),
   121  									string(keyvault.SecretPermissionsList),
   122  									string(keyvault.SecretPermissionsSet),
   123  								}, false),
   124  							},
   125  						},
   126  					},
   127  				},
   128  			},
   129  
   130  			"enabled_for_deployment": {
   131  				Type:     schema.TypeBool,
   132  				Optional: true,
   133  			},
   134  
   135  			"enabled_for_disk_encryption": {
   136  				Type:     schema.TypeBool,
   137  				Optional: true,
   138  			},
   139  
   140  			"enabled_for_template_deployment": {
   141  				Type:     schema.TypeBool,
   142  				Optional: true,
   143  			},
   144  
   145  			"tags": tagsSchema(),
   146  		},
   147  	}
   148  }
   149  
   150  func resourceArmKeyVaultCreate(d *schema.ResourceData, meta interface{}) error {
   151  	client := meta.(*ArmClient).keyVaultClient
   152  	log.Printf("[INFO] preparing arguments for Azure ARM KeyVault creation.")
   153  
   154  	name := d.Get("name").(string)
   155  	location := d.Get("location").(string)
   156  	resGroup := d.Get("resource_group_name").(string)
   157  	tenantUUID := uuid.FromStringOrNil(d.Get("tenant_id").(string))
   158  	enabledForDeployment := d.Get("enabled_for_deployment").(bool)
   159  	enabledForDiskEncryption := d.Get("enabled_for_disk_encryption").(bool)
   160  	enabledForTemplateDeployment := d.Get("enabled_for_template_deployment").(bool)
   161  	tags := d.Get("tags").(map[string]interface{})
   162  
   163  	parameters := keyvault.VaultCreateOrUpdateParameters{
   164  		Location: &location,
   165  		Properties: &keyvault.VaultProperties{
   166  			TenantID:                     &tenantUUID,
   167  			Sku:                          expandKeyVaultSku(d),
   168  			AccessPolicies:               expandKeyVaultAccessPolicies(d),
   169  			EnabledForDeployment:         &enabledForDeployment,
   170  			EnabledForDiskEncryption:     &enabledForDiskEncryption,
   171  			EnabledForTemplateDeployment: &enabledForTemplateDeployment,
   172  		},
   173  		Tags: expandTags(tags),
   174  	}
   175  
   176  	_, err := client.CreateOrUpdate(resGroup, name, parameters)
   177  	if err != nil {
   178  		return err
   179  	}
   180  
   181  	read, err := client.Get(resGroup, name)
   182  	if err != nil {
   183  		return err
   184  	}
   185  	if read.ID == nil {
   186  		return fmt.Errorf("Cannot read KeyVault %s (resource group %s) ID", name, resGroup)
   187  	}
   188  
   189  	d.SetId(*read.ID)
   190  
   191  	return resourceArmKeyVaultRead(d, meta)
   192  }
   193  
   194  func resourceArmKeyVaultRead(d *schema.ResourceData, meta interface{}) error {
   195  	client := meta.(*ArmClient).keyVaultClient
   196  
   197  	id, err := parseAzureResourceID(d.Id())
   198  	if err != nil {
   199  		return err
   200  	}
   201  	resGroup := id.ResourceGroup
   202  	name := id.Path["vaults"]
   203  
   204  	resp, err := client.Get(resGroup, name)
   205  	if err != nil {
   206  		return fmt.Errorf("Error making Read request on Azure KeyVault %s: %s", name, err)
   207  	}
   208  	if resp.StatusCode == http.StatusNotFound {
   209  		d.SetId("")
   210  		return nil
   211  	}
   212  
   213  	d.Set("name", resp.Name)
   214  	d.Set("resource_group_name", resGroup)
   215  	d.Set("location", azureRMNormalizeLocation(*resp.Location))
   216  	d.Set("tenant_id", resp.Properties.TenantID.String())
   217  	d.Set("enabled_for_deployment", resp.Properties.EnabledForDeployment)
   218  	d.Set("enabled_for_disk_encryption", resp.Properties.EnabledForDiskEncryption)
   219  	d.Set("enabled_for_template_deployment", resp.Properties.EnabledForTemplateDeployment)
   220  	d.Set("sku", flattenKeyVaultSku(resp.Properties.Sku))
   221  	d.Set("access_policy", flattenKeyVaultAccessPolicies(resp.Properties.AccessPolicies))
   222  	d.Set("vault_uri", resp.Properties.VaultURI)
   223  
   224  	flattenAndSetTags(d, resp.Tags)
   225  
   226  	return nil
   227  }
   228  
   229  func resourceArmKeyVaultDelete(d *schema.ResourceData, meta interface{}) error {
   230  	client := meta.(*ArmClient).keyVaultClient
   231  
   232  	id, err := parseAzureResourceID(d.Id())
   233  	if err != nil {
   234  		return err
   235  	}
   236  	resGroup := id.ResourceGroup
   237  	name := id.Path["vaults"]
   238  
   239  	_, err = client.Delete(resGroup, name)
   240  
   241  	return err
   242  }
   243  
   244  func expandKeyVaultSku(d *schema.ResourceData) *keyvault.Sku {
   245  	skuSets := d.Get("sku").(*schema.Set).List()
   246  	sku := skuSets[0].(map[string]interface{})
   247  
   248  	return &keyvault.Sku{
   249  		Family: &armKeyVaultSkuFamily,
   250  		Name:   keyvault.SkuName(sku["name"].(string)),
   251  	}
   252  }
   253  
   254  func expandKeyVaultAccessPolicies(d *schema.ResourceData) *[]keyvault.AccessPolicyEntry {
   255  	policies := d.Get("access_policy").([]interface{})
   256  	result := make([]keyvault.AccessPolicyEntry, 0, len(policies))
   257  
   258  	for _, policySet := range policies {
   259  		policyRaw := policySet.(map[string]interface{})
   260  
   261  		keyPermissionsRaw := policyRaw["key_permissions"].([]interface{})
   262  		keyPermissions := []keyvault.KeyPermissions{}
   263  		for _, permission := range keyPermissionsRaw {
   264  			keyPermissions = append(keyPermissions, keyvault.KeyPermissions(permission.(string)))
   265  		}
   266  
   267  		secretPermissionsRaw := policyRaw["secret_permissions"].([]interface{})
   268  		secretPermissions := []keyvault.SecretPermissions{}
   269  		for _, permission := range secretPermissionsRaw {
   270  			secretPermissions = append(secretPermissions, keyvault.SecretPermissions(permission.(string)))
   271  		}
   272  
   273  		policy := keyvault.AccessPolicyEntry{
   274  			Permissions: &keyvault.Permissions{
   275  				Keys:    &keyPermissions,
   276  				Secrets: &secretPermissions,
   277  			},
   278  		}
   279  
   280  		tenantUUID := uuid.FromStringOrNil(policyRaw["tenant_id"].(string))
   281  		policy.TenantID = &tenantUUID
   282  		objectUUID := policyRaw["object_id"].(string)
   283  		policy.ObjectID = &objectUUID
   284  
   285  		result = append(result, policy)
   286  	}
   287  
   288  	return &result
   289  }
   290  
   291  func flattenKeyVaultSku(sku *keyvault.Sku) []interface{} {
   292  	result := map[string]interface{}{
   293  		"name": string(sku.Name),
   294  	}
   295  
   296  	return []interface{}{result}
   297  }
   298  
   299  func flattenKeyVaultAccessPolicies(policies *[]keyvault.AccessPolicyEntry) []interface{} {
   300  	result := make([]interface{}, 0, len(*policies))
   301  
   302  	for _, policy := range *policies {
   303  		policyRaw := make(map[string]interface{})
   304  
   305  		keyPermissionsRaw := make([]interface{}, 0, len(*policy.Permissions.Keys))
   306  		for _, keyPermission := range *policy.Permissions.Keys {
   307  			keyPermissionsRaw = append(keyPermissionsRaw, string(keyPermission))
   308  		}
   309  
   310  		secretPermissionsRaw := make([]interface{}, 0, len(*policy.Permissions.Secrets))
   311  		for _, secretPermission := range *policy.Permissions.Secrets {
   312  			secretPermissionsRaw = append(secretPermissionsRaw, string(secretPermission))
   313  		}
   314  
   315  		policyRaw["tenant_id"] = policy.TenantID.String()
   316  		policyRaw["object_id"] = policy.ObjectID
   317  		policyRaw["key_permissions"] = keyPermissionsRaw
   318  		policyRaw["secret_permissions"] = secretPermissionsRaw
   319  
   320  		result = append(result, policyRaw)
   321  	}
   322  
   323  	return result
   324  }