github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/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": {
    37  				Type:      schema.TypeString,
    38  				Required:  true,
    39  				ForceNew:  true,
    40  				StateFunc: azureRMNormalizeLocation,
    41  			},
    42  
    43  			"resource_group_name": {
    44  				Type:     schema.TypeString,
    45  				Required: true,
    46  				ForceNew: true,
    47  			},
    48  
    49  			"sku": {
    50  				Type:     schema.TypeSet,
    51  				Required: true,
    52  				Elem: &schema.Resource{
    53  					Schema: map[string]*schema.Schema{
    54  						"name": {
    55  							Type:     schema.TypeString,
    56  							Required: true,
    57  							ValidateFunc: validation.StringInSlice([]string{
    58  								string(keyvault.Standard),
    59  								string(keyvault.Premium),
    60  							}, false),
    61  						},
    62  					},
    63  				},
    64  			},
    65  
    66  			"vault_uri": {
    67  				Type:     schema.TypeString,
    68  				Computed: true,
    69  			},
    70  
    71  			"tenant_id": {
    72  				Type:         schema.TypeString,
    73  				Required:     true,
    74  				ValidateFunc: validateUUID,
    75  			},
    76  
    77  			"access_policy": {
    78  				Type:     schema.TypeList,
    79  				Optional: true,
    80  				MinItems: 1,
    81  				Elem: &schema.Resource{
    82  					Schema: map[string]*schema.Schema{
    83  						"tenant_id": {
    84  							Type:         schema.TypeString,
    85  							Required:     true,
    86  							ValidateFunc: validateUUID,
    87  						},
    88  						"object_id": {
    89  							Type:         schema.TypeString,
    90  							Required:     true,
    91  							ValidateFunc: validateUUID,
    92  						},
    93  						"key_permissions": {
    94  							Type:     schema.TypeList,
    95  							Required: true,
    96  							Elem: &schema.Schema{
    97  								Type: schema.TypeString,
    98  								ValidateFunc: validation.StringInSlice([]string{
    99  									string(keyvault.All),
   100  									string(keyvault.Backup),
   101  									string(keyvault.Create),
   102  									string(keyvault.Decrypt),
   103  									string(keyvault.Delete),
   104  									string(keyvault.Encrypt),
   105  									string(keyvault.Get),
   106  									string(keyvault.Import),
   107  									string(keyvault.List),
   108  									string(keyvault.Restore),
   109  									string(keyvault.Sign),
   110  									string(keyvault.Unwrapkey),
   111  									string(keyvault.Update),
   112  									string(keyvault.Verify),
   113  									string(keyvault.Wrapkey),
   114  								}, false),
   115  							},
   116  						},
   117  						"secret_permissions": {
   118  							Type:     schema.TypeList,
   119  							Required: true,
   120  							Elem: &schema.Schema{
   121  								Type: schema.TypeString,
   122  								ValidateFunc: validation.StringInSlice([]string{
   123  									string(keyvault.SecretPermissionsAll),
   124  									string(keyvault.SecretPermissionsDelete),
   125  									string(keyvault.SecretPermissionsGet),
   126  									string(keyvault.SecretPermissionsList),
   127  									string(keyvault.SecretPermissionsSet),
   128  								}, false),
   129  							},
   130  						},
   131  					},
   132  				},
   133  			},
   134  
   135  			"enabled_for_deployment": {
   136  				Type:     schema.TypeBool,
   137  				Optional: true,
   138  			},
   139  
   140  			"enabled_for_disk_encryption": {
   141  				Type:     schema.TypeBool,
   142  				Optional: true,
   143  			},
   144  
   145  			"enabled_for_template_deployment": {
   146  				Type:     schema.TypeBool,
   147  				Optional: true,
   148  			},
   149  
   150  			"tags": tagsSchema(),
   151  		},
   152  	}
   153  }
   154  
   155  func resourceArmKeyVaultCreate(d *schema.ResourceData, meta interface{}) error {
   156  	client := meta.(*ArmClient).keyVaultClient
   157  	log.Printf("[INFO] preparing arguments for Azure ARM KeyVault creation.")
   158  
   159  	name := d.Get("name").(string)
   160  	location := d.Get("location").(string)
   161  	resGroup := d.Get("resource_group_name").(string)
   162  	tenantUUID := uuid.FromStringOrNil(d.Get("tenant_id").(string))
   163  	enabledForDeployment := d.Get("enabled_for_deployment").(bool)
   164  	enabledForDiskEncryption := d.Get("enabled_for_disk_encryption").(bool)
   165  	enabledForTemplateDeployment := d.Get("enabled_for_template_deployment").(bool)
   166  	tags := d.Get("tags").(map[string]interface{})
   167  
   168  	parameters := keyvault.VaultCreateOrUpdateParameters{
   169  		Location: &location,
   170  		Properties: &keyvault.VaultProperties{
   171  			TenantID:                     &tenantUUID,
   172  			Sku:                          expandKeyVaultSku(d),
   173  			AccessPolicies:               expandKeyVaultAccessPolicies(d),
   174  			EnabledForDeployment:         &enabledForDeployment,
   175  			EnabledForDiskEncryption:     &enabledForDiskEncryption,
   176  			EnabledForTemplateDeployment: &enabledForTemplateDeployment,
   177  		},
   178  		Tags: expandTags(tags),
   179  	}
   180  
   181  	_, err := client.CreateOrUpdate(resGroup, name, parameters)
   182  	if err != nil {
   183  		return err
   184  	}
   185  
   186  	read, err := client.Get(resGroup, name)
   187  	if err != nil {
   188  		return err
   189  	}
   190  	if read.ID == nil {
   191  		return fmt.Errorf("Cannot read KeyVault %s (resource group %s) ID", name, resGroup)
   192  	}
   193  
   194  	d.SetId(*read.ID)
   195  
   196  	return resourceArmKeyVaultRead(d, meta)
   197  }
   198  
   199  func resourceArmKeyVaultRead(d *schema.ResourceData, meta interface{}) error {
   200  	client := meta.(*ArmClient).keyVaultClient
   201  
   202  	id, err := parseAzureResourceID(d.Id())
   203  	if err != nil {
   204  		return err
   205  	}
   206  	resGroup := id.ResourceGroup
   207  	name := id.Path["vaults"]
   208  
   209  	resp, err := client.Get(resGroup, name)
   210  	if err != nil {
   211  		return fmt.Errorf("Error making Read request on Azure KeyVault %s: %s", name, err)
   212  	}
   213  	if resp.StatusCode == http.StatusNotFound {
   214  		d.SetId("")
   215  		return nil
   216  	}
   217  
   218  	d.Set("name", resp.Name)
   219  	d.Set("resource_group_name", resGroup)
   220  	d.Set("location", azureRMNormalizeLocation(*resp.Location))
   221  	d.Set("tenant_id", resp.Properties.TenantID.String())
   222  	d.Set("enabled_for_deployment", resp.Properties.EnabledForDeployment)
   223  	d.Set("enabled_for_disk_encryption", resp.Properties.EnabledForDiskEncryption)
   224  	d.Set("enabled_for_template_deployment", resp.Properties.EnabledForTemplateDeployment)
   225  	d.Set("sku", flattenKeyVaultSku(resp.Properties.Sku))
   226  	d.Set("access_policy", flattenKeyVaultAccessPolicies(resp.Properties.AccessPolicies))
   227  	d.Set("vault_uri", resp.Properties.VaultURI)
   228  
   229  	flattenAndSetTags(d, resp.Tags)
   230  
   231  	return nil
   232  }
   233  
   234  func resourceArmKeyVaultDelete(d *schema.ResourceData, meta interface{}) error {
   235  	client := meta.(*ArmClient).keyVaultClient
   236  
   237  	id, err := parseAzureResourceID(d.Id())
   238  	if err != nil {
   239  		return err
   240  	}
   241  	resGroup := id.ResourceGroup
   242  	name := id.Path["vaults"]
   243  
   244  	_, err = client.Delete(resGroup, name)
   245  
   246  	return err
   247  }
   248  
   249  func expandKeyVaultSku(d *schema.ResourceData) *keyvault.Sku {
   250  	skuSets := d.Get("sku").(*schema.Set).List()
   251  	sku := skuSets[0].(map[string]interface{})
   252  
   253  	return &keyvault.Sku{
   254  		Family: &armKeyVaultSkuFamily,
   255  		Name:   keyvault.SkuName(sku["name"].(string)),
   256  	}
   257  }
   258  
   259  func expandKeyVaultAccessPolicies(d *schema.ResourceData) *[]keyvault.AccessPolicyEntry {
   260  	policies := d.Get("access_policy").([]interface{})
   261  	result := make([]keyvault.AccessPolicyEntry, 0, len(policies))
   262  
   263  	for _, policySet := range policies {
   264  		policyRaw := policySet.(map[string]interface{})
   265  
   266  		keyPermissionsRaw := policyRaw["key_permissions"].([]interface{})
   267  		keyPermissions := []keyvault.KeyPermissions{}
   268  		for _, permission := range keyPermissionsRaw {
   269  			keyPermissions = append(keyPermissions, keyvault.KeyPermissions(permission.(string)))
   270  		}
   271  
   272  		secretPermissionsRaw := policyRaw["secret_permissions"].([]interface{})
   273  		secretPermissions := []keyvault.SecretPermissions{}
   274  		for _, permission := range secretPermissionsRaw {
   275  			secretPermissions = append(secretPermissions, keyvault.SecretPermissions(permission.(string)))
   276  		}
   277  
   278  		policy := keyvault.AccessPolicyEntry{
   279  			Permissions: &keyvault.Permissions{
   280  				Keys:    &keyPermissions,
   281  				Secrets: &secretPermissions,
   282  			},
   283  		}
   284  
   285  		tenantUUID := uuid.FromStringOrNil(policyRaw["tenant_id"].(string))
   286  		policy.TenantID = &tenantUUID
   287  		objectUUID := uuid.FromStringOrNil(policyRaw["object_id"].(string))
   288  		policy.ObjectID = &objectUUID
   289  
   290  		result = append(result, policy)
   291  	}
   292  
   293  	return &result
   294  }
   295  
   296  func flattenKeyVaultSku(sku *keyvault.Sku) []interface{} {
   297  	result := map[string]interface{}{
   298  		"name": string(sku.Name),
   299  	}
   300  
   301  	return []interface{}{result}
   302  }
   303  
   304  func flattenKeyVaultAccessPolicies(policies *[]keyvault.AccessPolicyEntry) []interface{} {
   305  	result := make([]interface{}, 0, len(*policies))
   306  
   307  	for _, policy := range *policies {
   308  		policyRaw := make(map[string]interface{})
   309  
   310  		keyPermissionsRaw := make([]interface{}, 0, len(*policy.Permissions.Keys))
   311  		for _, keyPermission := range *policy.Permissions.Keys {
   312  			keyPermissionsRaw = append(keyPermissionsRaw, string(keyPermission))
   313  		}
   314  
   315  		secretPermissionsRaw := make([]interface{}, 0, len(*policy.Permissions.Secrets))
   316  		for _, secretPermission := range *policy.Permissions.Secrets {
   317  			secretPermissionsRaw = append(secretPermissionsRaw, string(secretPermission))
   318  		}
   319  
   320  		policyRaw["tenant_id"] = policy.TenantID.String()
   321  		policyRaw["object_id"] = policy.ObjectID.String()
   322  		policyRaw["key_permissions"] = keyPermissionsRaw
   323  		policyRaw["secret_permissions"] = secretPermissionsRaw
   324  
   325  		result = append(result, policyRaw)
   326  	}
   327  
   328  	return result
   329  }