From e10f10aa709736e93cdbfc0e9b9cb0bba78e16df Mon Sep 17 00:00:00 2001 From: Damien Caro Date: Tue, 6 Mar 2018 22:37:33 -0800 Subject: [PATCH 001/320] Added support for vpn client protocol and radius server --- .../resource_arm_virtual_network_gateway.go | 59 ++++++++++++++- ...source_arm_virtual_network_gateway_test.go | 75 +++++++++++++++++++ .../r/virtual_network_gateway.html.markdown | 13 +++- 3 files changed, 145 insertions(+), 2 deletions(-) diff --git a/azurerm/resource_arm_virtual_network_gateway.go b/azurerm/resource_arm_virtual_network_gateway.go index 26d6259181f7..998e94704b3e 100644 --- a/azurerm/resource_arm_virtual_network_gateway.go +++ b/azurerm/resource_arm_virtual_network_gateway.go @@ -137,9 +137,20 @@ func resourceArmVirtualNetworkGateway() *schema.Resource { Type: schema.TypeString, }, }, + "vpn_client_protocol": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, "root_certificate": { Type: schema.TypeSet, - Required: true, + Optional: true, + ConflictsWith: []string{ + "vpn_client_configuration.0.radius_server_address", + "vpn_client_configuration.0.radius_server_secret", + }, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { @@ -157,6 +168,10 @@ func resourceArmVirtualNetworkGateway() *schema.Resource { "revoked_certificate": { Type: schema.TypeSet, Optional: true, + ConflictsWith: []string{ + "vpn_client_configuration.0.radius_server_address", + "vpn_client_configuration.0.radius_server_secret", + }, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ "name": { @@ -171,6 +186,28 @@ func resourceArmVirtualNetworkGateway() *schema.Resource { }, Set: hashVirtualNetworkGatewayRevokedCert, }, + "radius_server_address": { + Type: schema.TypeString, + Optional: true, + ConflictsWith: []string{ + "vpn_client_configuration.0.root_certificate", + "vpn_client_configuration.0.revoked_certificate", + }, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "radius_server_secret": { + Type: schema.TypeString, + Optional: true, + ConflictsWith: []string{ + "vpn_client_configuration.0.root_certificate", + "vpn_client_configuration.0.revoked_certificate", + }, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, }, }, }, @@ -491,12 +528,24 @@ func expandArmVirtualNetworkGatewayVpnClientConfig(d *schema.ResourceData) *netw revokedCerts = append(revokedCerts, r) } + confVpnClientProtocol := conf["vpn_client_protocol"].([]interface{}) + vpnClientProtocols := make([]network.VpnClientProtocol, 0, len(confVpnClientProtocol)) + for _, protocol := range confVpnClientProtocol { + vpnClientProtocols = append(vpnClientProtocols, network.VpnClientProtocol(protocol.(string))) + } + + confRadiusServerAddress := conf["radius_server_address"].(string) + confRadiusServerSecret := conf["radius_server_secret"].(string) + return &network.VpnClientConfiguration{ VpnClientAddressPool: &network.AddressSpace{ AddressPrefixes: &addresses, }, VpnClientRootCertificates: &rootCerts, VpnClientRevokedCertificates: &revokedCerts, + VpnClientProtocols: &vpnClientProtocols, + RadiusServerAddress: &confRadiusServerAddress, + RadiusServerSecret: &confRadiusServerSecret, } } @@ -574,6 +623,14 @@ func flattenArmVirtualNetworkGatewayVpnClientConfig(cfg *network.VpnClientConfig } flat["revoked_certificate"] = schema.NewSet(hashVirtualNetworkGatewayRevokedCert, revokedCerts) + vpnClientProtocol := make([]interface{}, 0) + if vpnProtocols := cfg.VpnClientProtocols; vpnProtocols != nil { + for _, vpnProtocol := range *vpnProtocols { + vpnClientProtocol = append(vpnClientProtocol, vpnProtocol) + } + } + flat["vpn_client_protocol"] = vpnClientProtocol + return []interface{}{flat} } diff --git a/azurerm/resource_arm_virtual_network_gateway_test.go b/azurerm/resource_arm_virtual_network_gateway_test.go index 597e6d2d16da..3e58b6cf9551 100644 --- a/azurerm/resource_arm_virtual_network_gateway_test.go +++ b/azurerm/resource_arm_virtual_network_gateway_test.go @@ -48,6 +48,25 @@ func TestAccAzureRMVirtualNetworkGateway_vpnGw1(t *testing.T) { }) } +func TestAccAzureRMVirtualNetworkGateway_vpnClientRadius(t *testing.T) { + ri := acctest.RandInt() + config := testAccAzureRMVirtualNetworkGateway_vpnClient(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMVirtualNetworkGatewayDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMVirtualNetworkGatewayExists("azurerm_virtual_network_gateway.test"), + ), + }, + }, + }) +} + func testCheckAzureRMVirtualNetworkGatewayExists(name string) resource.TestCheckFunc { return func(s *terraform.State) error { name, resourceGroup, err := getArmResourceNameAndGroup(s, name) @@ -188,3 +207,59 @@ resource "azurerm_virtual_network_gateway" "test" { } `, rInt, location, rInt, rInt, rInt) } + +func testAccAzureRMVirtualNetworkGateway_vpnClient(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_virtual_network" "test" { + name = "acctestvn-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + address_space = ["10.0.0.0/16"] +} + +resource "azurerm_subnet" "test" { + name = "GatewaySubnet" + resource_group_name = "${azurerm_resource_group.test.name}" + virtual_network_name = "${azurerm_virtual_network.test.name}" + address_prefix = "10.0.1.0/24" +} + +resource "azurerm_public_ip" "test" { + name = "acctestpip-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + public_ip_address_allocation = "Dynamic" +} + +resource "azurerm_virtual_network_gateway" "test" { + name = "acctestvng-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + + type = "Vpn" + vpn_type = "RouteBased" + sku = "VpnGw1" + + ip_configuration { + public_ip_address_id = "${azurerm_public_ip.test.id}" + private_ip_address_allocation = "Dynamic" + subnet_id = "${azurerm_subnet.test.id}" + } + + vpn_client_configuration { + address_space = [ "11.2.0.0/24" ] + + vpn_client_protocol = [ "SSTP", "IkeV2" ] + + radius_server_address = "1.2.3.4" + radius_server_secret = "verysecretsecret" + + } +} +`, rInt, location, rInt, rInt, rInt) +} diff --git a/website/docs/r/virtual_network_gateway.html.markdown b/website/docs/r/virtual_network_gateway.html.markdown index 638ffedc6230..64f8329b6b19 100644 --- a/website/docs/r/virtual_network_gateway.html.markdown +++ b/website/docs/r/virtual_network_gateway.html.markdown @@ -170,12 +170,23 @@ The `vpn_client_configuration` block supports: vpn clients will be taken. You can provide more than one address space, e.g. in CIDR notation. -* `root_certificate` - (Required) One or more `root_certificate` blocks which are +* `vpn_client_protocol` - (Optional) List of the protocols supported by the vpn client. + The supported values are "SSTP" and "IkeV2". + +* `root_certificate` - (Optional) One or more `root_certificate` blocks which are defined below. These root certificates are used to sign the client certificate used by the VPN clients to connect to the gateway. + This setting is incompatible with the use of `radius_server_address` and `radius_server_secret`. * `revoked_certificate` - (Optional) One or more `revoked_certificate` blocks which are defined below. + This setting is incompatible with the use of `radius_server_address` and `radius_server_secret`. + +* `radius_server_address` - (Optional) The address of the Radius server. + This setting is incompatible with the use of `root_certificate` and `revoked_certificate`. + +* `radius_server_secret` - (Optional) The secret used by the Radius server. + This setting is incompatible with the use of `root_certificate` and `revoked_certificate`. The `bgp_settings` block supports: From b2d5a482d05f7eeaafdd466eac1a83eca59208f4 Mon Sep 17 00:00:00 2001 From: Damien Caro Date: Tue, 6 Mar 2018 22:47:36 -0800 Subject: [PATCH 002/320] Added validation of values --- azurerm/resource_arm_virtual_network_gateway.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/azurerm/resource_arm_virtual_network_gateway.go b/azurerm/resource_arm_virtual_network_gateway.go index 998e94704b3e..558dd911c30c 100644 --- a/azurerm/resource_arm_virtual_network_gateway.go +++ b/azurerm/resource_arm_virtual_network_gateway.go @@ -140,6 +140,10 @@ func resourceArmVirtualNetworkGateway() *schema.Resource { "vpn_client_protocol": { Type: schema.TypeList, Optional: true, + ValidateFunc: validation.StringInSlice([]string{ + "SSTP", + "IkeV2", + }, false), Elem: &schema.Schema{ Type: schema.TypeString, }, From a324d117fc10a439302528af89ce903e494d99fb Mon Sep 17 00:00:00 2001 From: Damien Caro Date: Tue, 6 Mar 2018 23:21:25 -0800 Subject: [PATCH 003/320] Removed validation function on list --- azurerm/resource_arm_virtual_network_gateway.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/azurerm/resource_arm_virtual_network_gateway.go b/azurerm/resource_arm_virtual_network_gateway.go index 558dd911c30c..998e94704b3e 100644 --- a/azurerm/resource_arm_virtual_network_gateway.go +++ b/azurerm/resource_arm_virtual_network_gateway.go @@ -140,10 +140,6 @@ func resourceArmVirtualNetworkGateway() *schema.Resource { "vpn_client_protocol": { Type: schema.TypeList, Optional: true, - ValidateFunc: validation.StringInSlice([]string{ - "SSTP", - "IkeV2", - }, false), Elem: &schema.Schema{ Type: schema.TypeString, }, From 4fa76c4553e7b6bb9483eeb7f9853cb88dbae0bf Mon Sep 17 00:00:00 2001 From: Jeffrey Zampieron Date: Tue, 20 Mar 2018 15:55:22 -0400 Subject: [PATCH 004/320] Initial code and unit tests for Storage Account Shared Access Signature support. --- azurerm/resource_arm_storage_account_sas.go | 193 ++++++++++++++++++ .../resource_arm_storage_account_sas_test.go | 87 ++++++++ 2 files changed, 280 insertions(+) create mode 100644 azurerm/resource_arm_storage_account_sas.go create mode 100644 azurerm/resource_arm_storage_account_sas_test.go diff --git a/azurerm/resource_arm_storage_account_sas.go b/azurerm/resource_arm_storage_account_sas.go new file mode 100644 index 000000000000..ff52d1ad5780 --- /dev/null +++ b/azurerm/resource_arm_storage_account_sas.go @@ -0,0 +1,193 @@ +package azurerm + +import "github.com/hashicorp/terraform/helper/schema" + +import ( + "fmt" + "regexp" + "strings" + + "crypto/hmac" + "crypto/sha256" +) + +const ( + connStringAccountKeyKey = "AccountKey" + connStringAccountNameKey = "AccountName" + sasSignedVersion = "2017-07-29" +) + +// This is an ACCOUNT SAS : https://docs.microsoft.com/en-us/rest/api/storageservices/Constructing-an-Account-SAS +// not Service SAS +func resourceArmStorageAccountSharedAccessSignature() *schema.Resource { + return &schema.Resource{ + Create: resourceArmStorageAccountSasCreate, + Read: resourceArmStorageAccountSasRead, + Delete: resourceArmStorageAccountSasDelete, + + Schema: map[string]*schema.Schema{ + "connection_string": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "https_only": { + Type: schema.TypeBool, + Required: true, + ForceNew: true, + }, + + "resource_types": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validateArmStorageAccountSasResourceTypes, + }, + + "services": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + // Always in UTC and must be ISO-8601 format + "start": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + // Always in UTC and must be ISO-8601 format + "expiry": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "permissions": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "sas": { + Type: schema.TypeString, + Computed: true, + }, + }, + } + +} + +func resourceArmStorageAccountSasCreate(d *schema.ResourceData, meta interface{}) error { + + connString := d.Get("connection_string").(string) + httpsOnly := d.Get("https_only").(bool) + resourceTypes := d.Get("resource_types").(string) + services := d.Get("services").(string) + start := d.Get("start").(string) + expiry := d.Get("expiry").(string) + permissions := d.Get("permissions").(string) + + // Parse the connection string + kvp, err := parseAzureStorageAccountConnectionString(connString) + if err != nil { + return err + } + + // Create the string to sign with the key... + + // Details on how to do this are here: + // https://docs.microsoft.com/en-us/rest/api/storageservices/Constructing-an-Account-SAS + accountName := kvp[connStringAccountNameKey] + accountKey := kvp[connStringAccountKeyKey] + var signedProtocol = "https,http" + if httpsOnly { + signedProtocol = "https" + } + signedIp := "" + signedVersion := sasSignedVersion + + sasToken := computeAzureStorageAccountSas(accountName, accountKey, permissions, services, resourceTypes, + start, expiry, signedProtocol, signedIp, signedVersion) + + d.Set("sas", sasToken) + + return nil +} + +func resourceArmStorageAccountSasRead(d *schema.ResourceData, meta interface{}) error { + // There really isn't anything to read + // The computed SAS element stores what it needs. + return nil +} + +func resourceArmStorageAccountSasDelete(d *schema.ResourceData, meta interface{}) error { + // Nothing to delete... + return nil +} + +func validateArmStorageAccountSasResourceTypes(v interface{}, k string) (ws []string, es []error) { + input := v.(string) + + if !regexp.MustCompile(`\A([cos]{1,3})\z`).MatchString(input) { + es = append(es, fmt.Errorf("resource Types can only consist of 's', 'c', 'o', and must be between 1 and 3 characters long")) + } + + return +} + +func computeAzureStorageAccountSas(accountName string, + accountKey string, + permissions string, services string, + resourceTypes string, start string, expiry string, + signedProtocol string, signedIp string, signedVersion string) string { + + // UTF-8 by default... + stringToSign := accountName + "\n" + permissions + "\n" + services + "\n" + resourceTypes + "\n" + start + "\n" + + expiry + "\n" + signedIp + "\n" + signedProtocol + "\n" + signedVersion + "\n" + + hasher := hmac.New(sha256.New, []byte(accountKey)) + signature := hasher.Sum([]byte(stringToSign)) + + sasToken := "?sv=" + signedVersion + "&ss=" + services + "&srt=" + resourceTypes + "&sp=" + permissions + + "&st=" + start + "&se=" + expiry + "&spr=" + signedProtocol + + // this is consistent with how the Azure portal builds these. + if len(signedIp) > 0 { + sasToken += "&sip=" + signedIp + } + + sasToken += "&sig=" + string(signature) + + return sasToken +} + +// This connection string was for a real storage account which has been deleted +// so its safe to include here for reference to understand the format. +// DefaultEndpointsProtocol=https;AccountName=azurermtestsa0;AccountKey=2vJrjEyL4re2nxCEg590wJUUC7PiqqrDHjAN5RU304FNUQieiEwS2bfp83O0v28iSfWjvYhkGmjYQAdd9x+6nw==;EndpointSuffix=core.windows.net + +func parseAzureStorageAccountConnectionString(connString string) (kvp map[string]string, err error) { + validKeys := map[string]bool{"DefaultEndpointsProtocol": true, "BlobEndpoint": true, + "AccountName": true, "AccountKey": true, "EndpointSuffix": true} + // The k-v pairs are separated with semi-colons + tokens := strings.Split(connString, ";") + + for _, atoken := range tokens { + // The individual k-v are separated by an equals sign. + kv := strings.SplitN(atoken, "=", 2) + key := kv[0] + val := kv[1] + if _, present := validKeys[key]; !present { + return nil, fmt.Errorf("[ERROR] Unknown Key: %s", key) + } + kvp[key] = val + } + + if _, present := kvp[connStringAccountKeyKey]; !present { + return nil, fmt.Errorf("[ERROR] Storage Account Key not found in connection string: %s", connString) + } + + return kvp, nil +} diff --git a/azurerm/resource_arm_storage_account_sas_test.go b/azurerm/resource_arm_storage_account_sas_test.go new file mode 100644 index 000000000000..9c9ac5363ac0 --- /dev/null +++ b/azurerm/resource_arm_storage_account_sas_test.go @@ -0,0 +1,87 @@ +package azurerm + +import ( + "testing" +) + +func TestValidateArmStorageAccountSasResourceTypes(t *testing.T) { + testCases := []struct { + input string + shouldError bool + }{ + {"s", false}, + {"c", false}, + {"o", false}, + {"sc", false}, + {"cs", false}, + {"os", false}, + {"sco", false}, + {"cso", false}, + {"osc", false}, + {"scos", true}, + {"csoc", true}, + {"oscs", true}, + {"S", true}, + {"C", true}, + {"O", true}, + } + + for _, test := range testCases { + _, es := validateArmStorageAccountSasResourceTypes(test.input, "") + + if test.shouldError && len(es) == 0 { + t.Fatalf("Expected validating resource_types %q to fail", test.input) + } + } +} + +// This connection string was for a real storage account which has been deleted +// so its safe to include here for reference to understand the format. +// DefaultEndpointsProtocol=https;AccountName=azurermtestsa0;AccountKey=2vJrjEyL4re2nxCEg590wJUUC7PiqqrDHjAN5RU304FNUQieiEwS2bfp83O0v28iSfWjvYhkGmjYQAdd9x+6nw==;EndpointSuffix=core.windows.net + +func TestComputeAzureStorageAccountSas(t *testing.T) { + testCases := []struct { + accountName string + accountKey string + permissions string + services string + resourceTypes string + start string + expiry string + signedProtocol string + signedIp string + signedVersion string + knownSasToken string + }{ + { + "azurermtestsa0", + "2vJrjEyL4re2nxCEg590wJUUC7PiqqrDHjAN5RU304FNUQieiEwS2bfp83O0v28iSfWjvYhkGmjYQAdd9x+6nw==", + "rwac", + "b", + "c", + "2018-03-20T04:00:00Z", + "2020-03-20T04:00:00Z", + "https", + "", + "2017-07-29", + "?sv=2017-07-29&ss=b&srt=c&sp=rwac&se=2020-03-20T04:00:00Z&st=2018-03-20T04:00:00Z&spr=https&sig=SQigK%2FnFA4pv0F0oMLqr6DxUWV4vtFqWi6q3Mf7o9nY%3D", + }, + } + + for _, test := range testCases { + computedToken := computeAzureStorageAccountSas(test.accountName, + test.accountKey, + test.permissions, + test.services, + test.resourceTypes, + test.start, + test.expiry, + test.signedProtocol, + test.signedIp, + test.signedVersion) + + if computedToken != test.knownSasToken { + t.Fatalf("Test failed: Expected Azure SAS %s but was %s", test.knownSasToken, computedToken) + } + } +} From 048bb767336e30b725179172623e242b5e473b8f Mon Sep 17 00:00:00 2001 From: Jeffrey Zampieron Date: Tue, 20 Mar 2018 17:04:03 -0400 Subject: [PATCH 005/320] Unit test for SAS computation which matches the Azure Portal passes. --- azurerm/resource_arm_storage_account_sas.go | 46 ++++++++++++++----- .../resource_arm_storage_account_sas_test.go | 10 ++-- 2 files changed, 41 insertions(+), 15 deletions(-) diff --git a/azurerm/resource_arm_storage_account_sas.go b/azurerm/resource_arm_storage_account_sas.go index ff52d1ad5780..f8e9cd907920 100644 --- a/azurerm/resource_arm_storage_account_sas.go +++ b/azurerm/resource_arm_storage_account_sas.go @@ -3,7 +3,9 @@ package azurerm import "github.com/hashicorp/terraform/helper/schema" import ( + "encoding/base64" "fmt" + "net/url" "regexp" "strings" @@ -109,8 +111,11 @@ func resourceArmStorageAccountSasCreate(d *schema.ResourceData, meta interface{} signedIp := "" signedVersion := sasSignedVersion - sasToken := computeAzureStorageAccountSas(accountName, accountKey, permissions, services, resourceTypes, + sasToken, err := computeAzureStorageAccountSas(accountName, accountKey, permissions, services, resourceTypes, start, expiry, signedProtocol, signedIp, signedVersion) + if err != nil { + return err + } d.Set("sas", sasToken) @@ -142,26 +147,43 @@ func computeAzureStorageAccountSas(accountName string, accountKey string, permissions string, services string, resourceTypes string, start string, expiry string, - signedProtocol string, signedIp string, signedVersion string) string { + signedProtocol string, signedIp string, signedVersion string) (string, error) { // UTF-8 by default... - stringToSign := accountName + "\n" + permissions + "\n" + services + "\n" + resourceTypes + "\n" + start + "\n" + - expiry + "\n" + signedIp + "\n" + signedProtocol + "\n" + signedVersion + "\n" - - hasher := hmac.New(sha256.New, []byte(accountKey)) - signature := hasher.Sum([]byte(stringToSign)) - - sasToken := "?sv=" + signedVersion + "&ss=" + services + "&srt=" + resourceTypes + "&sp=" + permissions + - "&st=" + start + "&se=" + expiry + "&spr=" + signedProtocol + stringToSign := accountName + "\n" + stringToSign += permissions + "\n" + stringToSign += services + "\n" + stringToSign += resourceTypes + "\n" + stringToSign += start + "\n" + stringToSign += expiry + "\n" + stringToSign += signedIp + "\n" + stringToSign += signedProtocol + "\n" + stringToSign += signedVersion + "\n" + + binaryKey, err := base64.StdEncoding.DecodeString(accountKey) + if err != nil { + return "", err + } + hasher := hmac.New(sha256.New, binaryKey) + hasher.Write([]byte(stringToSign)) + signature := hasher.Sum(nil) + + sasToken := "?sv=" + url.QueryEscape(signedVersion) + sasToken += "&ss=" + url.QueryEscape(services) + sasToken += "&srt=" + url.QueryEscape(resourceTypes) + sasToken += "&sp=" + url.QueryEscape(permissions) + sasToken += "&se=" + (expiry) + sasToken += "&st=" + (start) + sasToken += "&spr=" + url.QueryEscape(signedProtocol) // this is consistent with how the Azure portal builds these. if len(signedIp) > 0 { sasToken += "&sip=" + signedIp } - sasToken += "&sig=" + string(signature) + sasToken += "&sig=" + url.QueryEscape(base64.StdEncoding.EncodeToString(signature)) - return sasToken + return sasToken, nil } // This connection string was for a real storage account which has been deleted diff --git a/azurerm/resource_arm_storage_account_sas_test.go b/azurerm/resource_arm_storage_account_sas_test.go index 9c9ac5363ac0..b6cb4c787efa 100644 --- a/azurerm/resource_arm_storage_account_sas_test.go +++ b/azurerm/resource_arm_storage_account_sas_test.go @@ -37,7 +37,7 @@ func TestValidateArmStorageAccountSasResourceTypes(t *testing.T) { // This connection string was for a real storage account which has been deleted // so its safe to include here for reference to understand the format. -// DefaultEndpointsProtocol=https;AccountName=azurermtestsa0;AccountKey=2vJrjEyL4re2nxCEg590wJUUC7PiqqrDHjAN5RU304FNUQieiEwS2bfp83O0v28iSfWjvYhkGmjYQAdd9x+6nw==;EndpointSuffix=core.windows.net +// DefaultEndpointsProtocol=https;AccountName=azurermtestsa0;AccountKey=T0ZQouXBDpWud/PlTRHIJH2+VUK8D+fnedEynb9Mx638IYnsMUe4mv1fFjC7t0NayTfFAQJzPZuV1WHFKOzGdg==;EndpointSuffix=core.windows.net func TestComputeAzureStorageAccountSas(t *testing.T) { testCases := []struct { @@ -55,7 +55,7 @@ func TestComputeAzureStorageAccountSas(t *testing.T) { }{ { "azurermtestsa0", - "2vJrjEyL4re2nxCEg590wJUUC7PiqqrDHjAN5RU304FNUQieiEwS2bfp83O0v28iSfWjvYhkGmjYQAdd9x+6nw==", + "T0ZQouXBDpWud/PlTRHIJH2+VUK8D+fnedEynb9Mx638IYnsMUe4mv1fFjC7t0NayTfFAQJzPZuV1WHFKOzGdg==", "rwac", "b", "c", @@ -69,7 +69,7 @@ func TestComputeAzureStorageAccountSas(t *testing.T) { } for _, test := range testCases { - computedToken := computeAzureStorageAccountSas(test.accountName, + computedToken, err := computeAzureStorageAccountSas(test.accountName, test.accountKey, test.permissions, test.services, @@ -80,6 +80,10 @@ func TestComputeAzureStorageAccountSas(t *testing.T) { test.signedIp, test.signedVersion) + if err != nil { + t.Fatalf("Test Failed: Error computing storage account Sas: %q", err) + } + if computedToken != test.knownSasToken { t.Fatalf("Test failed: Expected Azure SAS %s but was %s", test.knownSasToken, computedToken) } From d9d1dc21c88e2b776b9fed1651e7055f9a749c8b Mon Sep 17 00:00:00 2001 From: Jeffrey Zampieron Date: Tue, 20 Mar 2018 17:11:01 -0400 Subject: [PATCH 006/320] Unit test for SAS computation which matches the Azure Portal passes - 2 --- azurerm/provider.go | 1 + azurerm/resource_arm_storage_account_sas.go | 15 +++++++++++---- azurerm/resource_arm_storage_account_sas_test.go | 13 +++++++++++++ 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/azurerm/provider.go b/azurerm/provider.go index 55bfae9685c9..cb32194ed1b0 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -193,6 +193,7 @@ func Provider() terraform.ResourceProvider { "azurerm_sql_active_directory_administrator": resourceArmSqlAdministrator(), "azurerm_sql_server": resourceArmSqlServer(), "azurerm_storage_account": resourceArmStorageAccount(), + "azurerm_storage_account_sas": resourceArmStorageAccountSharedAccessSignature(), "azurerm_storage_blob": resourceArmStorageBlob(), "azurerm_storage_container": resourceArmStorageContainer(), "azurerm_storage_share": resourceArmStorageShare(), diff --git a/azurerm/resource_arm_storage_account_sas.go b/azurerm/resource_arm_storage_account_sas.go index f8e9cd907920..f35e2ffc1246 100644 --- a/azurerm/resource_arm_storage_account_sas.go +++ b/azurerm/resource_arm_storage_account_sas.go @@ -145,9 +145,14 @@ func validateArmStorageAccountSasResourceTypes(v interface{}, k string) (ws []st func computeAzureStorageAccountSas(accountName string, accountKey string, - permissions string, services string, - resourceTypes string, start string, expiry string, - signedProtocol string, signedIp string, signedVersion string) (string, error) { + permissions string, + services string, + resourceTypes string, + start string, + expiry string, + signedProtocol string, + signedIp string, + signedVersion string) (string, error) { // UTF-8 by default... stringToSign := accountName + "\n" @@ -168,13 +173,15 @@ func computeAzureStorageAccountSas(accountName string, hasher.Write([]byte(stringToSign)) signature := hasher.Sum(nil) + // Trial and error to determine which fields the Azure portal + // URL encodes for a query string and which it does not. sasToken := "?sv=" + url.QueryEscape(signedVersion) sasToken += "&ss=" + url.QueryEscape(services) sasToken += "&srt=" + url.QueryEscape(resourceTypes) sasToken += "&sp=" + url.QueryEscape(permissions) sasToken += "&se=" + (expiry) sasToken += "&st=" + (start) - sasToken += "&spr=" + url.QueryEscape(signedProtocol) + sasToken += "&spr=" + (signedProtocol) // this is consistent with how the Azure portal builds these. if len(signedIp) > 0 { diff --git a/azurerm/resource_arm_storage_account_sas_test.go b/azurerm/resource_arm_storage_account_sas_test.go index b6cb4c787efa..434710ae3353 100644 --- a/azurerm/resource_arm_storage_account_sas_test.go +++ b/azurerm/resource_arm_storage_account_sas_test.go @@ -66,6 +66,19 @@ func TestComputeAzureStorageAccountSas(t *testing.T) { "2017-07-29", "?sv=2017-07-29&ss=b&srt=c&sp=rwac&se=2020-03-20T04:00:00Z&st=2018-03-20T04:00:00Z&spr=https&sig=SQigK%2FnFA4pv0F0oMLqr6DxUWV4vtFqWi6q3Mf7o9nY%3D", }, + { + "azurermtestsa0", + "2vJrjEyL4re2nxCEg590wJUUC7PiqqrDHjAN5RU304FNUQieiEwS2bfp83O0v28iSfWjvYhkGmjYQAdd9x+6nw==", + "rwdlac", + "b", + "sco", + "2018-03-20T04:00:00Z", + "2018-03-28T05:04:25Z", + "https,http", + "", + "2017-07-29", + "?sv=2017-07-29&ss=b&srt=sco&sp=rwdlac&se=2018-03-28T05:04:25Z&st=2018-03-20T04:00:00Z&spr=https,http&sig=OLNwL%2B7gxeDQQaUyNdXcDPK2aCbCMgEkJNjha9te448%3D", + }, } for _, test := range testCases { From d59dfb18eb26a27b93a06dd320d7bf8785b11288 Mon Sep 17 00:00:00 2001 From: Jeffrey Zampieron Date: Wed, 21 Mar 2018 13:13:12 -0400 Subject: [PATCH 007/320] Move SAS support from a resource to a data source. --- ....go => data_source_storage_account_sas.go} | 202 ++++++++++++++++-- ...> data_source_storage_account_sas_test.go} | 0 azurerm/provider.go | 2 +- 3 files changed, 182 insertions(+), 22 deletions(-) rename azurerm/{resource_arm_storage_account_sas.go => data_source_storage_account_sas.go} (58%) rename azurerm/{resource_arm_storage_account_sas_test.go => data_source_storage_account_sas_test.go} (100%) diff --git a/azurerm/resource_arm_storage_account_sas.go b/azurerm/data_source_storage_account_sas.go similarity index 58% rename from azurerm/resource_arm_storage_account_sas.go rename to azurerm/data_source_storage_account_sas.go index f35e2ffc1246..b0339a42c168 100644 --- a/azurerm/resource_arm_storage_account_sas.go +++ b/azurerm/data_source_storage_account_sas.go @@ -21,11 +21,9 @@ const ( // This is an ACCOUNT SAS : https://docs.microsoft.com/en-us/rest/api/storageservices/Constructing-an-Account-SAS // not Service SAS -func resourceArmStorageAccountSharedAccessSignature() *schema.Resource { +func dataSourceArmStorageAccountSharedAccessSignature() *schema.Resource { return &schema.Resource{ - Create: resourceArmStorageAccountSasCreate, - Read: resourceArmStorageAccountSasRead, - Delete: resourceArmStorageAccountSasDelete, + Read: dataSourceArmStorageAccountSasRead, Schema: map[string]*schema.Schema{ "connection_string": { @@ -41,16 +39,58 @@ func resourceArmStorageAccountSharedAccessSignature() *schema.Resource { }, "resource_types": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: validateArmStorageAccountSasResourceTypes, + Type: schema.TypeList, + Required: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "service": { + Type: schema.TypeBool, + Required: true, + }, + + "container": { + Type: schema.TypeBool, + Required: true, + }, + + "object": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, }, "services": { - Type: schema.TypeString, + Type: schema.TypeList, Required: true, ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "blob": { + Type: schema.TypeBool, + Required: true, + }, + + "queue": { + Type: schema.TypeBool, + Required: true, + }, + + "table": { + Type: schema.TypeBool, + Required: true, + }, + + "file": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, }, // Always in UTC and must be ISO-8601 format @@ -68,9 +108,53 @@ func resourceArmStorageAccountSharedAccessSignature() *schema.Resource { }, "permissions": { - Type: schema.TypeString, + Type: schema.TypeList, Required: true, ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "read": { + Type: schema.TypeBool, + Required: true, + }, + + "write": { + Type: schema.TypeBool, + Required: true, + }, + + "delete": { + Type: schema.TypeBool, + Required: true, + }, + + "list": { + Type: schema.TypeBool, + Required: true, + }, + + "add": { + Type: schema.TypeBool, + Required: true, + }, + + "create": { + Type: schema.TypeBool, + Required: true, + }, + + "update": { + Type: schema.TypeBool, + Required: true, + }, + + "process": { + Type: schema.TypeBool, + Required: true, + }, + }, + }, }, "sas": { @@ -82,15 +166,24 @@ func resourceArmStorageAccountSharedAccessSignature() *schema.Resource { } -func resourceArmStorageAccountSasCreate(d *schema.ResourceData, meta interface{}) error { +func dataSourceArmStorageAccountSasRead(d *schema.ResourceData, meta interface{}) error { connString := d.Get("connection_string").(string) httpsOnly := d.Get("https_only").(bool) - resourceTypes := d.Get("resource_types").(string) - services := d.Get("services").(string) + resourceTypesIface := d.Get("resource_types").([]interface{}) + servicesIface := d.Get("services").([]interface{}) start := d.Get("start").(string) expiry := d.Get("expiry").(string) - permissions := d.Get("permissions").(string) + permissionsIface := d.Get("permissions").([]interface{}) + + resourceTypes := buildResourceTypesString(resourceTypesIface[0].(map[string]interface{})) + services := buildServicesString(servicesIface[0].(map[string]interface{})) + permissions := buildPermissionsString(permissionsIface[0].(map[string]interface{})) + + _, svcErr := validateArmStorageAccountSasResourceTypes(services, "") + if svcErr != nil { + return svcErr[0] + } // Parse the connection string kvp, err := parseAzureStorageAccountConnectionString(connString) @@ -122,15 +215,82 @@ func resourceArmStorageAccountSasCreate(d *schema.ResourceData, meta interface{} return nil } -func resourceArmStorageAccountSasRead(d *schema.ResourceData, meta interface{}) error { - // There really isn't anything to read - // The computed SAS element stores what it needs. - return nil +func buildPermissionsString(perms map[string]interface{}) string { + retVal := "" + + if val := perms["read"].(bool); val { + retVal += "r" + } + + if val := perms["write"].(bool); val { + retVal += "w" + } + + if val := perms["delete"].(bool); val { + retVal += "d" + } + + if val := perms["list"].(bool); val { + retVal += "l" + } + + if val := perms["add"].(bool); val { + retVal += "a" + } + + if val := perms["create"].(bool); val { + retVal += "c" + } + + if val := perms["update"].(bool); val { + retVal += "u" + } + + if val := perms["process"].(bool); val { + retVal += "p" + } + + return retVal } -func resourceArmStorageAccountSasDelete(d *schema.ResourceData, meta interface{}) error { - // Nothing to delete... - return nil +func buildServicesString(services map[string]interface{}) string { + retVal := "" + + if val := services["blob"].(bool); val { + retVal += "b" + } + + if val := services["queue"].(bool); val { + retVal += "q" + } + + if val := services["table"].(bool); val { + retVal += "t" + } + + if val := services["file"].(bool); val { + retVal += "f" + } + + return retVal +} + +func buildResourceTypesString(resTypes map[string]interface{}) string { + retVal := "" + + if val := resTypes["service"].(bool); val { + retVal += "s" + } + + if val := resTypes["container"].(bool); val { + retVal += "c" + } + + if val := resTypes["object"].(bool); val { + retVal += "o" + } + + return retVal } func validateArmStorageAccountSasResourceTypes(v interface{}, k string) (ws []string, es []error) { diff --git a/azurerm/resource_arm_storage_account_sas_test.go b/azurerm/data_source_storage_account_sas_test.go similarity index 100% rename from azurerm/resource_arm_storage_account_sas_test.go rename to azurerm/data_source_storage_account_sas_test.go diff --git a/azurerm/provider.go b/azurerm/provider.go index cb32194ed1b0..4fb9f7df2a81 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -97,6 +97,7 @@ func Provider() terraform.ResourceProvider { "azurerm_scheduler_job_collection": dataSourceArmSchedulerJobCollection(), "azurerm_snapshot": dataSourceArmSnapshot(), "azurerm_storage_account": dataSourceArmStorageAccount(), + "azurerm_storage_account_sas": dataSourceArmStorageAccountSharedAccessSignature(), "azurerm_subnet": dataSourceArmSubnet(), "azurerm_subscription": dataSourceArmSubscription(), "azurerm_subscriptions": dataSourceArmSubscriptions(), @@ -193,7 +194,6 @@ func Provider() terraform.ResourceProvider { "azurerm_sql_active_directory_administrator": resourceArmSqlAdministrator(), "azurerm_sql_server": resourceArmSqlServer(), "azurerm_storage_account": resourceArmStorageAccount(), - "azurerm_storage_account_sas": resourceArmStorageAccountSharedAccessSignature(), "azurerm_storage_blob": resourceArmStorageBlob(), "azurerm_storage_container": resourceArmStorageContainer(), "azurerm_storage_share": resourceArmStorageShare(), From 109629b7bafc174fbcd9a040d79fca64fe59ff1e Mon Sep 17 00:00:00 2001 From: Jeffrey Zampieron Date: Wed, 21 Mar 2018 15:52:52 -0400 Subject: [PATCH 008/320] Add unit tests for the string building functions. --- azurerm/data_source_storage_account_sas.go | 30 ++--- .../data_source_storage_account_sas_test.go | 119 ++++++++++++++++++ 2 files changed, 134 insertions(+), 15 deletions(-) diff --git a/azurerm/data_source_storage_account_sas.go b/azurerm/data_source_storage_account_sas.go index b0339a42c168..7d7096a6aff8 100644 --- a/azurerm/data_source_storage_account_sas.go +++ b/azurerm/data_source_storage_account_sas.go @@ -218,35 +218,35 @@ func dataSourceArmStorageAccountSasRead(d *schema.ResourceData, meta interface{} func buildPermissionsString(perms map[string]interface{}) string { retVal := "" - if val := perms["read"].(bool); val { + if val, pres := perms["read"].(bool); pres && val { retVal += "r" } - if val := perms["write"].(bool); val { + if val, pres := perms["write"].(bool); pres && val { retVal += "w" } - if val := perms["delete"].(bool); val { + if val, pres := perms["delete"].(bool); pres && val { retVal += "d" } - if val := perms["list"].(bool); val { + if val, pres := perms["list"].(bool); pres && val { retVal += "l" } - if val := perms["add"].(bool); val { + if val, pres := perms["add"].(bool); pres && val { retVal += "a" } - if val := perms["create"].(bool); val { + if val, pres := perms["create"].(bool); pres && val { retVal += "c" } - if val := perms["update"].(bool); val { + if val, pres := perms["update"].(bool); pres && val { retVal += "u" } - if val := perms["process"].(bool); val { + if val, pres := perms["process"].(bool); pres && val { retVal += "p" } @@ -256,19 +256,19 @@ func buildPermissionsString(perms map[string]interface{}) string { func buildServicesString(services map[string]interface{}) string { retVal := "" - if val := services["blob"].(bool); val { + if val, pres := services["blob"].(bool); pres && val { retVal += "b" } - if val := services["queue"].(bool); val { + if val, pres := services["queue"].(bool); pres && val { retVal += "q" } - if val := services["table"].(bool); val { + if val, pres := services["table"].(bool); pres && val { retVal += "t" } - if val := services["file"].(bool); val { + if val, pres := services["file"].(bool); pres && val { retVal += "f" } @@ -278,15 +278,15 @@ func buildServicesString(services map[string]interface{}) string { func buildResourceTypesString(resTypes map[string]interface{}) string { retVal := "" - if val := resTypes["service"].(bool); val { + if val, pres := resTypes["service"].(bool); pres && val { retVal += "s" } - if val := resTypes["container"].(bool); val { + if val, pres := resTypes["container"].(bool); pres && val { retVal += "c" } - if val := resTypes["object"].(bool); val { + if val, pres := resTypes["object"].(bool); pres && val { retVal += "o" } diff --git a/azurerm/data_source_storage_account_sas_test.go b/azurerm/data_source_storage_account_sas_test.go index 434710ae3353..b2be388745f4 100644 --- a/azurerm/data_source_storage_account_sas_test.go +++ b/azurerm/data_source_storage_account_sas_test.go @@ -1,9 +1,128 @@ package azurerm import ( + "fmt" "testing" ) +func TestDataSourceArmStorageAccountSasRead(t *testing.T) { + +} + +func testAccDataSourceAzureRMStorageAccountSas_basic(rInt int, rString string, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestsa-%d" + location = "%s" +} + +resource "azurerm_storage_account" "test" { + name = "acctestsads%s" + resource_group_name = "${azurerm_resource_group.test.name}" + + location = "${azurerm_resource_group.test.location}" + account_tier = "Standard" + account_replication_type = "LRS" + + tags { + environment = "production" + } +} + +data "azurerm_storage_account_sas" "test" { + connection_string = "${azurerm_storage_account.test.primary_connection_string}" + https_only = true + resource_types { + service = true + container = false + object = false + } + services { + blob = true + queue = false + table = false + file = false + } + start = "" + expirty = "" + permissions { + read = true + write = true + delete = false + list = false + add = true + create = true + update = false + process = false + } +} +`, rInt, location, rString) +} + +func TestBuildResourceTypesString(t *testing.T) { + testCases := []struct { + input map[string]interface{} + expected string + }{ + {map[string]interface{}{"service": true}, "s"}, + {map[string]interface{}{"container": true}, "c"}, + {map[string]interface{}{"object": true}, "o"}, + {map[string]interface{}{"service": true, "container": true, "object": true}, "sco"}, + } + + for _, test := range testCases { + result := buildResourceTypesString(test.input) + if test.expected != result { + t.Fatalf("Failed to build resource type string: expected: %s, result: %s", test.expected, result) + } + } +} + +func TestBuildServicesString(t *testing.T) { + testCases := []struct { + input map[string]interface{} + expected string + }{ + {map[string]interface{}{"blob": true}, "b"}, + {map[string]interface{}{"queue": true}, "q"}, + {map[string]interface{}{"table": true}, "t"}, + {map[string]interface{}{"file": true}, "f"}, + {map[string]interface{}{"blob": true, "queue": true, "table": true, "file": true}, "bqtf"}, + } + + for _, test := range testCases { + result := buildServicesString(test.input) + if test.expected != result { + t.Fatalf("Failed to build resource type string: expected: %s, result: %s", test.expected, result) + } + } + +} + +func TestBuildPermissionsString(t *testing.T) { + testCases := []struct { + input map[string]interface{} + expected string + }{ + {map[string]interface{}{"read": true}, "r"}, + {map[string]interface{}{"write": true}, "w"}, + {map[string]interface{}{"delete": true}, "d"}, + {map[string]interface{}{"list": true}, "l"}, + {map[string]interface{}{"add": true}, "a"}, + {map[string]interface{}{"create": true}, "c"}, + {map[string]interface{}{"update": true}, "u"}, + {map[string]interface{}{"process": true}, "p"}, + {map[string]interface{}{"read": true, "write": true, "add": true, "create": true}, "rwac"}, + } + + for _, test := range testCases { + result := buildPermissionsString(test.input) + if test.expected != result { + t.Fatalf("Failed to build resource type string: expected: %s, result: %s", test.expected, result) + } + } +} + func TestValidateArmStorageAccountSasResourceTypes(t *testing.T) { testCases := []struct { input string From 27e8d5a7848e68b298610b0b0dcc5675d4141aaa Mon Sep 17 00:00:00 2001 From: Jeffrey Zampieron Date: Wed, 21 Mar 2018 15:53:38 -0400 Subject: [PATCH 009/320] Fix warnings on unused func params. --- azurerm/data_source_storage_account_sas.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/azurerm/data_source_storage_account_sas.go b/azurerm/data_source_storage_account_sas.go index 7d7096a6aff8..5a496c665a8e 100644 --- a/azurerm/data_source_storage_account_sas.go +++ b/azurerm/data_source_storage_account_sas.go @@ -166,7 +166,7 @@ func dataSourceArmStorageAccountSharedAccessSignature() *schema.Resource { } -func dataSourceArmStorageAccountSasRead(d *schema.ResourceData, meta interface{}) error { +func dataSourceArmStorageAccountSasRead(d *schema.ResourceData, _ interface{}) error { connString := d.Get("connection_string").(string) httpsOnly := d.Get("https_only").(bool) @@ -293,7 +293,7 @@ func buildResourceTypesString(resTypes map[string]interface{}) string { return retVal } -func validateArmStorageAccountSasResourceTypes(v interface{}, k string) (ws []string, es []error) { +func validateArmStorageAccountSasResourceTypes(v interface{}, _ string) (ws []string, es []error) { input := v.(string) if !regexp.MustCompile(`\A([cos]{1,3})\z`).MatchString(input) { From c19295dce3925a76414784d168e393d7f8f07cba Mon Sep 17 00:00:00 2001 From: Jeffrey Zampieron Date: Wed, 21 Mar 2018 17:08:30 -0400 Subject: [PATCH 010/320] Add unit test for the connection string parse. --- azurerm/data_source_storage_account_sas.go | 8 ++-- .../data_source_storage_account_sas_test.go | 37 +++++++++++++++++-- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/azurerm/data_source_storage_account_sas.go b/azurerm/data_source_storage_account_sas.go index 5a496c665a8e..fd2378d00cdc 100644 --- a/azurerm/data_source_storage_account_sas.go +++ b/azurerm/data_source_storage_account_sas.go @@ -180,7 +180,7 @@ func dataSourceArmStorageAccountSasRead(d *schema.ResourceData, _ interface{}) e services := buildServicesString(servicesIface[0].(map[string]interface{})) permissions := buildPermissionsString(permissionsIface[0].(map[string]interface{})) - _, svcErr := validateArmStorageAccountSasResourceTypes(services, "") + _, svcErr := validateArmStorageAccountSasResourceTypes(resourceTypes, "") if svcErr != nil { return svcErr[0] } @@ -297,7 +297,7 @@ func validateArmStorageAccountSasResourceTypes(v interface{}, _ string) (ws []st input := v.(string) if !regexp.MustCompile(`\A([cos]{1,3})\z`).MatchString(input) { - es = append(es, fmt.Errorf("resource Types can only consist of 's', 'c', 'o', and must be between 1 and 3 characters long")) + es = append(es, fmt.Errorf("resource types can only consist of 's', 'c', 'o', and must be between 1 and 3 characters long: found: %s", input)) } return @@ -357,12 +357,14 @@ func computeAzureStorageAccountSas(accountName string, // so its safe to include here for reference to understand the format. // DefaultEndpointsProtocol=https;AccountName=azurermtestsa0;AccountKey=2vJrjEyL4re2nxCEg590wJUUC7PiqqrDHjAN5RU304FNUQieiEwS2bfp83O0v28iSfWjvYhkGmjYQAdd9x+6nw==;EndpointSuffix=core.windows.net -func parseAzureStorageAccountConnectionString(connString string) (kvp map[string]string, err error) { +func parseAzureStorageAccountConnectionString(connString string) (map[string]string, error) { validKeys := map[string]bool{"DefaultEndpointsProtocol": true, "BlobEndpoint": true, "AccountName": true, "AccountKey": true, "EndpointSuffix": true} // The k-v pairs are separated with semi-colons tokens := strings.Split(connString, ";") + kvp := make(map[string]string) + for _, atoken := range tokens { // The individual k-v are separated by an equals sign. kv := strings.SplitN(atoken, "=", 2) diff --git a/azurerm/data_source_storage_account_sas_test.go b/azurerm/data_source_storage_account_sas_test.go index b2be388745f4..2ef914cbfc42 100644 --- a/azurerm/data_source_storage_account_sas_test.go +++ b/azurerm/data_source_storage_account_sas_test.go @@ -10,6 +10,8 @@ func TestDataSourceArmStorageAccountSasRead(t *testing.T) { } func testAccDataSourceAzureRMStorageAccountSas_basic(rInt int, rString string, location string) string { + startDate := "" + endDate := "" return fmt.Sprintf(` resource "azurerm_resource_group" "test" { name = "acctestsa-%d" @@ -43,8 +45,8 @@ data "azurerm_storage_account_sas" "test" { table = false file = false } - start = "" - expirty = "" + start = "%s" + expiry = "%s" permissions { read = true write = true @@ -56,7 +58,36 @@ data "azurerm_storage_account_sas" "test" { process = false } } -`, rInt, location, rString) +`, rInt, location, rString, startDate, endDate) +} + +func TestParseAzureStorageAccountConnectionString(t *testing.T) { + testCases := []struct { + input string + expectedAccountName string + expectedAccountKey string + }{ + { + "DefaultEndpointsProtocol=https;AccountName=azurermtestsa0;AccountKey=2vJrjEyL4re2nxCEg590wJUUC7PiqqrDHjAN5RU304FNUQieiEwS2bfp83O0v28iSfWjvYhkGmjYQAdd9x+6nw==;EndpointSuffix=core.windows.net", + "azurermtestsa0", + "2vJrjEyL4re2nxCEg590wJUUC7PiqqrDHjAN5RU304FNUQieiEwS2bfp83O0v28iSfWjvYhkGmjYQAdd9x+6nw==", + }, + } + + for _, test := range testCases { + result, err := parseAzureStorageAccountConnectionString(test.input) + if err != nil { + t.Fatalf("Failed to parse resource type string: %s, %q", test.input, result) + } else { + if val, pres := result[connStringAccountKeyKey]; !pres || val != test.expectedAccountKey { + t.Fatalf("Failed to parse Account Key: Expected: %s, Found: %s", test.expectedAccountKey, val) + } + if val, pres := result[connStringAccountNameKey]; !pres || val != test.expectedAccountName { + t.Fatalf("Failed to parse Account Name: Expected: %s, Found: %s", test.expectedAccountName, val) + } + } + } + } func TestBuildResourceTypesString(t *testing.T) { From a1f12ee04f31ef4a319a7861cb61d6b1bd577540 Mon Sep 17 00:00:00 2001 From: Jeffrey Zampieron Date: Wed, 21 Mar 2018 17:32:18 -0400 Subject: [PATCH 011/320] Make sure to set the id of the data source element. --- azurerm/data_source_storage_account_sas.go | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/azurerm/data_source_storage_account_sas.go b/azurerm/data_source_storage_account_sas.go index fd2378d00cdc..863d701612e1 100644 --- a/azurerm/data_source_storage_account_sas.go +++ b/azurerm/data_source_storage_account_sas.go @@ -11,6 +11,7 @@ import ( "crypto/hmac" "crypto/sha256" + "encoding/hex" ) const ( @@ -27,9 +28,10 @@ func dataSourceArmStorageAccountSharedAccessSignature() *schema.Resource { Schema: map[string]*schema.Schema{ "connection_string": { - Type: schema.TypeString, - Required: true, - ForceNew: true, + Type: schema.TypeString, + Required: true, + ForceNew: true, + Sensitive: true, }, "https_only": { @@ -158,8 +160,9 @@ func dataSourceArmStorageAccountSharedAccessSignature() *schema.Resource { }, "sas": { - Type: schema.TypeString, - Computed: true, + Type: schema.TypeString, + Computed: true, + Sensitive: true, }, }, } @@ -211,6 +214,8 @@ func dataSourceArmStorageAccountSasRead(d *schema.ResourceData, _ interface{}) e } d.Set("sas", sasToken) + tokenHash := sha256.Sum256([]byte(sasToken)) + d.SetId(hex.EncodeToString(tokenHash[:])) return nil } From 66c8acae7bce93339b2338f678e184b0fb7569e3 Mon Sep 17 00:00:00 2001 From: Jeffrey Zampieron Date: Thu, 22 Mar 2018 10:56:16 -0400 Subject: [PATCH 012/320] Make https_only an optional/defaulted field. --- azurerm/data_source_storage_account_sas.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/azurerm/data_source_storage_account_sas.go b/azurerm/data_source_storage_account_sas.go index 863d701612e1..3bbc839018d0 100644 --- a/azurerm/data_source_storage_account_sas.go +++ b/azurerm/data_source_storage_account_sas.go @@ -36,7 +36,8 @@ func dataSourceArmStorageAccountSharedAccessSignature() *schema.Resource { "https_only": { Type: schema.TypeBool, - Required: true, + Optional: true, + Default: true, ForceNew: true, }, From d16f5df59032d7f1c4476e28895047859ca657dc Mon Sep 17 00:00:00 2001 From: Jeffrey Zampieron Date: Thu, 22 Mar 2018 10:56:47 -0400 Subject: [PATCH 013/320] Add documentation for data source `azurerm_storage_account_sas`. --- website/azurerm.erb | 4 + .../docs/d/storage_account_sas.html.markdown | 87 +++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 website/docs/d/storage_account_sas.html.markdown diff --git a/website/azurerm.erb b/website/azurerm.erb index 009d3583e01f..76bf6da89c66 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -103,6 +103,10 @@ azurerm_storage_account + > + azurerm_storage_account_sas + + > azurerm_subnet diff --git a/website/docs/d/storage_account_sas.html.markdown b/website/docs/d/storage_account_sas.html.markdown new file mode 100644 index 000000000000..8fda6bdff206 --- /dev/null +++ b/website/docs/d/storage_account_sas.html.markdown @@ -0,0 +1,87 @@ +--- +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_storage_account_sas" +sidebar_current: "docs-azurerm-datasource-storage-account-sas" +description: |- + Create a Shared Access Signature (SAS) for an Azure Storage Account. + +--- + +# Data Source: azurerm_storage_account_sas + +Use this data source to create a Shared Access Signature (SAS) for an Azure Storage Account. + +Shared access signatures allow fine-grained, ephemeral access control to various aspects of an Azure Storage Account. + +Note that this is an [Account SAS](https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas) +and *not* a [Service SAS](https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas). + +## Example Usage + +```hcl +resource "azurerm_resource_group" "testrg" { + name = "resourceGroupName" + location = "westus" +} + +resource "azurerm_storage_account" "testsa" { + name = "storageaccountname" + resource_group_name = "${azurerm_resource_group.testrg.name}" + location = "westus" + account_tier = "Standard" + account_replication_type = "GRS" + + tags { + environment = "staging" + } +} + +data "azurerm_storage_account_sas" "test" { + connection_string = "${azurerm_storage_account.testsa.primary_connection_string}" + https_only = true + resource_types { + service = true + container = false + object = false + } + services { + blob = true + queue = false + table = false + file = false + } + start = "2018-03-21" + expiry = "2020-03-21" + permissions { + read = true + write = true + delete = false + list = false + add = true + create = true + update = false + process = false + } +} + +output "sas_url_query_string" { + value = "${data.azurerm_storage_account_sas.sas}" +} +``` + +## Argument Reference + +* `connection_string` - (Required) The connection string for the storage account to which this SAS applies. Typically directly from the `primary_connection_string` attribute of a terraform created `azurerm_storage_account` resource. +* `https_only` - (Optional) Only permit `https` access. If `false`, both `http` and `https` are permitted. (Default `true`) +* `resouce_types` - (Required) A set of true/false flags which define the storage account resource types that are granted access by this SAS. +* `services` - (Required) A set of true/false flags which define the storage account services that are granted access by this SAS. +* `start` - (Required) The starting time and date of validity of this SAS. Must be a valid ISO-8601 format time/date string. +* `expiry` - (Required) The expiration time and date of this SAS. Must be a valid ISO-8601 format time/date string. +* `permissions` - (Required) A set of true/false flags which define the granted permissions. + +Refer to the [SAS creation reference from Azure](https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas) +for additional details on the fields above. + +## Attributes Reference + +* `sas` - (Computed) The computed Account Shared Access Signature (SAS). From 608808360f262f3620c9f7e5debf212a42961723 Mon Sep 17 00:00:00 2001 From: Jeffrey Zampieron Date: Thu, 22 Mar 2018 14:16:37 -0400 Subject: [PATCH 014/320] WIP: Add acceptance test. --- .../data_source_storage_account_sas_test.go | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/azurerm/data_source_storage_account_sas_test.go b/azurerm/data_source_storage_account_sas_test.go index 2ef914cbfc42..09550215b963 100644 --- a/azurerm/data_source_storage_account_sas_test.go +++ b/azurerm/data_source_storage_account_sas_test.go @@ -2,16 +2,39 @@ package azurerm import ( "fmt" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" "testing" + "time" ) -func TestDataSourceArmStorageAccountSasRead(t *testing.T) { +func TestAccDataSourceArmStorageAccountSasRead(t *testing.T) { + dataSourceName := "data.azurerm_storage_account_sas.test" + rInt := acctest.RandInt() + rString := acctest.RandString(4) + location := testLocation() + utcNow := time.Now().UTC() + startDate := utcNow.Format(time.RFC3339) + endDate := utcNow.Add(time.Hour * 24).Format(time.RFC3339) + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceAzureRMStorageAccountSas_basic(rInt, rString, location, startDate, endDate), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(dataSourceName, "https_only", "true"), + resource.TestCheckResourceAttr(dataSourceName, "start", startDate), + resource.TestCheckResourceAttr(dataSourceName, "expiry", endDate), + resource.TestCheckResourceAttrSet(dataSourceName, "sas"), + ), + }, + }, + }) } -func testAccDataSourceAzureRMStorageAccountSas_basic(rInt int, rString string, location string) string { - startDate := "" - endDate := "" +func testAccDataSourceAzureRMStorageAccountSas_basic(rInt int, rString string, location string, startDate string, endDate string) string { return fmt.Sprintf(` resource "azurerm_resource_group" "test" { name = "acctestsa-%d" From e2b4cf291d6dabef0ec3914b1eb65ac2283241f3 Mon Sep 17 00:00:00 2001 From: kt Date: Thu, 19 Apr 2018 05:05:08 -0700 Subject: [PATCH 015/320] New Resource/Data Source: `azurerm_recovery_services_vault` (#995) * Added new resource azurerm_recovery_services_vault and data source azurerm_recovery_services_vault * updating to include the latest sdk * Duplicating the checks for consistency * Making govendor happy * Data Source: name should be ForceNew --- azurerm/config.go | 11 + .../data_source_recovery_services_vault.go | 69 + ...ata_source_recovery_services_vault_test.go | 44 + azurerm/provider.go | 2 + .../resource_arm_recovery_services_vault.go | 149 +++ ...source_arm_recovery_services_vault_test.go | 114 ++ examples/recoveryservice-vault/main.tf | 12 + examples/recoveryservice-vault/outputs.tf | 4 + examples/recoveryservice-vault/variables.tf | 11 + .../2016-06-01/recoveryservices/client.go | 51 + .../2016-06-01/recoveryservices/models.go | 1190 +++++++++++++++++ .../2016-06-01/recoveryservices/operations.go | 126 ++ .../recoveryservices/registeredidentities.go | 107 ++ .../recoveryservices/replicationusages.go | 107 ++ .../2016-06-01/recoveryservices/usages.go | 107 ++ .../recoveryservices/vaultcertificates.go | 111 ++ .../recoveryservices/vaultextendedinfo.go | 245 ++++ .../2016-06-01/recoveryservices/vaults.go | 494 +++++++ .../2016-06-01/recoveryservices/version.go | 30 + vendor/vendor.json | 10 +- website/azurerm.erb | 13 + .../docs/d/recovery_services_vault.markdown | 40 + .../docs/r/recovery_services_vault.markdown | 57 + 23 files changed, 3103 insertions(+), 1 deletion(-) create mode 100644 azurerm/data_source_recovery_services_vault.go create mode 100644 azurerm/data_source_recovery_services_vault_test.go create mode 100644 azurerm/resource_arm_recovery_services_vault.go create mode 100644 azurerm/resource_arm_recovery_services_vault_test.go create mode 100644 examples/recoveryservice-vault/main.tf create mode 100644 examples/recoveryservice-vault/outputs.tf create mode 100644 examples/recoveryservice-vault/variables.tf create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/client.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/models.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/operations.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/registeredidentities.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/replicationusages.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/usages.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/vaultcertificates.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/vaultextendedinfo.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/vaults.go create mode 100644 vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/version.go create mode 100644 website/docs/d/recovery_services_vault.markdown create mode 100644 website/docs/r/recovery_services_vault.markdown diff --git a/azurerm/config.go b/azurerm/config.go index 488cd7ecf9dc..2249cbaf9658 100644 --- a/azurerm/config.go +++ b/azurerm/config.go @@ -32,6 +32,7 @@ import ( "github.com/Azure/azure-sdk-for-go/services/operationalinsights/mgmt/2015-11-01-preview/operationalinsights" "github.com/Azure/azure-sdk-for-go/services/operationsmanagement/mgmt/2015-11-01-preview/operationsmanagement" "github.com/Azure/azure-sdk-for-go/services/postgresql/mgmt/2017-04-30-preview/postgresql" + "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices" "github.com/Azure/azure-sdk-for-go/services/redis/mgmt/2018-03-01/redis" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-06-01/subscriptions" "github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2016-09-01/locks" @@ -166,6 +167,9 @@ type ArmClient struct { vnetPeeringsClient network.VirtualNetworkPeeringsClient watcherClient network.WatchersClient + // Recovery Services + recoveryServicesVaultsClient recoveryservices.VaultsClient + // Resources managementLocksClient locks.ManagementLocksClient deploymentsClient resources.DeploymentsClient @@ -373,6 +377,7 @@ func getArmClient(c *authentication.Config) (*ArmClient, error) { client.registerMonitorClients(endpoint, c.SubscriptionID, auth, sender) client.registerNetworkingClients(endpoint, c.SubscriptionID, auth, sender) client.registerOperationalInsightsClients(endpoint, c.SubscriptionID, auth, sender) + client.registerRecoveryServiceClients(endpoint, c.SubscriptionID, auth) client.registerRedisClients(endpoint, c.SubscriptionID, auth, sender) client.registerResourcesClients(endpoint, c.SubscriptionID, auth) client.registerSearchClients(endpoint, c.SubscriptionID, auth) @@ -786,6 +791,12 @@ func (c *ArmClient) registerOperationalInsightsClients(endpoint, subscriptionId c.solutionsClient = solutionsClient } +func (c *ArmClient) registerRecoveryServiceClients(endpoint, subscriptionId string, auth autorest.Authorizer) { + vaultsClient := recoveryservices.NewVaultsClientWithBaseURI(endpoint, subscriptionId) + c.configureClient(&vaultsClient.Client, auth) + c.recoveryServicesVaultsClient = vaultsClient +} + func (c *ArmClient) registerRedisClients(endpoint, subscriptionId string, auth autorest.Authorizer, sender autorest.Sender) { redisClient := redis.NewClientWithBaseURI(endpoint, subscriptionId) c.configureClient(&redisClient.Client, auth) diff --git a/azurerm/data_source_recovery_services_vault.go b/azurerm/data_source_recovery_services_vault.go new file mode 100644 index 000000000000..203dbf4286a7 --- /dev/null +++ b/azurerm/data_source_recovery_services_vault.go @@ -0,0 +1,69 @@ +package azurerm + +import ( + "fmt" + "log" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func dataSourceArmRecoveryServicesVault() *schema.Resource { + return &schema.Resource{ + Read: dataSourceArmRecoveryServicesVaultRead, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "location": locationForDataSourceSchema(), + + "resource_group_name": resourceGroupNameForDataSourceSchema(), + + "tags": tagsForDataSourceSchema(), + + "sku": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func dataSourceArmRecoveryServicesVaultRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).recoveryServicesVaultsClient + ctx := meta.(*ArmClient).StopContext + + name := d.Get("name").(string) + resourceGroup := d.Get("resource_group_name").(string) + + log.Printf("[DEBUG] Reading Recovery Service Vault %q (resource group %q)", name, resourceGroup) + + vault, err := client.Get(ctx, resourceGroup, name) + if err != nil { + if utils.ResponseWasNotFound(vault.Response) { + d.SetId("") + return nil + } + + return fmt.Errorf("Error making Read request on Recovery Service Vault %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + d.SetId(*vault.ID) + d.Set("name", vault.Name) + d.Set("location", azureRMNormalizeLocation(*vault.Location)) + d.Set("resource_group_name", resourceGroup) + + if sku := vault.Sku; sku != nil { + d.Set("sku", string(sku.Name)) + } + + flattenAndSetTags(d, vault.Tags) + return nil +} diff --git a/azurerm/data_source_recovery_services_vault_test.go b/azurerm/data_source_recovery_services_vault_test.go new file mode 100644 index 000000000000..d654c5e16d58 --- /dev/null +++ b/azurerm/data_source_recovery_services_vault_test.go @@ -0,0 +1,44 @@ +package azurerm + +import ( + "fmt" + "testing" + + "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices" + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" +) + +func TestAccDataSourceAzureRMRecoveryServicesVault_basic(t *testing.T) { + dataSourceName := "data.azurerm_recovery_services_vault.test" + ri := acctest.RandInt() + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccDataSourceRecoveryServicesVault_basic(ri, testLocation()), + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMRecoveryServicesVaultExists(dataSourceName), + resource.TestCheckResourceAttrSet(dataSourceName, "name"), + resource.TestCheckResourceAttrSet(dataSourceName, "location"), + resource.TestCheckResourceAttrSet(dataSourceName, "resource_group_name"), + resource.TestCheckResourceAttr(dataSourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(dataSourceName, "sku", string(recoveryservices.Standard)), + ), + }, + }, + }) +} + +func testAccDataSourceRecoveryServicesVault_basic(rInt int, location string) string { + return fmt.Sprintf(` +%s + +data "azurerm_recovery_services_vault" "test" { + name = "${azurerm_recovery_services_vault.test.name}" + resource_group_name = "${azurerm_resource_group.test.name}" +} +`, testAccAzureRMRecoveryServicesVault_basic(rInt, location)) +} diff --git a/azurerm/provider.go b/azurerm/provider.go index 4439a2ce415c..ac2afb83958b 100644 --- a/azurerm/provider.go +++ b/azurerm/provider.go @@ -93,6 +93,7 @@ func Provider() terraform.ResourceProvider { "azurerm_platform_image": dataSourceArmPlatformImage(), "azurerm_public_ip": dataSourceArmPublicIP(), "azurerm_public_ips": dataSourceArmPublicIPs(), + "azurerm_recovery_services_vault": dataSourceArmRecoveryServicesVault(), "azurerm_resource_group": dataSourceArmResourceGroup(), "azurerm_role_definition": dataSourceArmRoleDefinition(), "azurerm_scheduler_job_collection": dataSourceArmSchedulerJobCollection(), @@ -179,6 +180,7 @@ func Provider() terraform.ResourceProvider { "azurerm_postgresql_firewall_rule": resourceArmPostgreSQLFirewallRule(), "azurerm_postgresql_server": resourceArmPostgreSQLServer(), "azurerm_public_ip": resourceArmPublicIp(), + "azurerm_recovery_services_vault": resourceArmRecoveryServicesVault(), "azurerm_redis_cache": resourceArmRedisCache(), "azurerm_redis_firewall_rule": resourceArmRedisFirewallRule(), "azurerm_resource_group": resourceArmResourceGroup(), diff --git a/azurerm/resource_arm_recovery_services_vault.go b/azurerm/resource_arm_recovery_services_vault.go new file mode 100644 index 000000000000..bdc1860ead3e --- /dev/null +++ b/azurerm/resource_arm_recovery_services_vault.go @@ -0,0 +1,149 @@ +package azurerm + +import ( + "fmt" + "log" + "regexp" + + "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices" + + "github.com/hashicorp/terraform/helper/schema" + "github.com/hashicorp/terraform/helper/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceArmRecoveryServicesVault() *schema.Resource { + return &schema.Resource{ + Create: resourceArmRecoveryServicesVaultCreateUpdate, + Read: resourceArmRecoveryServicesVaultRead, + Update: resourceArmRecoveryServicesVaultCreateUpdate, + Delete: resourceArmRecoveryServicesVaultDelete, + + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringMatch( + regexp.MustCompile("^[a-zA-Z][-a-zA-Z0-9]{1,49}$"), + "Recovery Service Vault name must be 2 - 50 characters long, start with a letter, contain only letters, numbers and hyphens.", + ), + }, + + "location": locationSchema(), + + "resource_group_name": resourceGroupNameSchema(), + + "tags": tagsSchema(), + + "sku": { + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: ignoreCaseDiffSuppressFunc, + ValidateFunc: validation.StringInSlice([]string{ + string(recoveryservices.RS0), + string(recoveryservices.Standard), + }, true), + }, + }, + } +} + +func resourceArmRecoveryServicesVaultCreateUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).recoveryServicesVaultsClient + ctx := meta.(*ArmClient).StopContext + + name := d.Get("name").(string) + location := d.Get("location").(string) + resourceGroup := d.Get("resource_group_name").(string) + tags := d.Get("tags").(map[string]interface{}) + + log.Printf("[DEBUG] Creating/updating Recovery Service Vault %q (resource group %q)", name, resourceGroup) + + //build vault struct + vault := recoveryservices.Vault{ + Location: utils.String(location), + Tags: expandTags(tags), + Sku: &recoveryservices.Sku{ + Name: recoveryservices.SkuName(d.Get("sku").(string)), + }, + Properties: &recoveryservices.VaultProperties{}, + } + + //create recovery services vault + vault, err := client.CreateOrUpdate(ctx, resourceGroup, name, vault) + if err != nil { + return fmt.Errorf("Error creating/updating Recovery Service Vault %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + d.SetId(*vault.ID) + + return resourceArmRecoveryServicesVaultRead(d, meta) +} + +func resourceArmRecoveryServicesVaultRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).recoveryServicesVaultsClient + ctx := meta.(*ArmClient).StopContext + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + + name := id.Path["vaults"] + resourceGroup := id.ResourceGroup + + log.Printf("[DEBUG] Reading Recovery Service Vault %q (resource group %q)", name, resourceGroup) + + resp, err := client.Get(ctx, resourceGroup, name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + d.SetId("") + return nil + } + + return fmt.Errorf("Error making Read request on Recovery Service Vault %q (Resource Group %q): %+v", name, resourceGroup, err) + } + + d.Set("name", resp.Name) + d.Set("resource_group_name", resourceGroup) + if location := resp.Location; location != nil { + d.Set("location", azureRMNormalizeLocation(*location)) + } + + if sku := resp.Sku; sku != nil { + d.Set("sku", string(sku.Name)) + } + + flattenAndSetTags(d, resp.Tags) + + return nil +} + +func resourceArmRecoveryServicesVaultDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*ArmClient).recoveryServicesVaultsClient + ctx := meta.(*ArmClient).StopContext + + id, err := parseAzureResourceID(d.Id()) + if err != nil { + return err + } + + name := id.Path["vaults"] + resourceGroup := id.ResourceGroup + + log.Printf("[DEBUG] Deleting Recovery Service Vault %q (resource group %q)", name, resourceGroup) + + resp, err := client.Delete(ctx, resourceGroup, name) + if err != nil { + if !utils.ResponseWasNotFound(resp) { + return fmt.Errorf("Error issuing delete request for Recovery Service Vault %q (Resource Group %q): %+v", name, resourceGroup, err) + } + } + + return nil +} diff --git a/azurerm/resource_arm_recovery_services_vault_test.go b/azurerm/resource_arm_recovery_services_vault_test.go new file mode 100644 index 000000000000..7af1affe15d1 --- /dev/null +++ b/azurerm/resource_arm_recovery_services_vault_test.go @@ -0,0 +1,114 @@ +package azurerm + +import ( + "fmt" + "testing" + + "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices" + + "github.com/hashicorp/terraform/helper/acctest" + "github.com/hashicorp/terraform/helper/resource" + "github.com/hashicorp/terraform/terraform" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func TestAccAzureRMRecoveryServicesVault_basic(t *testing.T) { + ri := acctest.RandInt() + + resourceName := "azurerm_recovery_services_vault.test" + config := testAccAzureRMRecoveryServicesVault_basic(ri, testLocation()) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + CheckDestroy: testCheckAzureRMRecoveryServicesVaultDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testCheckAzureRMRecoveryServicesVaultExists(resourceName), + resource.TestCheckResourceAttrSet(resourceName, "name"), + resource.TestCheckResourceAttrSet(resourceName, "location"), + resource.TestCheckResourceAttrSet(resourceName, "resource_group_name"), + resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), + resource.TestCheckResourceAttr(resourceName, "sku", string(recoveryservices.Standard)), + ), + }, + }, + }) +} + +func testCheckAzureRMRecoveryServicesVaultDestroy(s *terraform.State) error { + for _, rs := range s.RootModule().Resources { + if rs.Type != "azurerm_recovery_services_vault" { + continue + } + + name := rs.Primary.Attributes["name"] + resourceGroup := rs.Primary.Attributes["resource_group_name"] + + client := testAccProvider.Meta().(*ArmClient).recoveryServicesVaultsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + + resp, err := client.Get(ctx, resourceGroup, name) + + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return nil + } + + return err + } + + return fmt.Errorf("Recovery Services Vault still exists:\n%#v", resp) + } + + return nil +} + +func testCheckAzureRMRecoveryServicesVaultExists(name string) resource.TestCheckFunc { + return func(s *terraform.State) error { + // Ensure we have enough information in state to look up in API + rs, ok := s.RootModule().Resources[name] + if !ok { + return fmt.Errorf("Not found: %q", name) + } + + name := rs.Primary.Attributes["name"] + resourceGroup, hasResourceGroup := rs.Primary.Attributes["resource_group_name"] + if !hasResourceGroup { + return fmt.Errorf("Bad: no resource group found in state for Recovery Services Vault: %q", name) + } + + client := testAccProvider.Meta().(*ArmClient).recoveryServicesVaultsClient + ctx := testAccProvider.Meta().(*ArmClient).StopContext + resp, err := client.Get(ctx, resourceGroup, name) + + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("Recovery Services Vault %q (resource group: %q) was not found: %+v", name, resourceGroup, err) + } + + return fmt.Errorf("Bad: Get on recoveryServicesVaultsClient: %+v", err) + } + + return nil + } +} + +func testAccAzureRMRecoveryServicesVault_basic(rInt int, location string) string { + return fmt.Sprintf(` +resource "azurerm_resource_group" "test" { + name = "acctestRG-%d" + location = "%s" +} + +resource "azurerm_recovery_services_vault" "test" { + name = "acctest-%d" + location = "${azurerm_resource_group.test.location}" + resource_group_name = "${azurerm_resource_group.test.name}" + sku = "Standard" +} + +`, rInt, location, rInt) +} diff --git a/examples/recoveryservice-vault/main.tf b/examples/recoveryservice-vault/main.tf new file mode 100644 index 000000000000..b54ef863e64e --- /dev/null +++ b/examples/recoveryservice-vault/main.tf @@ -0,0 +1,12 @@ + +resource "azurerm_resource_group" "rg" { + name = "${var.resource_group_name}" + location = "${var.resource_group_location}" +} + +resource "azurerm_recovery_services_vault" "vault" { + name = "example-recovery-vault" + location = "${azurerm_resource_group.rg.location}" + resource_group_name = "${azurerm_resource_group.rg.name}" + sku = "Standard" +} diff --git a/examples/recoveryservice-vault/outputs.tf b/examples/recoveryservice-vault/outputs.tf new file mode 100644 index 000000000000..1e18aee70d71 --- /dev/null +++ b/examples/recoveryservice-vault/outputs.tf @@ -0,0 +1,4 @@ + +output "vault-id" { + value = "${azurerm_recovery_services_vault.vault.id}" +} \ No newline at end of file diff --git a/examples/recoveryservice-vault/variables.tf b/examples/recoveryservice-vault/variables.tf new file mode 100644 index 000000000000..bbec5d88f6b5 --- /dev/null +++ b/examples/recoveryservice-vault/variables.tf @@ -0,0 +1,11 @@ +variable "resource_group_name" { + type = "string" + description = "Name of the azure resource group." + default = "tfex-recovery_vault" +} + +variable "resource_group_location" { + type = "string" + description = "Location of the azure resource group." + default = "westus" +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/client.go new file mode 100644 index 000000000000..221b1dd05edb --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/client.go @@ -0,0 +1,51 @@ +// Package recoveryservices implements the Azure ARM Recoveryservices service API version 2016-06-01. +// +// Recovery Services Client +package recoveryservices + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "github.com/Azure/go-autorest/autorest" +) + +const ( + // DefaultBaseURI is the default URI used for the service Recoveryservices + DefaultBaseURI = "https://management.azure.com" +) + +// BaseClient is the base client for Recoveryservices. +type BaseClient struct { + autorest.Client + BaseURI string + SubscriptionID string +} + +// New creates an instance of the BaseClient client. +func New(subscriptionID string) BaseClient { + return NewWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewWithBaseURI creates an instance of the BaseClient client. +func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { + return BaseClient{ + Client: autorest.NewClientWithUserAgent(UserAgent()), + BaseURI: baseURI, + SubscriptionID: subscriptionID, + } +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/models.go new file mode 100644 index 000000000000..f9bb1290b62e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/models.go @@ -0,0 +1,1190 @@ +package recoveryservices + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "encoding/json" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/date" + "github.com/Azure/go-autorest/autorest/to" + "net/http" +) + +// AuthType enumerates the values for auth type. +type AuthType string + +const ( + // AAD ... + AAD AuthType = "AAD" + // AccessControlService ... + AccessControlService AuthType = "AccessControlService" + // ACS ... + ACS AuthType = "ACS" + // AzureActiveDirectory ... + AzureActiveDirectory AuthType = "AzureActiveDirectory" + // Invalid ... + Invalid AuthType = "Invalid" +) + +// PossibleAuthTypeValues returns an array of possible values for the AuthType const type. +func PossibleAuthTypeValues() []AuthType { + return []AuthType{AAD, AccessControlService, ACS, AzureActiveDirectory, Invalid} +} + +// AuthTypeBasicResourceCertificateDetails enumerates the values for auth type basic resource certificate +// details. +type AuthTypeBasicResourceCertificateDetails string + +const ( + // AuthTypeAccessControlService ... + AuthTypeAccessControlService AuthTypeBasicResourceCertificateDetails = "AccessControlService" + // AuthTypeAzureActiveDirectory ... + AuthTypeAzureActiveDirectory AuthTypeBasicResourceCertificateDetails = "AzureActiveDirectory" + // AuthTypeResourceCertificateDetails ... + AuthTypeResourceCertificateDetails AuthTypeBasicResourceCertificateDetails = "ResourceCertificateDetails" +) + +// PossibleAuthTypeBasicResourceCertificateDetailsValues returns an array of possible values for the AuthTypeBasicResourceCertificateDetails const type. +func PossibleAuthTypeBasicResourceCertificateDetailsValues() []AuthTypeBasicResourceCertificateDetails { + return []AuthTypeBasicResourceCertificateDetails{AuthTypeAccessControlService, AuthTypeAzureActiveDirectory, AuthTypeResourceCertificateDetails} +} + +// SkuName enumerates the values for sku name. +type SkuName string + +const ( + // RS0 ... + RS0 SkuName = "RS0" + // Standard ... + Standard SkuName = "Standard" +) + +// PossibleSkuNameValues returns an array of possible values for the SkuName const type. +func PossibleSkuNameValues() []SkuName { + return []SkuName{RS0, Standard} +} + +// TriggerType enumerates the values for trigger type. +type TriggerType string + +const ( + // ForcedUpgrade ... + ForcedUpgrade TriggerType = "ForcedUpgrade" + // UserTriggered ... + UserTriggered TriggerType = "UserTriggered" +) + +// PossibleTriggerTypeValues returns an array of possible values for the TriggerType const type. +func PossibleTriggerTypeValues() []TriggerType { + return []TriggerType{ForcedUpgrade, UserTriggered} +} + +// UsagesUnit enumerates the values for usages unit. +type UsagesUnit string + +const ( + // Bytes ... + Bytes UsagesUnit = "Bytes" + // BytesPerSecond ... + BytesPerSecond UsagesUnit = "BytesPerSecond" + // Count ... + Count UsagesUnit = "Count" + // CountPerSecond ... + CountPerSecond UsagesUnit = "CountPerSecond" + // Percent ... + Percent UsagesUnit = "Percent" + // Seconds ... + Seconds UsagesUnit = "Seconds" +) + +// PossibleUsagesUnitValues returns an array of possible values for the UsagesUnit const type. +func PossibleUsagesUnitValues() []UsagesUnit { + return []UsagesUnit{Bytes, BytesPerSecond, Count, CountPerSecond, Percent, Seconds} +} + +// VaultUpgradeState enumerates the values for vault upgrade state. +type VaultUpgradeState string + +const ( + // Failed ... + Failed VaultUpgradeState = "Failed" + // InProgress ... + InProgress VaultUpgradeState = "InProgress" + // Unknown ... + Unknown VaultUpgradeState = "Unknown" + // Upgraded ... + Upgraded VaultUpgradeState = "Upgraded" +) + +// PossibleVaultUpgradeStateValues returns an array of possible values for the VaultUpgradeState const type. +func PossibleVaultUpgradeStateValues() []VaultUpgradeState { + return []VaultUpgradeState{Failed, InProgress, Unknown, Upgraded} +} + +// CertificateRequest details of the certificate to be uploaded to the vault. +type CertificateRequest struct { + Properties *RawCertificateData `json:"properties,omitempty"` +} + +// ClientDiscoveryDisplay localized display information of an operation. +type ClientDiscoveryDisplay struct { + // Provider - Name of the provider for display purposes + Provider *string `json:"provider,omitempty"` + // Resource - ResourceType for which this Operation can be performed. + Resource *string `json:"resource,omitempty"` + // Operation - Operations Name itself. + Operation *string `json:"operation,omitempty"` + // Description - Description of the operation having details of what operation is about. + Description *string `json:"description,omitempty"` +} + +// ClientDiscoveryForLogSpecification class to represent shoebox log specification in json client discovery. +type ClientDiscoveryForLogSpecification struct { + // Name - Name of the log. + Name *string `json:"name,omitempty"` + // DisplayName - Localized display name + DisplayName *string `json:"displayName,omitempty"` + // BlobDuration - Blobs created in customer storage account per hour + BlobDuration *string `json:"blobDuration,omitempty"` +} + +// ClientDiscoveryForProperties class to represent shoebox properties in json client discovery. +type ClientDiscoveryForProperties struct { + // ServiceSpecification - Operation properties. + ServiceSpecification *ClientDiscoveryForServiceSpecification `json:"serviceSpecification,omitempty"` +} + +// ClientDiscoveryForServiceSpecification class to represent shoebox service specification in json client +// discovery. +type ClientDiscoveryForServiceSpecification struct { + // LogSpecifications - List of log specifications of this operation. + LogSpecifications *[]ClientDiscoveryForLogSpecification `json:"logSpecifications,omitempty"` +} + +// ClientDiscoveryResponse operations List response which contains list of available APIs. +type ClientDiscoveryResponse struct { + autorest.Response `json:"-"` + // Value - List of available operationss. + Value *[]ClientDiscoveryValueForSingleAPI `json:"value,omitempty"` + // NextLink - Link to the next chunk of the response + NextLink *string `json:"nextLink,omitempty"` +} + +// ClientDiscoveryResponseIterator provides access to a complete listing of ClientDiscoveryValueForSingleAPI +// values. +type ClientDiscoveryResponseIterator struct { + i int + page ClientDiscoveryResponsePage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *ClientDiscoveryResponseIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter ClientDiscoveryResponseIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter ClientDiscoveryResponseIterator) Response() ClientDiscoveryResponse { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter ClientDiscoveryResponseIterator) Value() ClientDiscoveryValueForSingleAPI { + if !iter.page.NotDone() { + return ClientDiscoveryValueForSingleAPI{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (cdr ClientDiscoveryResponse) IsEmpty() bool { + return cdr.Value == nil || len(*cdr.Value) == 0 +} + +// clientDiscoveryResponsePreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (cdr ClientDiscoveryResponse) clientDiscoveryResponsePreparer() (*http.Request, error) { + if cdr.NextLink == nil || len(to.String(cdr.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(cdr.NextLink))) +} + +// ClientDiscoveryResponsePage contains a page of ClientDiscoveryValueForSingleAPI values. +type ClientDiscoveryResponsePage struct { + fn func(ClientDiscoveryResponse) (ClientDiscoveryResponse, error) + cdr ClientDiscoveryResponse +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *ClientDiscoveryResponsePage) Next() error { + next, err := page.fn(page.cdr) + if err != nil { + return err + } + page.cdr = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page ClientDiscoveryResponsePage) NotDone() bool { + return !page.cdr.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page ClientDiscoveryResponsePage) Response() ClientDiscoveryResponse { + return page.cdr +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page ClientDiscoveryResponsePage) Values() []ClientDiscoveryValueForSingleAPI { + if page.cdr.IsEmpty() { + return nil + } + return *page.cdr.Value +} + +// ClientDiscoveryValueForSingleAPI available operation details. +type ClientDiscoveryValueForSingleAPI struct { + // Name - Name of the Operation. + Name *string `json:"name,omitempty"` + // Display - Contains the localized display information for this particular operation + Display *ClientDiscoveryDisplay `json:"display,omitempty"` + // Origin - The intended executor of the operation;governs the display of the operation in the RBAC UX and the audit logs UX + Origin *string `json:"origin,omitempty"` + // Properties - ShoeBox properties for the given operation. + Properties *ClientDiscoveryForProperties `json:"properties,omitempty"` +} + +// JobsSummary summary of the replication job data for this vault. +type JobsSummary struct { + // FailedJobs - Count of failed jobs. + FailedJobs *int32 `json:"failedJobs,omitempty"` + // SuspendedJobs - Count of suspended jobs. + SuspendedJobs *int32 `json:"suspendedJobs,omitempty"` + // InProgressJobs - Count of in-progress jobs. + InProgressJobs *int32 `json:"inProgressJobs,omitempty"` +} + +// MonitoringSummary summary of the replication monitoring data for this vault. +type MonitoringSummary struct { + // UnHealthyVMCount - Count of unhealthy VMs. + UnHealthyVMCount *int32 `json:"unHealthyVmCount,omitempty"` + // UnHealthyProviderCount - Count of unhealthy replication providers. + UnHealthyProviderCount *int32 `json:"unHealthyProviderCount,omitempty"` + // EventsCount - Count of all critical warnings. + EventsCount *int32 `json:"eventsCount,omitempty"` + // DeprecatedProviderCount - Count of all deprecated recovery service providers. + DeprecatedProviderCount *int32 `json:"deprecatedProviderCount,omitempty"` + // SupportedProviderCount - Count of all the supported recovery service providers. + SupportedProviderCount *int32 `json:"supportedProviderCount,omitempty"` + // UnsupportedProviderCount - Count of all the unsupported recovery service providers. + UnsupportedProviderCount *int32 `json:"unsupportedProviderCount,omitempty"` +} + +// NameInfo the name of usage. +type NameInfo struct { + // Value - Value of usage. + Value *string `json:"value,omitempty"` + // LocalizedValue - Localized value of usage. + LocalizedValue *string `json:"localizedValue,omitempty"` +} + +// PatchTrackedResource tracked resource with location. +type PatchTrackedResource struct { + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` + // ID - Resource Id represents the complete path to the resource. + ID *string `json:"id,omitempty"` + // Name - Resource name associated with the resource. + Name *string `json:"name,omitempty"` + // Type - Resource type represents the complete path of the form Namespace/ResourceType/ResourceType/... + Type *string `json:"type,omitempty"` + // ETag - Optional ETag. + ETag *string `json:"eTag,omitempty"` +} + +// MarshalJSON is the custom marshaler for PatchTrackedResource. +func (ptr PatchTrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if ptr.Location != nil { + objectMap["location"] = ptr.Location + } + if ptr.Tags != nil { + objectMap["tags"] = ptr.Tags + } + if ptr.ID != nil { + objectMap["id"] = ptr.ID + } + if ptr.Name != nil { + objectMap["name"] = ptr.Name + } + if ptr.Type != nil { + objectMap["type"] = ptr.Type + } + if ptr.ETag != nil { + objectMap["eTag"] = ptr.ETag + } + return json.Marshal(objectMap) +} + +// PatchVault patch Resource information, as returned by the resource provider. +type PatchVault struct { + Properties *VaultProperties `json:"properties,omitempty"` + Sku *Sku `json:"sku,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` + // ID - Resource Id represents the complete path to the resource. + ID *string `json:"id,omitempty"` + // Name - Resource name associated with the resource. + Name *string `json:"name,omitempty"` + // Type - Resource type represents the complete path of the form Namespace/ResourceType/ResourceType/... + Type *string `json:"type,omitempty"` + // ETag - Optional ETag. + ETag *string `json:"eTag,omitempty"` +} + +// MarshalJSON is the custom marshaler for PatchVault. +func (pv PatchVault) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if pv.Properties != nil { + objectMap["properties"] = pv.Properties + } + if pv.Sku != nil { + objectMap["sku"] = pv.Sku + } + if pv.Location != nil { + objectMap["location"] = pv.Location + } + if pv.Tags != nil { + objectMap["tags"] = pv.Tags + } + if pv.ID != nil { + objectMap["id"] = pv.ID + } + if pv.Name != nil { + objectMap["name"] = pv.Name + } + if pv.Type != nil { + objectMap["type"] = pv.Type + } + if pv.ETag != nil { + objectMap["eTag"] = pv.ETag + } + return json.Marshal(objectMap) +} + +// RawCertificateData raw certificate data. +type RawCertificateData struct { + // AuthType - Specifies the authentication type. Possible values include: 'Invalid', 'ACS', 'AAD', 'AccessControlService', 'AzureActiveDirectory' + AuthType AuthType `json:"authType,omitempty"` + // Certificate - The base64 encoded certificate raw data string + Certificate *[]byte `json:"certificate,omitempty"` +} + +// ReplicationUsage replication usages of a vault. +type ReplicationUsage struct { + // MonitoringSummary - Summary of the replication monitoring data for this vault. + MonitoringSummary *MonitoringSummary `json:"monitoringSummary,omitempty"` + // JobsSummary - Summary of the replication jobs data for this vault. + JobsSummary *JobsSummary `json:"jobsSummary,omitempty"` + // ProtectedItemCount - Number of replication protected items for this vault. + ProtectedItemCount *int32 `json:"protectedItemCount,omitempty"` + // RecoveryPlanCount - Number of replication recovery plans for this vault. + RecoveryPlanCount *int32 `json:"recoveryPlanCount,omitempty"` + // RegisteredServersCount - Number of servers registered to this vault. + RegisteredServersCount *int32 `json:"registeredServersCount,omitempty"` + // RecoveryServicesProviderAuthType - The authentication type of recovery service providers in the vault. + RecoveryServicesProviderAuthType *int32 `json:"recoveryServicesProviderAuthType,omitempty"` +} + +// ReplicationUsageList replication usages for vault. +type ReplicationUsageList struct { + autorest.Response `json:"-"` + // Value - The list of replication usages for the given vault. + Value *[]ReplicationUsage `json:"value,omitempty"` +} + +// Resource ARM Resource. +type Resource struct { + // ID - Resource Id represents the complete path to the resource. + ID *string `json:"id,omitempty"` + // Name - Resource name associated with the resource. + Name *string `json:"name,omitempty"` + // Type - Resource type represents the complete path of the form Namespace/ResourceType/ResourceType/... + Type *string `json:"type,omitempty"` + // ETag - Optional ETag. + ETag *string `json:"eTag,omitempty"` +} + +// ResourceCertificateAndAadDetails certificate details representing the Vault credentials for AAD. +type ResourceCertificateAndAadDetails struct { + // AadAuthority - AAD tenant authority. + AadAuthority *string `json:"aadAuthority,omitempty"` + // AadTenantID - AAD tenant Id. + AadTenantID *string `json:"aadTenantId,omitempty"` + // ServicePrincipalClientID - AAD service principal clientId. + ServicePrincipalClientID *string `json:"servicePrincipalClientId,omitempty"` + // ServicePrincipalObjectID - AAD service principal ObjectId. + ServicePrincipalObjectID *string `json:"servicePrincipalObjectId,omitempty"` + // AzureManagementEndpointAudience - Azure Management Endpoint Audience. + AzureManagementEndpointAudience *string `json:"azureManagementEndpointAudience,omitempty"` + // Certificate - The base64 encoded certificate raw data string. + Certificate *[]byte `json:"certificate,omitempty"` + // FriendlyName - Certificate friendlyname. + FriendlyName *string `json:"friendlyName,omitempty"` + // Issuer - Certificate issuer. + Issuer *string `json:"issuer,omitempty"` + // ResourceID - Resource ID of the vault. + ResourceID *int64 `json:"resourceId,omitempty"` + // Subject - Certificate Subject Name. + Subject *string `json:"subject,omitempty"` + // Thumbprint - Certificate thumbprint. + Thumbprint *string `json:"thumbprint,omitempty"` + // ValidFrom - Certificate Validity start Date time. + ValidFrom *date.Time `json:"validFrom,omitempty"` + // ValidTo - Certificate Validity End Date time. + ValidTo *date.Time `json:"validTo,omitempty"` + // AuthType - Possible values include: 'AuthTypeResourceCertificateDetails', 'AuthTypeAzureActiveDirectory', 'AuthTypeAccessControlService' + AuthType AuthTypeBasicResourceCertificateDetails `json:"authType,omitempty"` +} + +// MarshalJSON is the custom marshaler for ResourceCertificateAndAadDetails. +func (rcaad ResourceCertificateAndAadDetails) MarshalJSON() ([]byte, error) { + rcaad.AuthType = AuthTypeAzureActiveDirectory + objectMap := make(map[string]interface{}) + if rcaad.AadAuthority != nil { + objectMap["aadAuthority"] = rcaad.AadAuthority + } + if rcaad.AadTenantID != nil { + objectMap["aadTenantId"] = rcaad.AadTenantID + } + if rcaad.ServicePrincipalClientID != nil { + objectMap["servicePrincipalClientId"] = rcaad.ServicePrincipalClientID + } + if rcaad.ServicePrincipalObjectID != nil { + objectMap["servicePrincipalObjectId"] = rcaad.ServicePrincipalObjectID + } + if rcaad.AzureManagementEndpointAudience != nil { + objectMap["azureManagementEndpointAudience"] = rcaad.AzureManagementEndpointAudience + } + if rcaad.Certificate != nil { + objectMap["certificate"] = rcaad.Certificate + } + if rcaad.FriendlyName != nil { + objectMap["friendlyName"] = rcaad.FriendlyName + } + if rcaad.Issuer != nil { + objectMap["issuer"] = rcaad.Issuer + } + if rcaad.ResourceID != nil { + objectMap["resourceId"] = rcaad.ResourceID + } + if rcaad.Subject != nil { + objectMap["subject"] = rcaad.Subject + } + if rcaad.Thumbprint != nil { + objectMap["thumbprint"] = rcaad.Thumbprint + } + if rcaad.ValidFrom != nil { + objectMap["validFrom"] = rcaad.ValidFrom + } + if rcaad.ValidTo != nil { + objectMap["validTo"] = rcaad.ValidTo + } + if rcaad.AuthType != "" { + objectMap["authType"] = rcaad.AuthType + } + return json.Marshal(objectMap) +} + +// AsResourceCertificateAndAadDetails is the BasicResourceCertificateDetails implementation for ResourceCertificateAndAadDetails. +func (rcaad ResourceCertificateAndAadDetails) AsResourceCertificateAndAadDetails() (*ResourceCertificateAndAadDetails, bool) { + return &rcaad, true +} + +// AsResourceCertificateAndAcsDetails is the BasicResourceCertificateDetails implementation for ResourceCertificateAndAadDetails. +func (rcaad ResourceCertificateAndAadDetails) AsResourceCertificateAndAcsDetails() (*ResourceCertificateAndAcsDetails, bool) { + return nil, false +} + +// AsResourceCertificateDetails is the BasicResourceCertificateDetails implementation for ResourceCertificateAndAadDetails. +func (rcaad ResourceCertificateAndAadDetails) AsResourceCertificateDetails() (*ResourceCertificateDetails, bool) { + return nil, false +} + +// AsBasicResourceCertificateDetails is the BasicResourceCertificateDetails implementation for ResourceCertificateAndAadDetails. +func (rcaad ResourceCertificateAndAadDetails) AsBasicResourceCertificateDetails() (BasicResourceCertificateDetails, bool) { + return &rcaad, true +} + +// ResourceCertificateAndAcsDetails certificate details representing the Vault credentials for ACS. +type ResourceCertificateAndAcsDetails struct { + // GlobalAcsNamespace - ACS namespace name - tenant for our service. + GlobalAcsNamespace *string `json:"globalAcsNamespace,omitempty"` + // GlobalAcsHostName - Acs mgmt host name to connect to. + GlobalAcsHostName *string `json:"globalAcsHostName,omitempty"` + // GlobalAcsRPRealm - Global ACS namespace RP realm. + GlobalAcsRPRealm *string `json:"globalAcsRPRealm,omitempty"` + // Certificate - The base64 encoded certificate raw data string. + Certificate *[]byte `json:"certificate,omitempty"` + // FriendlyName - Certificate friendlyname. + FriendlyName *string `json:"friendlyName,omitempty"` + // Issuer - Certificate issuer. + Issuer *string `json:"issuer,omitempty"` + // ResourceID - Resource ID of the vault. + ResourceID *int64 `json:"resourceId,omitempty"` + // Subject - Certificate Subject Name. + Subject *string `json:"subject,omitempty"` + // Thumbprint - Certificate thumbprint. + Thumbprint *string `json:"thumbprint,omitempty"` + // ValidFrom - Certificate Validity start Date time. + ValidFrom *date.Time `json:"validFrom,omitempty"` + // ValidTo - Certificate Validity End Date time. + ValidTo *date.Time `json:"validTo,omitempty"` + // AuthType - Possible values include: 'AuthTypeResourceCertificateDetails', 'AuthTypeAzureActiveDirectory', 'AuthTypeAccessControlService' + AuthType AuthTypeBasicResourceCertificateDetails `json:"authType,omitempty"` +} + +// MarshalJSON is the custom marshaler for ResourceCertificateAndAcsDetails. +func (rcaad ResourceCertificateAndAcsDetails) MarshalJSON() ([]byte, error) { + rcaad.AuthType = AuthTypeAccessControlService + objectMap := make(map[string]interface{}) + if rcaad.GlobalAcsNamespace != nil { + objectMap["globalAcsNamespace"] = rcaad.GlobalAcsNamespace + } + if rcaad.GlobalAcsHostName != nil { + objectMap["globalAcsHostName"] = rcaad.GlobalAcsHostName + } + if rcaad.GlobalAcsRPRealm != nil { + objectMap["globalAcsRPRealm"] = rcaad.GlobalAcsRPRealm + } + if rcaad.Certificate != nil { + objectMap["certificate"] = rcaad.Certificate + } + if rcaad.FriendlyName != nil { + objectMap["friendlyName"] = rcaad.FriendlyName + } + if rcaad.Issuer != nil { + objectMap["issuer"] = rcaad.Issuer + } + if rcaad.ResourceID != nil { + objectMap["resourceId"] = rcaad.ResourceID + } + if rcaad.Subject != nil { + objectMap["subject"] = rcaad.Subject + } + if rcaad.Thumbprint != nil { + objectMap["thumbprint"] = rcaad.Thumbprint + } + if rcaad.ValidFrom != nil { + objectMap["validFrom"] = rcaad.ValidFrom + } + if rcaad.ValidTo != nil { + objectMap["validTo"] = rcaad.ValidTo + } + if rcaad.AuthType != "" { + objectMap["authType"] = rcaad.AuthType + } + return json.Marshal(objectMap) +} + +// AsResourceCertificateAndAadDetails is the BasicResourceCertificateDetails implementation for ResourceCertificateAndAcsDetails. +func (rcaad ResourceCertificateAndAcsDetails) AsResourceCertificateAndAadDetails() (*ResourceCertificateAndAadDetails, bool) { + return nil, false +} + +// AsResourceCertificateAndAcsDetails is the BasicResourceCertificateDetails implementation for ResourceCertificateAndAcsDetails. +func (rcaad ResourceCertificateAndAcsDetails) AsResourceCertificateAndAcsDetails() (*ResourceCertificateAndAcsDetails, bool) { + return &rcaad, true +} + +// AsResourceCertificateDetails is the BasicResourceCertificateDetails implementation for ResourceCertificateAndAcsDetails. +func (rcaad ResourceCertificateAndAcsDetails) AsResourceCertificateDetails() (*ResourceCertificateDetails, bool) { + return nil, false +} + +// AsBasicResourceCertificateDetails is the BasicResourceCertificateDetails implementation for ResourceCertificateAndAcsDetails. +func (rcaad ResourceCertificateAndAcsDetails) AsBasicResourceCertificateDetails() (BasicResourceCertificateDetails, bool) { + return &rcaad, true +} + +// BasicResourceCertificateDetails certificate details representing the Vault credentials. +type BasicResourceCertificateDetails interface { + AsResourceCertificateAndAadDetails() (*ResourceCertificateAndAadDetails, bool) + AsResourceCertificateAndAcsDetails() (*ResourceCertificateAndAcsDetails, bool) + AsResourceCertificateDetails() (*ResourceCertificateDetails, bool) +} + +// ResourceCertificateDetails certificate details representing the Vault credentials. +type ResourceCertificateDetails struct { + // Certificate - The base64 encoded certificate raw data string. + Certificate *[]byte `json:"certificate,omitempty"` + // FriendlyName - Certificate friendlyname. + FriendlyName *string `json:"friendlyName,omitempty"` + // Issuer - Certificate issuer. + Issuer *string `json:"issuer,omitempty"` + // ResourceID - Resource ID of the vault. + ResourceID *int64 `json:"resourceId,omitempty"` + // Subject - Certificate Subject Name. + Subject *string `json:"subject,omitempty"` + // Thumbprint - Certificate thumbprint. + Thumbprint *string `json:"thumbprint,omitempty"` + // ValidFrom - Certificate Validity start Date time. + ValidFrom *date.Time `json:"validFrom,omitempty"` + // ValidTo - Certificate Validity End Date time. + ValidTo *date.Time `json:"validTo,omitempty"` + // AuthType - Possible values include: 'AuthTypeResourceCertificateDetails', 'AuthTypeAzureActiveDirectory', 'AuthTypeAccessControlService' + AuthType AuthTypeBasicResourceCertificateDetails `json:"authType,omitempty"` +} + +func unmarshalBasicResourceCertificateDetails(body []byte) (BasicResourceCertificateDetails, error) { + var m map[string]interface{} + err := json.Unmarshal(body, &m) + if err != nil { + return nil, err + } + + switch m["authType"] { + case string(AuthTypeAzureActiveDirectory): + var rcaad ResourceCertificateAndAadDetails + err := json.Unmarshal(body, &rcaad) + return rcaad, err + case string(AuthTypeAccessControlService): + var rcaad ResourceCertificateAndAcsDetails + err := json.Unmarshal(body, &rcaad) + return rcaad, err + default: + var rcd ResourceCertificateDetails + err := json.Unmarshal(body, &rcd) + return rcd, err + } +} +func unmarshalBasicResourceCertificateDetailsArray(body []byte) ([]BasicResourceCertificateDetails, error) { + var rawMessages []*json.RawMessage + err := json.Unmarshal(body, &rawMessages) + if err != nil { + return nil, err + } + + rcdArray := make([]BasicResourceCertificateDetails, len(rawMessages)) + + for index, rawMessage := range rawMessages { + rcd, err := unmarshalBasicResourceCertificateDetails(*rawMessage) + if err != nil { + return nil, err + } + rcdArray[index] = rcd + } + return rcdArray, nil +} + +// MarshalJSON is the custom marshaler for ResourceCertificateDetails. +func (rcd ResourceCertificateDetails) MarshalJSON() ([]byte, error) { + rcd.AuthType = AuthTypeResourceCertificateDetails + objectMap := make(map[string]interface{}) + if rcd.Certificate != nil { + objectMap["certificate"] = rcd.Certificate + } + if rcd.FriendlyName != nil { + objectMap["friendlyName"] = rcd.FriendlyName + } + if rcd.Issuer != nil { + objectMap["issuer"] = rcd.Issuer + } + if rcd.ResourceID != nil { + objectMap["resourceId"] = rcd.ResourceID + } + if rcd.Subject != nil { + objectMap["subject"] = rcd.Subject + } + if rcd.Thumbprint != nil { + objectMap["thumbprint"] = rcd.Thumbprint + } + if rcd.ValidFrom != nil { + objectMap["validFrom"] = rcd.ValidFrom + } + if rcd.ValidTo != nil { + objectMap["validTo"] = rcd.ValidTo + } + if rcd.AuthType != "" { + objectMap["authType"] = rcd.AuthType + } + return json.Marshal(objectMap) +} + +// AsResourceCertificateAndAadDetails is the BasicResourceCertificateDetails implementation for ResourceCertificateDetails. +func (rcd ResourceCertificateDetails) AsResourceCertificateAndAadDetails() (*ResourceCertificateAndAadDetails, bool) { + return nil, false +} + +// AsResourceCertificateAndAcsDetails is the BasicResourceCertificateDetails implementation for ResourceCertificateDetails. +func (rcd ResourceCertificateDetails) AsResourceCertificateAndAcsDetails() (*ResourceCertificateAndAcsDetails, bool) { + return nil, false +} + +// AsResourceCertificateDetails is the BasicResourceCertificateDetails implementation for ResourceCertificateDetails. +func (rcd ResourceCertificateDetails) AsResourceCertificateDetails() (*ResourceCertificateDetails, bool) { + return &rcd, true +} + +// AsBasicResourceCertificateDetails is the BasicResourceCertificateDetails implementation for ResourceCertificateDetails. +func (rcd ResourceCertificateDetails) AsBasicResourceCertificateDetails() (BasicResourceCertificateDetails, bool) { + return &rcd, true +} + +// Sku identifies the unique system identifier for each Azure resource. +type Sku struct { + // Name - The Sku name. Possible values include: 'Standard', 'RS0' + Name SkuName `json:"name,omitempty"` +} + +// TrackedResource tracked resource with location. +type TrackedResource struct { + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` + // ID - Resource Id represents the complete path to the resource. + ID *string `json:"id,omitempty"` + // Name - Resource name associated with the resource. + Name *string `json:"name,omitempty"` + // Type - Resource type represents the complete path of the form Namespace/ResourceType/ResourceType/... + Type *string `json:"type,omitempty"` + // ETag - Optional ETag. + ETag *string `json:"eTag,omitempty"` +} + +// MarshalJSON is the custom marshaler for TrackedResource. +func (tr TrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if tr.Location != nil { + objectMap["location"] = tr.Location + } + if tr.Tags != nil { + objectMap["tags"] = tr.Tags + } + if tr.ID != nil { + objectMap["id"] = tr.ID + } + if tr.Name != nil { + objectMap["name"] = tr.Name + } + if tr.Type != nil { + objectMap["type"] = tr.Type + } + if tr.ETag != nil { + objectMap["eTag"] = tr.ETag + } + return json.Marshal(objectMap) +} + +// UpgradeDetails details for upgrading vault. +type UpgradeDetails struct { + // OperationID - ID of the vault upgrade operation. + OperationID *string `json:"operationId,omitempty"` + // StartTimeUtc - UTC time at which the upgrade operation has started. + StartTimeUtc *date.Time `json:"startTimeUtc,omitempty"` + // LastUpdatedTimeUtc - UTC time at which the upgrade operation status was last updated. + LastUpdatedTimeUtc *date.Time `json:"lastUpdatedTimeUtc,omitempty"` + // EndTimeUtc - UTC time at which the upgrade operation has ended. + EndTimeUtc *date.Time `json:"endTimeUtc,omitempty"` + // Status - Status of the vault upgrade operation. Possible values include: 'Unknown', 'InProgress', 'Upgraded', 'Failed' + Status VaultUpgradeState `json:"status,omitempty"` + // Message - Message to the user containing information about the upgrade operation. + Message *string `json:"message,omitempty"` + // TriggerType - The way the vault upgradation was triggered. Possible values include: 'UserTriggered', 'ForcedUpgrade' + TriggerType TriggerType `json:"triggerType,omitempty"` + // UpgradedResourceID - Resource ID of the upgraded vault. + UpgradedResourceID *string `json:"upgradedResourceId,omitempty"` + // PreviousResourceID - Resource ID of the vault before the upgrade. + PreviousResourceID *string `json:"previousResourceId,omitempty"` +} + +// Vault resource information, as returned by the resource provider. +type Vault struct { + autorest.Response `json:"-"` + Properties *VaultProperties `json:"properties,omitempty"` + Sku *Sku `json:"sku,omitempty"` + // Location - Resource location. + Location *string `json:"location,omitempty"` + // Tags - Resource tags. + Tags map[string]*string `json:"tags"` + // ID - Resource Id represents the complete path to the resource. + ID *string `json:"id,omitempty"` + // Name - Resource name associated with the resource. + Name *string `json:"name,omitempty"` + // Type - Resource type represents the complete path of the form Namespace/ResourceType/ResourceType/... + Type *string `json:"type,omitempty"` + // ETag - Optional ETag. + ETag *string `json:"eTag,omitempty"` +} + +// MarshalJSON is the custom marshaler for Vault. +func (vVar Vault) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if vVar.Properties != nil { + objectMap["properties"] = vVar.Properties + } + if vVar.Sku != nil { + objectMap["sku"] = vVar.Sku + } + if vVar.Location != nil { + objectMap["location"] = vVar.Location + } + if vVar.Tags != nil { + objectMap["tags"] = vVar.Tags + } + if vVar.ID != nil { + objectMap["id"] = vVar.ID + } + if vVar.Name != nil { + objectMap["name"] = vVar.Name + } + if vVar.Type != nil { + objectMap["type"] = vVar.Type + } + if vVar.ETag != nil { + objectMap["eTag"] = vVar.ETag + } + return json.Marshal(objectMap) +} + +// VaultCertificateResponse certificate corresponding to a vault that can be used by clients to register themselves +// with the vault. +type VaultCertificateResponse struct { + autorest.Response `json:"-"` + // Name - Resource name associated with the resource. + Name *string `json:"name,omitempty"` + // Type - Resource type represents the complete path of the form Namespace/ResourceType/ResourceType/... + Type *string `json:"type,omitempty"` + // ID - Resource Id represents the complete path to the resource. + ID *string `json:"id,omitempty"` + Properties BasicResourceCertificateDetails `json:"properties,omitempty"` +} + +// UnmarshalJSON is the custom unmarshaler for VaultCertificateResponse struct. +func (vcr *VaultCertificateResponse) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + vcr.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + vcr.Type = &typeVar + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + vcr.ID = &ID + } + case "properties": + if v != nil { + properties, err := unmarshalBasicResourceCertificateDetails(*v) + if err != nil { + return err + } + vcr.Properties = properties + } + } + } + + return nil +} + +// VaultExtendedInfo vault extended information. +type VaultExtendedInfo struct { + // IntegrityKey - Integrity key. + IntegrityKey *string `json:"integrityKey,omitempty"` + // EncryptionKey - Encryption key. + EncryptionKey *string `json:"encryptionKey,omitempty"` + // EncryptionKeyThumbprint - Encryption key thumbprint. + EncryptionKeyThumbprint *string `json:"encryptionKeyThumbprint,omitempty"` + // Algorithm - Algorithm for Vault ExtendedInfo + Algorithm *string `json:"algorithm,omitempty"` +} + +// VaultExtendedInfoResource vault extended information. +type VaultExtendedInfoResource struct { + autorest.Response `json:"-"` + *VaultExtendedInfo `json:"properties,omitempty"` + // ID - Resource Id represents the complete path to the resource. + ID *string `json:"id,omitempty"` + // Name - Resource name associated with the resource. + Name *string `json:"name,omitempty"` + // Type - Resource type represents the complete path of the form Namespace/ResourceType/ResourceType/... + Type *string `json:"type,omitempty"` + // ETag - Optional ETag. + ETag *string `json:"eTag,omitempty"` +} + +// MarshalJSON is the custom marshaler for VaultExtendedInfoResource. +func (veir VaultExtendedInfoResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + if veir.VaultExtendedInfo != nil { + objectMap["properties"] = veir.VaultExtendedInfo + } + if veir.ID != nil { + objectMap["id"] = veir.ID + } + if veir.Name != nil { + objectMap["name"] = veir.Name + } + if veir.Type != nil { + objectMap["type"] = veir.Type + } + if veir.ETag != nil { + objectMap["eTag"] = veir.ETag + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON is the custom unmarshaler for VaultExtendedInfoResource struct. +func (veir *VaultExtendedInfoResource) UnmarshalJSON(body []byte) error { + var m map[string]*json.RawMessage + err := json.Unmarshal(body, &m) + if err != nil { + return err + } + for k, v := range m { + switch k { + case "properties": + if v != nil { + var vaultExtendedInfo VaultExtendedInfo + err = json.Unmarshal(*v, &vaultExtendedInfo) + if err != nil { + return err + } + veir.VaultExtendedInfo = &vaultExtendedInfo + } + case "id": + if v != nil { + var ID string + err = json.Unmarshal(*v, &ID) + if err != nil { + return err + } + veir.ID = &ID + } + case "name": + if v != nil { + var name string + err = json.Unmarshal(*v, &name) + if err != nil { + return err + } + veir.Name = &name + } + case "type": + if v != nil { + var typeVar string + err = json.Unmarshal(*v, &typeVar) + if err != nil { + return err + } + veir.Type = &typeVar + } + case "eTag": + if v != nil { + var eTag string + err = json.Unmarshal(*v, &eTag) + if err != nil { + return err + } + veir.ETag = &eTag + } + } + } + + return nil +} + +// VaultList the response model for a list of Vaults. +type VaultList struct { + autorest.Response `json:"-"` + Value *[]Vault `json:"value,omitempty"` + NextLink *string `json:"nextLink,omitempty"` +} + +// VaultListIterator provides access to a complete listing of Vault values. +type VaultListIterator struct { + i int + page VaultListPage +} + +// Next advances to the next value. If there was an error making +// the request the iterator does not advance and the error is returned. +func (iter *VaultListIterator) Next() error { + iter.i++ + if iter.i < len(iter.page.Values()) { + return nil + } + err := iter.page.Next() + if err != nil { + iter.i-- + return err + } + iter.i = 0 + return nil +} + +// NotDone returns true if the enumeration should be started or is not yet complete. +func (iter VaultListIterator) NotDone() bool { + return iter.page.NotDone() && iter.i < len(iter.page.Values()) +} + +// Response returns the raw server response from the last page request. +func (iter VaultListIterator) Response() VaultList { + return iter.page.Response() +} + +// Value returns the current value or a zero-initialized value if the +// iterator has advanced beyond the end of the collection. +func (iter VaultListIterator) Value() Vault { + if !iter.page.NotDone() { + return Vault{} + } + return iter.page.Values()[iter.i] +} + +// IsEmpty returns true if the ListResult contains no values. +func (vl VaultList) IsEmpty() bool { + return vl.Value == nil || len(*vl.Value) == 0 +} + +// vaultListPreparer prepares a request to retrieve the next set of results. +// It returns nil if no more results exist. +func (vl VaultList) vaultListPreparer() (*http.Request, error) { + if vl.NextLink == nil || len(to.String(vl.NextLink)) < 1 { + return nil, nil + } + return autorest.Prepare(&http.Request{}, + autorest.AsJSON(), + autorest.AsGet(), + autorest.WithBaseURL(to.String(vl.NextLink))) +} + +// VaultListPage contains a page of Vault values. +type VaultListPage struct { + fn func(VaultList) (VaultList, error) + vl VaultList +} + +// Next advances to the next page of values. If there was an error making +// the request the page does not advance and the error is returned. +func (page *VaultListPage) Next() error { + next, err := page.fn(page.vl) + if err != nil { + return err + } + page.vl = next + return nil +} + +// NotDone returns true if the page enumeration should be started or is not yet complete. +func (page VaultListPage) NotDone() bool { + return !page.vl.IsEmpty() +} + +// Response returns the raw server response from the last page request. +func (page VaultListPage) Response() VaultList { + return page.vl +} + +// Values returns the slice of values for the current page or nil if there are no values. +func (page VaultListPage) Values() []Vault { + if page.vl.IsEmpty() { + return nil + } + return *page.vl.Value +} + +// VaultProperties properties of the vault. +type VaultProperties struct { + // ProvisioningState - Provisioning State. + ProvisioningState *string `json:"provisioningState,omitempty"` + UpgradeDetails *UpgradeDetails `json:"upgradeDetails,omitempty"` +} + +// VaultUsage usages of a vault. +type VaultUsage struct { + // Unit - Unit of the usage. Possible values include: 'Count', 'Bytes', 'Seconds', 'Percent', 'CountPerSecond', 'BytesPerSecond' + Unit UsagesUnit `json:"unit,omitempty"` + // QuotaPeriod - Quota period of usage. + QuotaPeriod *string `json:"quotaPeriod,omitempty"` + // NextResetTime - Next reset time of usage. + NextResetTime *date.Time `json:"nextResetTime,omitempty"` + // CurrentValue - Current value of usage. + CurrentValue *int64 `json:"currentValue,omitempty"` + // Limit - Limit of usage. + Limit *int64 `json:"limit,omitempty"` + // Name - Name of usage. + Name *NameInfo `json:"name,omitempty"` +} + +// VaultUsageList usage for vault. +type VaultUsageList struct { + autorest.Response `json:"-"` + // Value - The list of usages for the given vault. + Value *[]VaultUsage `json:"value,omitempty"` +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/operations.go b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/operations.go new file mode 100644 index 000000000000..33cc200f0112 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/operations.go @@ -0,0 +1,126 @@ +package recoveryservices + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// OperationsClient is the recovery Services Client +type OperationsClient struct { + BaseClient +} + +// NewOperationsClient creates an instance of the OperationsClient client. +func NewOperationsClient(subscriptionID string) OperationsClient { + return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client. +func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient { + return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List returns the list of available operations. +func (client OperationsClient) List(ctx context.Context) (result ClientDiscoveryResponsePage, err error) { + result.fn = client.listNextResults + req, err := client.ListPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.OperationsClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.cdr.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "recoveryservices.OperationsClient", "List", resp, "Failure sending request") + return + } + + result.cdr, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.OperationsClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) { + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPath("/providers/Microsoft.RecoveryServices/operations"), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client OperationsClient) ListResponder(resp *http.Response) (result ClientDiscoveryResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listNextResults retrieves the next set of results, if any. +func (client OperationsClient) listNextResults(lastResults ClientDiscoveryResponse) (result ClientDiscoveryResponse, err error) { + req, err := lastResults.clientDiscoveryResponsePreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "recoveryservices.OperationsClient", "listNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "recoveryservices.OperationsClient", "listNextResults", resp, "Failure sending next results request") + } + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.OperationsClient", "listNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListComplete enumerates all values, automatically crossing page boundaries as required. +func (client OperationsClient) ListComplete(ctx context.Context) (result ClientDiscoveryResponseIterator, err error) { + result.page, err = client.List(ctx) + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/registeredidentities.go b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/registeredidentities.go new file mode 100644 index 000000000000..fbcb373245b1 --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/registeredidentities.go @@ -0,0 +1,107 @@ +package recoveryservices + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// RegisteredIdentitiesClient is the recovery Services Client +type RegisteredIdentitiesClient struct { + BaseClient +} + +// NewRegisteredIdentitiesClient creates an instance of the RegisteredIdentitiesClient client. +func NewRegisteredIdentitiesClient(subscriptionID string) RegisteredIdentitiesClient { + return NewRegisteredIdentitiesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewRegisteredIdentitiesClientWithBaseURI creates an instance of the RegisteredIdentitiesClient client. +func NewRegisteredIdentitiesClientWithBaseURI(baseURI string, subscriptionID string) RegisteredIdentitiesClient { + return RegisteredIdentitiesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Delete unregisters the given container from your Recovery Services vault. +// +// resourceGroupName is the name of the resource group where the recovery services vault is present. vaultName is +// the name of the recovery services vault. identityName is name of the protection container to unregister. +func (client RegisteredIdentitiesClient) Delete(ctx context.Context, resourceGroupName string, vaultName string, identityName string) (result autorest.Response, err error) { + req, err := client.DeletePreparer(ctx, resourceGroupName, vaultName, identityName) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.RegisteredIdentitiesClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "recoveryservices.RegisteredIdentitiesClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.RegisteredIdentitiesClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client RegisteredIdentitiesClient) DeletePreparer(ctx context.Context, resourceGroupName string, vaultName string, identityName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "identityName": autorest.Encode("path", identityName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vaultName": autorest.Encode("path", vaultName), + } + + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/registeredIdentities/{identityName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client RegisteredIdentitiesClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client RegisteredIdentitiesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), + autorest.ByClosing()) + result.Response = resp + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/replicationusages.go b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/replicationusages.go new file mode 100644 index 000000000000..49a1080905de --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/replicationusages.go @@ -0,0 +1,107 @@ +package recoveryservices + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// ReplicationUsagesClient is the recovery Services Client +type ReplicationUsagesClient struct { + BaseClient +} + +// NewReplicationUsagesClient creates an instance of the ReplicationUsagesClient client. +func NewReplicationUsagesClient(subscriptionID string) ReplicationUsagesClient { + return NewReplicationUsagesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewReplicationUsagesClientWithBaseURI creates an instance of the ReplicationUsagesClient client. +func NewReplicationUsagesClientWithBaseURI(baseURI string, subscriptionID string) ReplicationUsagesClient { + return ReplicationUsagesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// List fetches the replication usages of the vault. +// +// resourceGroupName is the name of the resource group where the recovery services vault is present. vaultName is +// the name of the recovery services vault. +func (client ReplicationUsagesClient) List(ctx context.Context, resourceGroupName string, vaultName string) (result ReplicationUsageList, err error) { + req, err := client.ListPreparer(ctx, resourceGroupName, vaultName) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.ReplicationUsagesClient", "List", nil, "Failure preparing request") + return + } + + resp, err := client.ListSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "recoveryservices.ReplicationUsagesClient", "List", resp, "Failure sending request") + return + } + + result, err = client.ListResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.ReplicationUsagesClient", "List", resp, "Failure responding to request") + } + + return +} + +// ListPreparer prepares the List request. +func (client ReplicationUsagesClient) ListPreparer(ctx context.Context, resourceGroupName string, vaultName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vaultName": autorest.Encode("path", vaultName), + } + + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/replicationUsages", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListSender sends the List request. The method will close the +// http.Response Body if it receives an error. +func (client ReplicationUsagesClient) ListSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListResponder handles the response to the List request. The method always +// closes the http.Response Body. +func (client ReplicationUsagesClient) ListResponder(resp *http.Response) (result ReplicationUsageList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/usages.go b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/usages.go new file mode 100644 index 000000000000..ab0ffa61edbc --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/usages.go @@ -0,0 +1,107 @@ +package recoveryservices + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// UsagesClient is the recovery Services Client +type UsagesClient struct { + BaseClient +} + +// NewUsagesClient creates an instance of the UsagesClient client. +func NewUsagesClient(subscriptionID string) UsagesClient { + return NewUsagesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewUsagesClientWithBaseURI creates an instance of the UsagesClient client. +func NewUsagesClientWithBaseURI(baseURI string, subscriptionID string) UsagesClient { + return UsagesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// ListByVaults fetches the usages of the vault. +// +// resourceGroupName is the name of the resource group where the recovery services vault is present. vaultName is +// the name of the recovery services vault. +func (client UsagesClient) ListByVaults(ctx context.Context, resourceGroupName string, vaultName string) (result VaultUsageList, err error) { + req, err := client.ListByVaultsPreparer(ctx, resourceGroupName, vaultName) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.UsagesClient", "ListByVaults", nil, "Failure preparing request") + return + } + + resp, err := client.ListByVaultsSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "recoveryservices.UsagesClient", "ListByVaults", resp, "Failure sending request") + return + } + + result, err = client.ListByVaultsResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.UsagesClient", "ListByVaults", resp, "Failure responding to request") + } + + return +} + +// ListByVaultsPreparer prepares the ListByVaults request. +func (client UsagesClient) ListByVaultsPreparer(ctx context.Context, resourceGroupName string, vaultName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vaultName": autorest.Encode("path", vaultName), + } + + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/usages", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByVaultsSender sends the ListByVaults request. The method will close the +// http.Response Body if it receives an error. +func (client UsagesClient) ListByVaultsSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByVaultsResponder handles the response to the ListByVaults request. The method always +// closes the http.Response Body. +func (client UsagesClient) ListByVaultsResponder(resp *http.Response) (result VaultUsageList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/vaultcertificates.go b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/vaultcertificates.go new file mode 100644 index 000000000000..7e738045842a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/vaultcertificates.go @@ -0,0 +1,111 @@ +package recoveryservices + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// VaultCertificatesClient is the recovery Services Client +type VaultCertificatesClient struct { + BaseClient +} + +// NewVaultCertificatesClient creates an instance of the VaultCertificatesClient client. +func NewVaultCertificatesClient(subscriptionID string) VaultCertificatesClient { + return NewVaultCertificatesClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewVaultCertificatesClientWithBaseURI creates an instance of the VaultCertificatesClient client. +func NewVaultCertificatesClientWithBaseURI(baseURI string, subscriptionID string) VaultCertificatesClient { + return VaultCertificatesClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// Create uploads a certificate for a resource. +// +// resourceGroupName is the name of the resource group where the recovery services vault is present. vaultName is +// the name of the recovery services vault. certificateName is certificate friendly name. certificateRequest is +// input parameters for uploading the vault certificate. +func (client VaultCertificatesClient) Create(ctx context.Context, resourceGroupName string, vaultName string, certificateName string, certificateRequest CertificateRequest) (result VaultCertificateResponse, err error) { + req, err := client.CreatePreparer(ctx, resourceGroupName, vaultName, certificateName, certificateRequest) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultCertificatesClient", "Create", nil, "Failure preparing request") + return + } + + resp, err := client.CreateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "recoveryservices.VaultCertificatesClient", "Create", resp, "Failure sending request") + return + } + + result, err = client.CreateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultCertificatesClient", "Create", resp, "Failure responding to request") + } + + return +} + +// CreatePreparer prepares the Create request. +func (client VaultCertificatesClient) CreatePreparer(ctx context.Context, resourceGroupName string, vaultName string, certificateName string, certificateRequest CertificateRequest) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "certificateName": autorest.Encode("path", certificateName), + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vaultName": autorest.Encode("path", vaultName), + } + + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/certificates/{certificateName}", pathParameters), + autorest.WithJSON(certificateRequest), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateSender sends the Create request. The method will close the +// http.Response Body if it receives an error. +func (client VaultCertificatesClient) CreateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateResponder handles the response to the Create request. The method always +// closes the http.Response Body. +func (client VaultCertificatesClient) CreateResponder(resp *http.Response) (result VaultCertificateResponse, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/vaultextendedinfo.go b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/vaultextendedinfo.go new file mode 100644 index 000000000000..3ae2a6dbd95e --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/vaultextendedinfo.go @@ -0,0 +1,245 @@ +package recoveryservices + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// VaultExtendedInfoClient is the recovery Services Client +type VaultExtendedInfoClient struct { + BaseClient +} + +// NewVaultExtendedInfoClient creates an instance of the VaultExtendedInfoClient client. +func NewVaultExtendedInfoClient(subscriptionID string) VaultExtendedInfoClient { + return NewVaultExtendedInfoClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewVaultExtendedInfoClientWithBaseURI creates an instance of the VaultExtendedInfoClient client. +func NewVaultExtendedInfoClientWithBaseURI(baseURI string, subscriptionID string) VaultExtendedInfoClient { + return VaultExtendedInfoClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate create vault extended info. +// +// resourceGroupName is the name of the resource group where the recovery services vault is present. vaultName is +// the name of the recovery services vault. resourceResourceExtendedInfoDetails is details of ResourceExtendedInfo +func (client VaultExtendedInfoClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, vaultName string, resourceResourceExtendedInfoDetails VaultExtendedInfoResource) (result VaultExtendedInfoResource, err error) { + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, vaultName, resourceResourceExtendedInfoDetails) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultExtendedInfoClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "recoveryservices.VaultExtendedInfoClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultExtendedInfoClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client VaultExtendedInfoClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, vaultName string, resourceResourceExtendedInfoDetails VaultExtendedInfoResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vaultName": autorest.Encode("path", vaultName), + } + + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/extendedInformation/vaultExtendedInfo", pathParameters), + autorest.WithJSON(resourceResourceExtendedInfoDetails), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client VaultExtendedInfoClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client VaultExtendedInfoClient) CreateOrUpdateResponder(resp *http.Response) (result VaultExtendedInfoResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Get get the vault extended info. +// +// resourceGroupName is the name of the resource group where the recovery services vault is present. vaultName is +// the name of the recovery services vault. +func (client VaultExtendedInfoClient) Get(ctx context.Context, resourceGroupName string, vaultName string) (result VaultExtendedInfoResource, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, vaultName) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultExtendedInfoClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "recoveryservices.VaultExtendedInfoClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultExtendedInfoClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VaultExtendedInfoClient) GetPreparer(ctx context.Context, resourceGroupName string, vaultName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vaultName": autorest.Encode("path", vaultName), + } + + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/extendedInformation/vaultExtendedInfo", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client VaultExtendedInfoClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VaultExtendedInfoClient) GetResponder(resp *http.Response) (result VaultExtendedInfoResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Update update vault extended info. +// +// resourceGroupName is the name of the resource group where the recovery services vault is present. vaultName is +// the name of the recovery services vault. resourceResourceExtendedInfoDetails is details of ResourceExtendedInfo +func (client VaultExtendedInfoClient) Update(ctx context.Context, resourceGroupName string, vaultName string, resourceResourceExtendedInfoDetails VaultExtendedInfoResource) (result VaultExtendedInfoResource, err error) { + req, err := client.UpdatePreparer(ctx, resourceGroupName, vaultName, resourceResourceExtendedInfoDetails) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultExtendedInfoClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "recoveryservices.VaultExtendedInfoClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultExtendedInfoClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client VaultExtendedInfoClient) UpdatePreparer(ctx context.Context, resourceGroupName string, vaultName string, resourceResourceExtendedInfoDetails VaultExtendedInfoResource) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vaultName": autorest.Encode("path", vaultName), + } + + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/extendedInformation/vaultExtendedInfo", pathParameters), + autorest.WithJSON(resourceResourceExtendedInfoDetails), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client VaultExtendedInfoClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client VaultExtendedInfoClient) UpdateResponder(resp *http.Response) (result VaultExtendedInfoResource, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/vaults.go b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/vaults.go new file mode 100644 index 000000000000..472d5877692b --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/vaults.go @@ -0,0 +1,494 @@ +package recoveryservices + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +import ( + "context" + "github.com/Azure/go-autorest/autorest" + "github.com/Azure/go-autorest/autorest/azure" + "net/http" +) + +// VaultsClient is the recovery Services Client +type VaultsClient struct { + BaseClient +} + +// NewVaultsClient creates an instance of the VaultsClient client. +func NewVaultsClient(subscriptionID string) VaultsClient { + return NewVaultsClientWithBaseURI(DefaultBaseURI, subscriptionID) +} + +// NewVaultsClientWithBaseURI creates an instance of the VaultsClient client. +func NewVaultsClientWithBaseURI(baseURI string, subscriptionID string) VaultsClient { + return VaultsClient{NewWithBaseURI(baseURI, subscriptionID)} +} + +// CreateOrUpdate creates or updates a Recovery Services vault. +// +// resourceGroupName is the name of the resource group where the recovery services vault is present. vaultName is +// the name of the recovery services vault. vault is recovery Services Vault to be created. +func (client VaultsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, vaultName string, vault Vault) (result Vault, err error) { + req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, vaultName, vault) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "CreateOrUpdate", nil, "Failure preparing request") + return + } + + resp, err := client.CreateOrUpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "CreateOrUpdate", resp, "Failure sending request") + return + } + + result, err = client.CreateOrUpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "CreateOrUpdate", resp, "Failure responding to request") + } + + return +} + +// CreateOrUpdatePreparer prepares the CreateOrUpdate request. +func (client VaultsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, vaultName string, vault Vault) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vaultName": autorest.Encode("path", vaultName), + } + + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPut(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}", pathParameters), + autorest.WithJSON(vault), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the +// http.Response Body if it receives an error. +func (client VaultsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always +// closes the http.Response Body. +func (client VaultsClient) CreateOrUpdateResponder(resp *http.Response) (result Vault, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// Delete deletes a vault. +// +// resourceGroupName is the name of the resource group where the recovery services vault is present. vaultName is +// the name of the recovery services vault. +func (client VaultsClient) Delete(ctx context.Context, resourceGroupName string, vaultName string) (result autorest.Response, err error) { + req, err := client.DeletePreparer(ctx, resourceGroupName, vaultName) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "Delete", nil, "Failure preparing request") + return + } + + resp, err := client.DeleteSender(req) + if err != nil { + result.Response = resp + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "Delete", resp, "Failure sending request") + return + } + + result, err = client.DeleteResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "Delete", resp, "Failure responding to request") + } + + return +} + +// DeletePreparer prepares the Delete request. +func (client VaultsClient) DeletePreparer(ctx context.Context, resourceGroupName string, vaultName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vaultName": autorest.Encode("path", vaultName), + } + + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsDelete(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// DeleteSender sends the Delete request. The method will close the +// http.Response Body if it receives an error. +func (client VaultsClient) DeleteSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// DeleteResponder handles the response to the Delete request. The method always +// closes the http.Response Body. +func (client VaultsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByClosing()) + result.Response = resp + return +} + +// Get get the Vault details. +// +// resourceGroupName is the name of the resource group where the recovery services vault is present. vaultName is +// the name of the recovery services vault. +func (client VaultsClient) Get(ctx context.Context, resourceGroupName string, vaultName string) (result Vault, err error) { + req, err := client.GetPreparer(ctx, resourceGroupName, vaultName) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "Get", nil, "Failure preparing request") + return + } + + resp, err := client.GetSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "Get", resp, "Failure sending request") + return + } + + result, err = client.GetResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "Get", resp, "Failure responding to request") + } + + return +} + +// GetPreparer prepares the Get request. +func (client VaultsClient) GetPreparer(ctx context.Context, resourceGroupName string, vaultName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vaultName": autorest.Encode("path", vaultName), + } + + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// GetSender sends the Get request. The method will close the +// http.Response Body if it receives an error. +func (client VaultsClient) GetSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// GetResponder handles the response to the Get request. The method always +// closes the http.Response Body. +func (client VaultsClient) GetResponder(resp *http.Response) (result Vault, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// ListByResourceGroup retrieve a list of Vaults. +// +// resourceGroupName is the name of the resource group where the recovery services vault is present. +func (client VaultsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result VaultListPage, err error) { + result.fn = client.listByResourceGroupNextResults + req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "ListByResourceGroup", nil, "Failure preparing request") + return + } + + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.vl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "ListByResourceGroup", resp, "Failure sending request") + return + } + + result.vl, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "ListByResourceGroup", resp, "Failure responding to request") + } + + return +} + +// ListByResourceGroupPreparer prepares the ListByResourceGroup request. +func (client VaultsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the +// http.Response Body if it receives an error. +func (client VaultsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always +// closes the http.Response Body. +func (client VaultsClient) ListByResourceGroupResponder(resp *http.Response) (result VaultList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listByResourceGroupNextResults retrieves the next set of results, if any. +func (client VaultsClient) listByResourceGroupNextResults(lastResults VaultList) (result VaultList, err error) { + req, err := lastResults.vaultListPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListByResourceGroupSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") + } + result, err = client.ListByResourceGroupResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. +func (client VaultsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result VaultListIterator, err error) { + result.page, err = client.ListByResourceGroup(ctx, resourceGroupName) + return +} + +// ListBySubscriptionID fetches all the resources of the specified type in the subscription. +func (client VaultsClient) ListBySubscriptionID(ctx context.Context) (result VaultListPage, err error) { + result.fn = client.listBySubscriptionIDNextResults + req, err := client.ListBySubscriptionIDPreparer(ctx) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "ListBySubscriptionID", nil, "Failure preparing request") + return + } + + resp, err := client.ListBySubscriptionIDSender(req) + if err != nil { + result.vl.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "ListBySubscriptionID", resp, "Failure sending request") + return + } + + result.vl, err = client.ListBySubscriptionIDResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "ListBySubscriptionID", resp, "Failure responding to request") + } + + return +} + +// ListBySubscriptionIDPreparer prepares the ListBySubscriptionID request. +func (client VaultsClient) ListBySubscriptionIDPreparer(ctx context.Context) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + } + + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsGet(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.RecoveryServices/vaults", pathParameters), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// ListBySubscriptionIDSender sends the ListBySubscriptionID request. The method will close the +// http.Response Body if it receives an error. +func (client VaultsClient) ListBySubscriptionIDSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// ListBySubscriptionIDResponder handles the response to the ListBySubscriptionID request. The method always +// closes the http.Response Body. +func (client VaultsClient) ListBySubscriptionIDResponder(resp *http.Response) (result VaultList, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} + +// listBySubscriptionIDNextResults retrieves the next set of results, if any. +func (client VaultsClient) listBySubscriptionIDNextResults(lastResults VaultList) (result VaultList, err error) { + req, err := lastResults.vaultListPreparer() + if err != nil { + return result, autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "listBySubscriptionIDNextResults", nil, "Failure preparing next results request") + } + if req == nil { + return + } + resp, err := client.ListBySubscriptionIDSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + return result, autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "listBySubscriptionIDNextResults", resp, "Failure sending next results request") + } + result, err = client.ListBySubscriptionIDResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "listBySubscriptionIDNextResults", resp, "Failure responding to next results request") + } + return +} + +// ListBySubscriptionIDComplete enumerates all values, automatically crossing page boundaries as required. +func (client VaultsClient) ListBySubscriptionIDComplete(ctx context.Context) (result VaultListIterator, err error) { + result.page, err = client.ListBySubscriptionID(ctx) + return +} + +// Update updates the vault. +// +// resourceGroupName is the name of the resource group where the recovery services vault is present. vaultName is +// the name of the recovery services vault. vault is recovery Services Vault to be created. +func (client VaultsClient) Update(ctx context.Context, resourceGroupName string, vaultName string, vault PatchVault) (result Vault, err error) { + req, err := client.UpdatePreparer(ctx, resourceGroupName, vaultName, vault) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "Update", nil, "Failure preparing request") + return + } + + resp, err := client.UpdateSender(req) + if err != nil { + result.Response = autorest.Response{Response: resp} + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "Update", resp, "Failure sending request") + return + } + + result, err = client.UpdateResponder(resp) + if err != nil { + err = autorest.NewErrorWithError(err, "recoveryservices.VaultsClient", "Update", resp, "Failure responding to request") + } + + return +} + +// UpdatePreparer prepares the Update request. +func (client VaultsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, vaultName string, vault PatchVault) (*http.Request, error) { + pathParameters := map[string]interface{}{ + "resourceGroupName": autorest.Encode("path", resourceGroupName), + "subscriptionId": autorest.Encode("path", client.SubscriptionID), + "vaultName": autorest.Encode("path", vaultName), + } + + const APIVersion = "2016-06-01" + queryParameters := map[string]interface{}{ + "api-version": APIVersion, + } + + preparer := autorest.CreatePreparer( + autorest.AsContentType("application/json; charset=utf-8"), + autorest.AsPatch(), + autorest.WithBaseURL(client.BaseURI), + autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}", pathParameters), + autorest.WithJSON(vault), + autorest.WithQueryParameters(queryParameters)) + return preparer.Prepare((&http.Request{}).WithContext(ctx)) +} + +// UpdateSender sends the Update request. The method will close the +// http.Response Body if it receives an error. +func (client VaultsClient) UpdateSender(req *http.Request) (*http.Response, error) { + return autorest.SendWithSender(client, req, + azure.DoRetryWithRegistration(client.Client)) +} + +// UpdateResponder handles the response to the Update request. The method always +// closes the http.Response Body. +func (client VaultsClient) UpdateResponder(resp *http.Response) (result Vault, err error) { + err = autorest.Respond( + resp, + client.ByInspecting(), + azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), + autorest.ByUnmarshallingJSON(&result), + autorest.ByClosing()) + result.Response = autorest.Response{Response: resp} + return +} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/version.go new file mode 100644 index 000000000000..a286fe2bb94a --- /dev/null +++ b/vendor/github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices/version.go @@ -0,0 +1,30 @@ +package recoveryservices + +import "github.com/Azure/azure-sdk-for-go/version" + +// Copyright (c) Microsoft and contributors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +// UserAgent returns the UserAgent string to use when sending http.Requests. +func UserAgent() string { + return "Azure-SDK-For-Go/" + version.Number + " recoveryservices/2016-06-01" +} + +// Version returns the semantic version (see http://semver.org) of the client. +func Version() string { + return version.Number +} diff --git a/vendor/vendor.json b/vendor/vendor.json index 38efbdd91b88..5d916e972bfd 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -178,10 +178,18 @@ "version": "v15.1.0", "versionExact": "v15.1.0" }, + { + "checksumSHA1": "MIhAkAYROlF0bQN4AT4WZWkBQtY=", + "path": "github.com/Azure/azure-sdk-for-go/services/recoveryservices/mgmt/2016-06-01/recoveryservices", + "revision": "0b745831a99da5f43aa3cc641cfcb9ed323e1f9f", + "revisionTime": "2018-04-09T17:42:04Z", + "version": "v15.1.0", + "versionExact": "v15.1.0" + }, { "checksumSHA1": "JNSBPrbVww7i2tKS02XHTRU9f6A=", "path": "github.com/Azure/azure-sdk-for-go/services/redis/mgmt/2018-03-01/redis", - "revision": "068ec4d616be5b2175509bf1fb3e4c8ea160d5c8", + "revision": "0b745831a99da5f43aa3cc641cfcb9ed323e1f9f", "revisionTime": "2018-04-09T17:42:04Z", "version": "v15.1.0", "versionExact": "v15.1.0" diff --git a/website/azurerm.erb b/website/azurerm.erb index de65afceec70..a97dd24179b0 100644 --- a/website/azurerm.erb +++ b/website/azurerm.erb @@ -91,6 +91,10 @@ azurerm_public_ips + > + azurerm_recovery_services_vault + + > azurerm_resource_group @@ -647,6 +651,15 @@ + > + Recovery Services + + + > Redis Resources + > + Data Lake Store Resources + + + > DNS Resources