Ejemplo n.º 1
0
func createResourceGroup(azureClient *azure.Client) (string, error) {
	name := fmt.Sprintf("riviera_resource_group_%d", rand.Intn(8999)+1000)

	r := azureClient.NewRequest()

	r.Command = azure.CreateResourceGroup{
		Name:     name,
		Location: azure.WestUS,
		Tags: map[string]*string{
			"Key1": azure.String("value1"),
			"Key2": azure.String("value2"),
		},
	}

	response, err := r.Execute()
	if err != nil {
		return "", err
	}

	if !response.IsSuccessful() {
		return "", fmt.Errorf("Error creating resource group %q", name)
	}

	return name, nil
}
Ejemplo n.º 2
0
func main() {
	// 1 - Configure the ARM Client with credentials
	creds := &azure.AzureResourceManagerCredentials{
		ClientID:       os.Getenv("ARM_CLIENT_ID"),
		ClientSecret:   os.Getenv("ARM_CLIENT_SECRET"),
		TenantID:       os.Getenv("ARM_TENANT_ID"),
		SubscriptionID: os.Getenv("ARM_SUBSCRIPTION_ID"),
	}

	azureClient, err := azure.NewClient(creds)
	if err != nil {
		log.Fatal(err)
	}

	// 2 - Create a new request with a location attached
	r := azureClient.NewRequest()

	// 3 - Create a command object, and assign it to the request
	r.Command = azure.CreateResourceGroup{
		Name:     resourceGroupName,
		Location: azure.WestUS,
		Tags: map[string]*string{
			"Key1": azure.String("value1"),
			"Key2": azure.String("value2"),
		},
	}

	// 4 - Execute the command
	response, err := r.Execute()
	if err != nil {
		log.Fatal(err)
	}

	// 5 - Make use of the result
	if response.IsSuccessful() {
		result := response.Parsed.(*azure.CreateResourceGroupResponse)
		fmt.Printf("Created resource group %q:\n", *result.Name)
		fmt.Printf("\tID: %s\n", *result.ID)
		fmt.Printf("\tLocation: %s\n", *result.Location)
		fmt.Printf("\tProvisioningState: %s\n", *result.ProvisioningState)
	} else {
		log.Fatalf("Failed creating resource group: %s", response.Error.Error())
	}

	// 6 - Delete the resource group
	d := azureClient.NewRequest()
	d.Command = azure.DeleteResourceGroup{
		Name: resourceGroupName,
	}
	deleteResponse, err := d.Execute()
	if err != nil {
		log.Fatal(err)
	}
	if deleteResponse.IsSuccessful() {
		log.Printf("Successfully deleted resource group %q", resourceGroupName)
	} else {
		log.Printf("Error deleting resource group %q", resourceGroupName)
	}
}
func resourceArmLoadBalancerCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient)
	loadBalancerClient := client.loadBalancerClient

	log.Printf("[INFO] preparing arguments for Azure ARM LoadBalancer creation.")

	name := d.Get("name").(string)
	location := d.Get("location").(string)
	resGroup := d.Get("resource_group_name").(string)
	tags := d.Get("tags").(map[string]interface{})
	expandedTags := expandTags(tags)

	properties := network.LoadBalancerPropertiesFormat{}

	if _, ok := d.GetOk("frontend_ip_configuration"); ok {
		properties.FrontendIPConfigurations = expandAzureRmLoadBalancerFrontendIpConfigurations(d)
	}

	loadbalancer := network.LoadBalancer{
		Name:       azure.String(name),
		Location:   azure.String(location),
		Tags:       expandedTags,
		Properties: &properties,
	}

	_, err := loadBalancerClient.CreateOrUpdate(resGroup, name, loadbalancer, make(chan struct{}))
	if err != nil {
		return errwrap.Wrapf("Error Creating/Updating LoadBalancer {{err}}", err)
	}

	read, err := loadBalancerClient.Get(resGroup, name, "")
	if err != nil {
		return errwrap.Wrapf("Error Getting LoadBalancer {{err}", err)
	}
	if read.ID == nil {
		return fmt.Errorf("Cannot read LoadBalancer %s (resource group %s) ID", name, resGroup)
	}

	d.SetId(*read.ID)

	log.Printf("[DEBUG] Waiting for LoadBalancer (%s) to become available", name)
	stateConf := &resource.StateChangeConf{
		Pending: []string{"Accepted", "Updating"},
		Target:  []string{"Succeeded"},
		Refresh: loadbalancerStateRefreshFunc(client, resGroup, name),
		Timeout: 10 * time.Minute,
	}
	if _, err := stateConf.WaitForState(); err != nil {
		return fmt.Errorf("Error waiting for LoadBalancer (%s) to become available: %s", name, err)
	}

	return resourecArmLoadBalancerRead(d, meta)
}
func expandAzureRmLoadBalancerNatRule(d *schema.ResourceData, lb *network.LoadBalancer) (*network.InboundNatRule, error) {

	properties := network.InboundNatRulePropertiesFormat{
		Protocol:     network.TransportProtocol(d.Get("protocol").(string)),
		FrontendPort: azure.Int32(int32(d.Get("frontend_port").(int))),
		BackendPort:  azure.Int32(int32(d.Get("backend_port").(int))),
	}

	if v := d.Get("frontend_ip_configuration_name").(string); v != "" {
		rule, _, exists := findLoadBalancerFrontEndIpConfigurationByName(lb, v)
		if !exists {
			return nil, fmt.Errorf("[ERROR] Cannot find FrontEnd IP Configuration with the name %s", v)
		}

		feip := network.SubResource{
			ID: rule.ID,
		}

		properties.FrontendIPConfiguration = &feip
	}

	natRule := network.InboundNatRule{
		Name:       azure.String(d.Get("name").(string)),
		Properties: &properties,
	}

	return &natRule, nil
}
func resourceArmContainerRegistryCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient).containerRegistryClient
	log.Printf("[INFO] preparing arguments for AzureRM Container Registry creation.")

	resourceGroup := d.Get("resource_group_name").(string)
	name := d.Get("name").(string)
	location := d.Get("location").(string)

	adminUserEnabled := d.Get("admin_enabled").(bool)
	tags := d.Get("tags").(map[string]interface{})

	parameters := containerregistry.Registry{
		Location: &location,
		RegistryProperties: &containerregistry.RegistryProperties{
			AdminUserEnabled: &adminUserEnabled,
		},
		Tags: expandTags(tags),
	}

	accounts := d.Get("storage_account").(*schema.Set).List()
	account := accounts[0].(map[string]interface{})
	storageAccountName := account["name"].(string)
	storageAccountAccessKey := account["access_key"].(string)
	parameters.RegistryProperties.StorageAccount = &containerregistry.StorageAccountProperties{
		Name:      azure.String(storageAccountName),
		AccessKey: azure.String(storageAccountAccessKey),
	}

	_, err := client.CreateOrUpdate(resourceGroup, name, parameters)
	if err != nil {
		return err
	}

	read, err := client.GetProperties(resourceGroup, name)
	if err != nil {
		return err
	}

	if read.ID == nil {
		return fmt.Errorf("Cannot read Container Registry %s (resource group %s) ID", name, resourceGroup)
	}

	d.SetId(*read.ID)

	return resourceArmContainerRegistryRead(d, meta)
}
Ejemplo n.º 6
0
func resourceArmSqlServerCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient)
	rivieraClient := client.rivieraClient

	tags := d.Get("tags").(map[string]interface{})
	expandedTags := expandTags(tags)

	createRequest := rivieraClient.NewRequest()
	createRequest.Command = &sql.CreateOrUpdateServer{
		Name:                       d.Get("name").(string),
		Location:                   d.Get("location").(string),
		ResourceGroupName:          d.Get("resource_group_name").(string),
		AdministratorLogin:         azure.String(d.Get("administrator_login").(string)),
		AdministratorLoginPassword: azure.String(d.Get("administrator_login_password").(string)),
		Version:                    azure.String(d.Get("version").(string)),
		Tags:                       *expandedTags,
	}

	createResponse, err := createRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error creating SQL Server: %s", err)
	}
	if !createResponse.IsSuccessful() {
		return fmt.Errorf("Error creating SQL Server: %s", createResponse.Error)
	}

	readRequest := rivieraClient.NewRequest()
	readRequest.Command = &sql.GetServer{
		Name:              d.Get("name").(string),
		ResourceGroupName: d.Get("resource_group_name").(string),
	}

	readResponse, err := readRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error reading SQL Server: %s", err)
	}
	if !readResponse.IsSuccessful() {
		return fmt.Errorf("Error reading SQL Server: %s", readResponse.Error)
	}

	resp := readResponse.Parsed.(*sql.GetServerResponse)
	d.SetId(*resp.ID)

	return resourceArmSqlServerRead(d, meta)
}
Ejemplo n.º 7
0
func setup(t *testing.T, conf map[string]string) {
	creds, err := getCredentialsFromConf(conf)
	if err != nil {
		t.Fatalf("Error getting credentials from conf: %v", err)
	}
	rivieraClient, err := getRivieraClient(creds)
	if err != nil {
		t.Fatalf("Error instantiating the riviera client: %v", err)
	}

	// Create resource group
	r := rivieraClient.NewRequest()
	r.Command = riviera.CreateResourceGroup{
		Name:     conf["resource_group_name"],
		Location: riviera.WestUS,
	}
	response, err := r.Execute()
	if err != nil {
		t.Fatalf("Error creating a resource group: %v", err)
	}
	if !response.IsSuccessful() {
		t.Fatalf("Error creating a resource group: %v", response.Error.Error())
	}

	// Create storage account
	r = rivieraClient.NewRequest()
	r.Command = storage.CreateStorageAccount{
		ResourceGroupName: conf["resource_group_name"],
		Name:              conf["storage_account_name"],
		AccountType:       riviera.String("Standard_LRS"),
		Location:          riviera.WestUS,
	}
	response, err = r.Execute()
	if err != nil {
		t.Fatalf("Error creating a storage account: %v", err)
	}
	if !response.IsSuccessful() {
		t.Fatalf("Error creating a storage account: %v", response.Error.Error())
	}

	// Create container
	accessKey, err := getStorageAccountAccessKey(conf, conf["resource_group_name"], conf["storage_account_name"])
	if err != nil {
		t.Fatalf("Error creating a storage account: %v", err)
	}
	storageClient, err := mainStorage.NewBasicClient(conf["storage_account_name"], accessKey)
	if err != nil {
		t.Fatalf("Error creating storage client for storage account %q: %s", conf["storage_account_name"], err)
	}
	blobClient := storageClient.GetBlobService()
	_, err = blobClient.CreateContainerIfNotExists(conf["container_name"], mainStorage.ContainerAccessTypePrivate)
	if err != nil {
		t.Fatalf("Couldn't create container with name %s: %s.", conf["container_name"], err)
	}
}
func resourceArmSqlFirewallRuleCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient)
	rivieraClient := client.rivieraClient

	createRequest := rivieraClient.NewRequest()
	createRequest.Command = &sql.CreateOrUpdateFirewallRule{
		Name:              d.Get("name").(string),
		ResourceGroupName: d.Get("resource_group_name").(string),
		ServerName:        d.Get("server_name").(string),
		StartIPAddress:    azure.String(d.Get("start_ip_address").(string)),
		EndIPAddress:      azure.String(d.Get("end_ip_address").(string)),
	}

	createResponse, err := createRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error creating SQL Server Firewall Rule: %s", err)
	}
	if !createResponse.IsSuccessful() {
		return fmt.Errorf("Error creating SQL Server Firewall Rule: %s", createResponse.Error)
	}

	readRequest := rivieraClient.NewRequest()
	readRequest.Command = &sql.GetFirewallRule{
		Name:              d.Get("name").(string),
		ResourceGroupName: d.Get("resource_group_name").(string),
		ServerName:        d.Get("server_name").(string),
	}

	readResponse, err := readRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error reading SQL Server Firewall Rule: %s", err)
	}
	if !readResponse.IsSuccessful() {
		return fmt.Errorf("Error reading SQL Server Firewall Rule: %s", readResponse.Error)
	}

	resp := readResponse.Parsed.(*sql.GetFirewallRuleResponse)
	d.SetId(*resp.ID)

	return resourceArmSqlFirewallRuleRead(d, meta)
}
func expandAzureRmLoadBalancerRule(d *schema.ResourceData, lb *network.LoadBalancer) (*network.LoadBalancingRule, error) {

	properties := network.LoadBalancingRulePropertiesFormat{
		Protocol:         network.TransportProtocol(d.Get("protocol").(string)),
		FrontendPort:     azure.Int32(int32(d.Get("frontend_port").(int))),
		BackendPort:      azure.Int32(int32(d.Get("backend_port").(int))),
		EnableFloatingIP: azure.Bool(d.Get("enable_floating_ip").(bool)),
	}

	if v, ok := d.GetOk("idle_timeout_in_minutes"); ok {
		properties.IdleTimeoutInMinutes = azure.Int32(int32(v.(int)))
	}

	if v := d.Get("load_distribution").(string); v != "" {
		properties.LoadDistribution = network.LoadDistribution(v)
	}

	if v := d.Get("frontend_ip_configuration_name").(string); v != "" {
		rule, _, exists := findLoadBalancerFrontEndIpConfigurationByName(lb, v)
		if !exists {
			return nil, fmt.Errorf("[ERROR] Cannot find FrontEnd IP Configuration with the name %s", v)
		}

		feip := network.SubResource{
			ID: rule.ID,
		}

		properties.FrontendIPConfiguration = &feip
	}

	if v := d.Get("backend_address_pool_id").(string); v != "" {
		beAP := network.SubResource{
			ID: &v,
		}

		properties.BackendAddressPool = &beAP
	}

	if v := d.Get("probe_id").(string); v != "" {
		pid := network.SubResource{
			ID: &v,
		}

		properties.Probe = &pid
	}

	lbRule := network.LoadBalancingRule{
		Name: azure.String(d.Get("name").(string)),
		LoadBalancingRulePropertiesFormat: &properties,
	}

	return &lbRule, nil
}
Ejemplo n.º 10
0
func main() {
	// 1 - Configure the ARM Client with credentials
	creds := &azure.AzureResourceManagerCredentials{
		ClientID:       os.Getenv("ARM_CLIENT_ID"),
		ClientSecret:   os.Getenv("ARM_CLIENT_SECRET"),
		TenantID:       os.Getenv("ARM_TENANT_ID"),
		SubscriptionID: os.Getenv("ARM_SUBSCRIPTION_ID"),
	}

	azureClient, err := azure.NewClient(creds)
	if err != nil {
		log.Fatal(err)
	}

	// 2 - Create a new request
	r := azureClient.NewRequest()

	// 3 - Create a command object, and assign it to the request
	r.Command = azure.CreateResourceGroup{
		Name:     resourceGroupName,
		Location: azure.WestUS,
		Tags: map[string]*string{
			"Key1": azure.String("value1"),
			"Key2": azure.String("value2"),
		},
	}

	// 4 - Execute the command
	response, err := r.Execute()
	if err != nil {
		log.Fatal(err)
	}

	if response.IsSuccessful() {
		log.Println("Worked - this shouldn't happen here!")
	} else {
		log.Println("Didn't Work:")
		log.Printf(response.Error.Error())
	}
}
Ejemplo n.º 11
0
func expandRedisConfiguration(d *schema.ResourceData) *map[string]*string {
	configuration := d.Get("redis_configuration").([]interface{})

	output := make(map[string]*string)

	if configuration == nil {
		return &output
	}

	// TODO: can we use this to remove the below? \/
	//config := configuration[0].(map[string]interface{})

	for _, v := range configuration {
		config := v.(map[string]interface{})

		maxClients := config["maxclients"].(string)
		if maxClients != "" {
			output["maxclients"] = azure.String(maxClients)
		}

		maxMemoryDelta := config["maxmemory_delta"].(string)
		if maxMemoryDelta != "" {
			output["maxmemory-delta"] = azure.String(maxMemoryDelta)
		}

		maxMemoryReserved := config["maxmemory_reserved"].(string)
		if maxMemoryReserved != "" {
			output["maxmemory-reserved"] = azure.String(maxMemoryReserved)
		}

		maxMemoryPolicy := config["maxmemory_policy"].(string)
		if maxMemoryPolicy != "" {
			output["maxmemory-policy"] = azure.String(maxMemoryPolicy)
		}
	}

	return &output
}
func expandAzureRmLoadBalancerProbe(d *schema.ResourceData, lb *network.LoadBalancer) (*network.Probe, error) {

	properties := network.ProbePropertiesFormat{
		NumberOfProbes:    azure.Int32(int32(d.Get("number_of_probes").(int))),
		IntervalInSeconds: azure.Int32(int32(d.Get("interval_in_seconds").(int))),
		Port:              azure.Int32(int32(d.Get("port").(int))),
	}

	if v, ok := d.GetOk("protocol"); ok {
		properties.Protocol = network.ProbeProtocol(v.(string))
	}

	if v, ok := d.GetOk("request_path"); ok {
		properties.RequestPath = azure.String(v.(string))
	}

	probe := network.Probe{
		Name:       azure.String(d.Get("name").(string)),
		Properties: &properties,
	}

	return &probe, nil
}
func expandAzureRmVirtualMachineDiagnosticsProfile(d *schema.ResourceData) *compute.DiagnosticsProfile {
	bootDiagnostics := d.Get("boot_diagnostics").([]interface{})

	diagnosticsProfile := &compute.DiagnosticsProfile{}
	if len(bootDiagnostics) > 0 {
		bootDiagnostic := bootDiagnostics[0].(map[string]interface{})

		diagnostic := &compute.BootDiagnostics{
			Enabled:    riviera.Bool(bootDiagnostic["enabled"].(bool)),
			StorageURI: riviera.String(bootDiagnostic["storage_uri"].(string)),
		}

		diagnosticsProfile.BootDiagnostics = diagnostic

		return diagnosticsProfile
	}

	return nil
}
Ejemplo n.º 14
0
func TestAccCreateDnsZone(t *testing.T) {
	rgName := test.RandPrefixString("testrg_", 20)
	zoneName := test.RandString(10) + ".com"

	test.Test(t, test.TestCase{
		Steps: []test.Step{
			&test.StepRegisterResourceProvider{
				Namespace: "Microsoft.Network",
			},
			&test.StepCreateResourceGroup{
				Name:     rgName,
				Location: azure.WestUS,
			},
			&test.StepRunCommand{
				StateBagKey: "dnszone",
				RunCommand: &CreateDNSZone{
					Name:              zoneName,
					ResourceGroupName: rgName,
					Location:          azure.Global,
					Tags: map[string]*string{
						"Purpose": azure.String("Acceptance Testing"),
					},
				},
				StateCommand: &GetDNSZone{
					Name:              zoneName,
					ResourceGroupName: rgName,
				},
				CleanupCommand: &DeleteDNSZone{
					Name:              zoneName,
					ResourceGroupName: rgName,
				},
			},
			&test.StepAssert{
				StateBagKey: "dnszone",
				Assertions: seq.Map{
					"Name":               zoneName,
					"NumberOfRecordSets": 2,
				},
			},
		},
	})
}
Ejemplo n.º 15
0
func TestAccUpdateResourceGroup(t *testing.T) {
	rgName := RandPrefixString("testrg_", 20)

	Test(t, TestCase{
		Steps: []Step{
			&StepCreateResourceGroup{
				Name:     rgName,
				Location: azure.WestUS,
			},
			&StepAssert{
				StateBagKey: "resourcegroup",
				Assertions: seq.Map{
					"Name":     rgName,
					"Location": azure.WestUS,
				},
			},
			&StepRunCommand{
				StateBagKey: "resourcegroup",
				RunCommand: &azure.UpdateResourceGroup{
					Name: rgName,
					Tags: map[string]*string{
						"Purpose": azure.String("Acceptance Testing"),
					},
				},
				StateCommand: &azure.GetResourceGroup{
					Name: rgName,
				},
			},
			&StepAssert{
				StateBagKey: "resourcegroup",
				Assertions: seq.Map{
					"Name":         rgName,
					"Tags.Purpose": "Acceptance Testing",
				},
			},
		},
	})
}
Ejemplo n.º 16
0
func TestAccCreateDnsARecordSet(t *testing.T) {
	rgName := test.RandPrefixString("testrg_", 20)
	zoneName := test.RandString(10) + ".com"
	recordSetName := test.RandPrefixString("rs_", 10)

	test.Test(t, test.TestCase{
		Steps: []test.Step{
			&test.StepRegisterResourceProvider{
				Namespace: "Microsoft.Network",
			},
			&test.StepCreateResourceGroup{
				Name:     rgName,
				Location: azure.WestUS,
			},
			&test.StepRunCommand{
				StateBagKey: "dnszone",
				RunCommand: &CreateDNSZone{
					Name:              zoneName,
					ResourceGroupName: rgName,
					Location:          azure.Global,
					Tags: map[string]*string{
						"Purpose": azure.String("Acceptance Testing"),
					},
				},
				StateCommand: &GetDNSZone{
					Name:              zoneName,
					ResourceGroupName: rgName,
				},
				CleanupCommand: &DeleteDNSZone{
					Name:              zoneName,
					ResourceGroupName: rgName,
				},
			},
			&test.StepRunCommand{
				StateBagKey: "dnsrecordset",
				RunCommand: &CreateARecordSet{
					Name:              recordSetName,
					ZoneName:          zoneName,
					ResourceGroupName: rgName,
					Location:          azure.Global,
					Tags: map[string]*string{
						"Purpose": azure.String("Acceptance Testing"),
					},
					TTL: 300,
					ARecords: []ARecord{
						ARecord{
							IPv4Address: "10.0.10.1",
						},
						ARecord{
							IPv4Address: "10.0.10.2",
						},
					},
				},
				StateCommandURIKey: "ID",
				StateCommand:       &GetARecordSet{},
				CleanupCommand: &DeleteRecordSet{
					Name:              recordSetName,
					ZoneName:          zoneName,
					ResourceGroupName: rgName,
					RecordSetType:     "A",
				},
			},
			&test.StepAssert{
				StateBagKey: "dnsrecordset",
				Assertions: seq.Map{
					"TTL":                     300,
					"Name":                    recordSetName,
					"Location":                azure.Global,
					"ARecords[0].ipv4Address": "10.0.10.1",
					"ARecords[1].ipv4Address": "10.0.10.2",
				},
			},
		},
	})
}
Ejemplo n.º 17
0
func main() {
	creds := &azure.AzureResourceManagerCredentials{
		ClientID:       os.Getenv("ARM_CLIENT_ID"),
		ClientSecret:   os.Getenv("ARM_CLIENT_SECRET"),
		TenantID:       os.Getenv("ARM_TENANT_ID"),
		SubscriptionID: os.Getenv("ARM_SUBSCRIPTION_ID"),
	}

	azureClient, err := azure.NewClient(creds)
	if err != nil {
		log.Fatal(err)
	}

	resourceGroupName, err := createResourceGroup(azureClient)
	if err != nil {
		log.Fatal(err)
	}

	r := azureClient.NewRequest()

	r.Command = sql.CreateOrUpdateServer{
		ResourceGroupName: resourceGroupName,
		Name:              "rivieradbservertest123",
		Location:          azure.WestUS,
		Tags: map[string]*string{
			"Key1": azure.String("value1"),
			"Key2": azure.String("value2"),
		},
		AdministratorLogin:         azure.String("hello"),
		AdministratorLoginPassword: azure.String("thisIsDog11'"),
		Version:                    azure.String("12.0"),
	}

	response, err := r.Execute()
	if err != nil {
		log.Fatal(err)
	}

	if response.IsSuccessful() {
		result := response.Parsed.(*sql.CreateOrUpdateServerResponse)

		log.Printf("Created SQL Server %q\n", result.Name)
		log.Printf("\tID: %s\n", *result.ID)
		log.Printf("\tFQDN: %s\n", *result.FullyQualifiedDomainName)
		log.Printf("\tFQDN: %s\n", *result.State)
	} else {
		log.Printf("Failed creating SQL Server: %s", response.Error.Error())
	}

	r3 := azureClient.NewRequest()
	r3.Command = sql.GetServer{
		ResourceGroupName: resourceGroupName,
		Name:              "rivieradbservertest123",
	}
	response, err = r3.Execute()
	if err != nil {
		log.Fatal(err)
	}

	if response.IsSuccessful() {
		result := response.Parsed.(*sql.GetServerResponse)

		log.Printf("Got SQL Server %q\n", result.Name)
		log.Printf(spew.Sdump(result))
	} else {
		log.Printf("Failed to get SQL Server: %s", response.Error.Error())
	}

	r2 := azureClient.NewRequest()
	r2.Command = sql.DeleteServer{
		ResourceGroupName: resourceGroupName,
		Name:              "rivieradbservertest123",
	}

	response2, err := r2.Execute()
	if err != nil {
		log.Fatal(err)
	}

	if response2.IsSuccessful() {
		log.Println("Deleted Server")
	} else {
		log.Printf("Failed deleting SQL Server: %s", response2.Error.Error())
	}

}
Ejemplo n.º 18
0
func main() {
	creds := &azure.AzureResourceManagerCredentials{
		ClientID:       os.Getenv("ARM_CLIENT_ID"),
		ClientSecret:   os.Getenv("ARM_CLIENT_SECRET"),
		TenantID:       os.Getenv("ARM_TENANT_ID"),
		SubscriptionID: os.Getenv("ARM_SUBSCRIPTION_ID"),
	}

	azureClient, err := azure.NewClient(creds)
	if err != nil {
		log.Fatal(err)
	}

	resourceGroupName, err := createResourceGroup(azureClient)
	if err != nil {
		log.Fatal(err)
	}

	storageAccountName := fmt.Sprintf("rivierastorage%d", rand.Intn(8999)+1000)

	r := azureClient.NewRequest()
	r.Command = storage.CreateStorageAccount{
		ResourceGroupName: resourceGroupName,
		Name:              storageAccountName,
		AccountType:       azure.String("Standard_LRS"),
		Location:          azure.WestUS,
	}

	response, err := r.Execute()
	if err != nil {
		log.Fatal(err)
	}

	if response.IsSuccessful() {
		result := response.Parsed.(*storage.CreateStorageAccountResponse)

		log.Printf("Created Storage Account\n")
		log.Printf("\tLocation: %s\n", *result.Location)
		log.Printf("\tAccount Type: %s\n", *result.AccountType)
	} else {
		log.Printf("Failed creating Storage Account\n")
	}

	read := azureClient.NewRequest()
	read.Command = storage.GetStorageAccountProperties{
		ResourceGroupName: resourceGroupName,
		Name:              storageAccountName,
	}

	readResponse, err := read.Execute()
	if err != nil {
		log.Fatalf("Failed reading account: %s", err)
	}

	var id string
	if readResponse.IsSuccessful() {
		result := readResponse.Parsed.(*storage.GetStorageAccountPropertiesResponse)

		log.Printf("ID: %s\n", *result.ID)
		spew.Dump(result)
		id = *result.ID
	} else {
		log.Printf("Failed getting Storage Account type: %s\n", readResponse.Error.Error())
	}

	r2 := azureClient.NewRequestForURI(id)
	r2.Command = storage.UpdateStorageAccountType{
		AccountType: azure.String("Standard_GRS"),
	}
	response2, err := r2.Execute()
	if err != nil {
		log.Fatal(err)
	}

	if response2.IsSuccessful() {
		result := response2.Parsed.(*storage.UpdateStorageAccountTypeResponse)
		log.Printf("Updated Storage Account Type to %s\n", *result.AccountType)
	} else {
		log.Printf("Failed updating Storage Account type\n")
	}

	r3 := azureClient.NewRequestForURI(id)
	r3.Command = storage.UpdateStorageAccountCustomDomain{
		CustomDomain: storage.CustomDomain{
			Name: azure.String("testname.hashicorptest.com"),
		},
	}

	response3, err := r3.Execute()
	if err != nil {
		log.Fatal(err)
	}

	if response3.IsSuccessful() {
		result := response3.Parsed.(*storage.UpdateStorageAccountCustomDomainResponse)
		log.Printf("Updated Storage Account Custom Domain to %s\n", *result.CustomDomain.Name)
	} else {
		log.Printf("Failed updating Storage Account Custom Domain\n")
	}

}
func expandAzureRmLoadBalancerBackendAddressPools(d *schema.ResourceData) network.BackendAddressPool {
	return network.BackendAddressPool{
		Name: azure.String(d.Get("name").(string)),
	}
}
Ejemplo n.º 20
0
func resourceArmSqlDatabaseCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*ArmClient)
	rivieraClient := client.rivieraClient

	tags := d.Get("tags").(map[string]interface{})
	expandedTags := expandTags(tags)

	command := &sql.CreateOrUpdateDatabase{
		Name:              d.Get("name").(string),
		Location:          d.Get("location").(string),
		ResourceGroupName: d.Get("resource_group_name").(string),
		ServerName:        d.Get("server_name").(string),
		Tags:              *expandedTags,
		CreateMode:        azure.String(d.Get("create_mode").(string)),
	}

	if v, ok := d.GetOk("source_database_id"); ok {
		command.SourceDatabaseID = azure.String(v.(string))
	}

	if v, ok := d.GetOk("edition"); ok {
		command.Edition = azure.String(v.(string))
	}

	if v, ok := d.GetOk("collation"); ok {
		command.Collation = azure.String(v.(string))
	}

	if v, ok := d.GetOk("max_size_bytes"); ok {
		command.MaxSizeBytes = azure.String(v.(string))
	}

	if v, ok := d.GetOk("source_database_deletion_date"); ok {
		command.SourceDatabaseDeletionDate = azure.String(v.(string))
	}

	if v, ok := d.GetOk("requested_service_objective_id"); ok {
		command.RequestedServiceObjectiveID = azure.String(v.(string))
	}

	if v, ok := d.GetOk("requested_service_objective_name"); ok {
		command.RequestedServiceObjectiveName = azure.String(v.(string))
	}

	createRequest := rivieraClient.NewRequest()
	createRequest.Command = command

	createResponse, err := createRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error creating SQL Database: %s", err)
	}
	if !createResponse.IsSuccessful() {
		return fmt.Errorf("Error creating SQL Database: %s", createResponse.Error)
	}

	readRequest := rivieraClient.NewRequest()
	readRequest.Command = &sql.GetDatabase{
		Name:              d.Get("name").(string),
		ResourceGroupName: d.Get("resource_group_name").(string),
		ServerName:        d.Get("server_name").(string),
	}

	readResponse, err := readRequest.Execute()
	if err != nil {
		return fmt.Errorf("Error reading SQL Database: %s", err)
	}
	if !readResponse.IsSuccessful() {
		return fmt.Errorf("Error reading SQL Database: %s", readResponse.Error)
	}

	resp := readResponse.Parsed.(*sql.GetDatabaseResponse)
	d.SetId(*resp.ID)

	return resourceArmSqlDatabaseRead(d, meta)
}