Example #1
0
func getTestSecurityGroup(services ...v1.Service) network.SecurityGroup {
	rules := []network.SecurityRule{}

	for _, service := range services {
		for _, port := range service.Spec.Ports {
			ruleName := getRuleName(&service, port)

			sources := getServiceSourceRanges(&service)
			for _, src := range sources {
				rules = append(rules, network.SecurityRule{
					Name: to.StringPtr(ruleName),
					Properties: &network.SecurityRulePropertiesFormat{
						SourceAddressPrefix:  to.StringPtr(src),
						DestinationPortRange: to.StringPtr(fmt.Sprintf("%d", port.Port)),
					},
				})
			}
		}
	}

	sg := network.SecurityGroup{
		Properties: &network.SecurityGroupPropertiesFormat{
			SecurityRules: &rules,
		},
	}

	return sg
}
Example #2
0
// vmExtension creates a CustomScript VM extension for the given VM
// which will execute the CustomData on the machine as a script.
func vmExtensionProperties(os jujuos.OSType) (*compute.VirtualMachineExtensionProperties, error) {
	var commandToExecute, extensionPublisher, extensionType, extensionVersion string

	switch os {
	case jujuos.Windows:
		commandToExecute = windowsExecuteCustomScriptCommand
		extensionPublisher = windowsCustomScriptPublisher
		extensionType = windowsCustomScriptType
		extensionVersion = windowsCustomScriptVersion
	case jujuos.CentOS:
		commandToExecute = linuxExecuteCustomScriptCommand
		extensionPublisher = linuxCustomScriptPublisher
		extensionType = linuxCustomScriptType
		extensionVersion = linuxCustomScriptVersion
	default:
		// Ubuntu renders CustomData as cloud-config, and interprets
		// it with cloud-init. Windows and CentOS do not use cloud-init
		// on Azure.
		return nil, errors.NotSupportedf("CustomScript extension for OS %q", os)
	}

	extensionSettings := map[string]interface{}{
		"commandToExecute": commandToExecute,
	}
	return &compute.VirtualMachineExtensionProperties{
		Publisher:               to.StringPtr(extensionPublisher),
		Type:                    to.StringPtr(extensionType),
		TypeHandlerVersion:      to.StringPtr(extensionVersion),
		AutoUpgradeMinorVersion: to.BoolPtr(true),
		Settings:                &extensionSettings,
	}, nil
}
Example #3
0
func (s *environSuite) TestDestroyController(c *gc.C) {
	groups := []resources.ResourceGroup{{
		Name: to.StringPtr("group1"),
	}, {
		Name: to.StringPtr("group2"),
	}}
	result := resources.ResourceGroupListResult{Value: &groups}

	env := s.openEnviron(c)
	s.sender = azuretesting.Senders{
		s.makeSender(".*/resourcegroups", result),        // GET
		s.makeSender(".*/resourcegroups/group[12]", nil), // DELETE
		s.makeSender(".*/resourcegroups/group[12]", nil), // DELETE
	}
	err := env.DestroyController(s.controllerUUID)
	c.Assert(err, jc.ErrorIsNil)

	c.Assert(s.requests, gc.HasLen, 3)
	c.Assert(s.requests[0].Method, gc.Equals, "GET")
	c.Assert(s.requests[0].URL.Query().Get("$filter"), gc.Equals, fmt.Sprintf(
		"tagname eq 'juju-controller-uuid' and tagvalue eq '%s'",
		testing.ControllerTag.Id(),
	))
	c.Assert(s.requests[1].Method, gc.Equals, "DELETE")
	c.Assert(s.requests[2].Method, gc.Equals, "DELETE")

	// Groups are deleted concurrently, so there's no known order.
	groupsDeleted := []string{
		path.Base(s.requests[1].URL.Path),
		path.Base(s.requests[2].URL.Path),
	}
	c.Assert(groupsDeleted, jc.SameContents, []string{"group1", "group2"})
}
Example #4
0
func (a AzureClient) CreatePublicIPAddress(ctx *DeploymentContext, resourceGroup, name, location string, isStatic bool, dnsLabel string) error {
	log.Info("Creating public IP address.", logutil.Fields{
		"name":   name,
		"static": isStatic})

	var ipType network.IPAllocationMethod
	if isStatic {
		ipType = network.Static
	} else {
		ipType = network.Dynamic
	}

	var dns *network.PublicIPAddressDNSSettings
	if dnsLabel != "" {
		dns = &network.PublicIPAddressDNSSettings{
			DomainNameLabel: to.StringPtr(dnsLabel),
		}
	}

	_, err := a.publicIPAddressClient().CreateOrUpdate(resourceGroup, name,
		network.PublicIPAddress{
			Location: to.StringPtr(location),
			Properties: &network.PublicIPAddressPropertiesFormat{
				PublicIPAllocationMethod: ipType,
				DNSSettings:              dns,
			},
		}, nil)
	if err != nil {
		return err
	}
	ip, err := a.publicIPAddressClient().Get(resourceGroup, name, "")
	ctx.PublicIPAddressID = to.String(ip.ID)
	return err
}
Example #5
0
func getTestLoadBalancer(services ...api.Service) network.LoadBalancer {
	rules := []network.LoadBalancingRule{}
	probes := []network.Probe{}

	for _, service := range services {
		for _, port := range service.Spec.Ports {
			ruleName := getRuleName(&service, port)
			rules = append(rules, network.LoadBalancingRule{
				Name: to.StringPtr(ruleName),
				Properties: &network.LoadBalancingRulePropertiesFormat{
					FrontendPort: to.Int32Ptr(port.Port),
					BackendPort:  to.Int32Ptr(port.Port),
				},
			})
			probes = append(probes, network.Probe{
				Name: to.StringPtr(ruleName),
				Properties: &network.ProbePropertiesFormat{
					Port: to.Int32Ptr(port.NodePort),
				},
			})
		}
	}

	lb := network.LoadBalancer{
		Properties: &network.LoadBalancerPropertiesFormat{
			LoadBalancingRules: &rules,
			Probes:             &probes,
		},
	}

	return lb
}
Example #6
0
func (s *environSuite) TestStartInstanceCentOS(c *gc.C) {
	// Starting a CentOS VM, we should not expect an image query.
	s.PatchValue(&s.ubuntuServerSKUs, nil)

	env := s.openEnviron(c)
	s.sender = s.startInstanceSenders(false)
	s.requests = nil
	args := makeStartInstanceParams(c, s.controllerUUID, "centos7")
	_, err := env.StartInstance(args)
	c.Assert(err, jc.ErrorIsNil)

	vmExtensionSettings := map[string]interface{}{
		"commandToExecute": `bash -c 'base64 -d /var/lib/waagent/CustomData | bash'`,
	}
	s.assertStartInstanceRequests(c, s.requests, assertStartInstanceRequestsParams{
		imageReference: &centos7ImageReference,
		diskSizeGB:     32,
		vmExtension: &compute.VirtualMachineExtensionProperties{
			Publisher:               to.StringPtr("Microsoft.OSTCExtensions"),
			Type:                    to.StringPtr("CustomScriptForLinux"),
			TypeHandlerVersion:      to.StringPtr("1.4"),
			AutoUpgradeMinorVersion: to.BoolPtr(true),
			Settings:                &vmExtensionSettings,
		},
		osProfile: &linuxOsProfile,
	})
}
Example #7
0
func checkName(name string) {
	c, err := helpers.LoadCredentials()
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	ac := storage.NewAccountsClient(c["subscriptionID"])

	spt, err := helpers.NewServicePrincipalTokenFromCredentials(c, azure.PublicCloud.ResourceManagerEndpoint)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}
	ac.Authorizer = spt

	ac.Sender = autorest.CreateSender(
		autorest.WithLogging(log.New(os.Stdout, "sdk-example: ", log.LstdFlags)))

	ac.RequestInspector = withInspection()
	ac.ResponseInspector = byInspecting()
	cna, err := ac.CheckNameAvailability(
		storage.AccountCheckNameAvailabilityParameters{
			Name: to.StringPtr(name),
			Type: to.StringPtr("Microsoft.Storage/storageAccounts")})

	if err != nil {
		log.Fatalf("Error: %v", err)
	} else {
		if to.Bool(cna.NameAvailable) {
			fmt.Printf("The name '%s' is available\n", name)
		} else {
			fmt.Printf("The name '%s' is unavailable because %s\n", name, to.String(cna.Message))
		}
	}
}
Example #8
0
func deviceCodeSender() autorest.Sender {
	return azuretesting.NewSenderWithValue(azure.DeviceCode{
		DeviceCode: to.StringPtr("device-code"),
		Interval:   to.Int64Ptr(1), // 1 second between polls
		Message:    to.StringPtr("open your browser, etc."),
	})
}
Example #9
0
func (s *TemplateBuilder) BuildWindows(keyVaultName, winRMCertificateUrl string) error {
	resource, err := s.getResourceByType(resourceVirtualMachine)
	if err != nil {
		return err
	}

	profile := resource.Properties.OsProfile

	profile.Secrets = &[]compute.VaultSecretGroup{
		{
			SourceVault: &compute.SubResource{
				ID: to.StringPtr(s.toResourceID(resourceKeyVaults, keyVaultName)),
			},
			VaultCertificates: &[]compute.VaultCertificate{
				{
					CertificateStore: to.StringPtr("My"),
					CertificateURL:   to.StringPtr(winRMCertificateUrl),
				},
			},
		},
	}

	profile.WindowsConfiguration = &compute.WindowsConfiguration{
		ProvisionVMAgent: to.BoolPtr(true),
		WinRM: &compute.WinRMConfiguration{
			Listeners: &[]compute.WinRMListener{
				{
					Protocol:       "https",
					CertificateURL: to.StringPtr(winRMCertificateUrl),
				},
			},
		},
	}
	return nil
}
Example #10
0
func (az *Cloud) ensurePublicIPExists(serviceName, pipName string) (*network.PublicIPAddress, error) {
	pip, existsPip, err := az.getPublicIPAddress(pipName)
	if err != nil {
		return nil, err
	}
	if existsPip {
		return &pip, nil
	}

	pip.Name = to.StringPtr(pipName)
	pip.Location = to.StringPtr(az.Location)
	pip.Properties = &network.PublicIPAddressPropertiesFormat{
		PublicIPAllocationMethod: network.Static,
	}
	pip.Tags = &map[string]*string{"service": &serviceName}

	glog.V(3).Infof("ensure(%s): pip(%s) - creating", serviceName, *pip.Name)
	_, err = az.PublicIPAddressesClient.CreateOrUpdate(az.ResourceGroup, *pip.Name, pip, nil)
	if err != nil {
		return nil, err
	}

	pip, err = az.PublicIPAddressesClient.Get(az.ResourceGroup, *pip.Name, "")
	if err != nil {
		return nil, err
	}

	return &pip, nil

}
Example #11
0
func createAccount(resourceGroup, name string) {
	c, err := helpers.LoadCredentials()
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	ac := storage.NewAccountsClient(c["subscriptionID"])

	spt, err := helpers.NewServicePrincipalTokenFromCredentials(c, azure.AzureResourceManagerScope)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}
	ac.Authorizer = spt

	cna, err := ac.CheckNameAvailability(
		storage.AccountCheckNameAvailabilityParameters{
			Name: to.StringPtr(name),
			Type: to.StringPtr("Microsoft.Storage/storageAccounts")})
	if err != nil {
		log.Fatalf("Error: %v", err)
		return
	}
	if !to.Bool(cna.NameAvailable) {
		fmt.Printf("%s is unavailable -- try again\n", name)
		return
	}
	fmt.Printf("%s is available\n\n", name)

	ac.Sender = autorest.CreateSender(withWatcher())
	ac.PollingMode = autorest.PollUntilAttempts
	ac.PollingAttempts = 5

	cp := storage.AccountCreateParameters{}
	cp.Location = to.StringPtr("westus")
	cp.Properties = &storage.AccountPropertiesCreateParameters{AccountType: storage.StandardLRS}

	sa, err := ac.Create(resourceGroup, name, cp)
	if err != nil {
		if sa.Response.StatusCode != http.StatusAccepted {
			fmt.Printf("Creation of %s.%s failed with err -- %v\n", resourceGroup, name, err)
			return
		}
		fmt.Printf("Create initiated for %s.%s -- poll %s to check status\n",
			resourceGroup,
			name,
			sa.GetPollingLocation())
		return
	}

	fmt.Printf("Successfully created %s.%s\n\n", resourceGroup, name)

	ac.Sender = nil
	r, err := ac.Delete(resourceGroup, name)
	if err != nil {
		fmt.Printf("Delete of %s.%s failed with status %s\n...%v\n", resourceGroup, name, r.Status, err)
		return
	}
	fmt.Printf("Deletion of %s.%s succeeded -- %s\n", resourceGroup, name, r.Status)
}
Example #12
0
func makeVirtualMachine(name string) compute.VirtualMachine {
	return compute.VirtualMachine{
		Name: to.StringPtr(name),
		Properties: &compute.VirtualMachineProperties{
			ProvisioningState: to.StringPtr("Succeeded"),
		},
	}
}
Example #13
0
func roleDefinitionListSender() autorest.Sender {
	roleDefinitions := []authorization.RoleDefinition{{
		ID:   to.StringPtr("owner-role-id"),
		Name: to.StringPtr("Owner"),
	}}
	return azuretesting.NewSenderWithValue(authorization.RoleDefinitionListResult{
		Value: &roleDefinitions,
	})
}
Example #14
0
func main() {
	resourceGroup := "resourceGroupName"
	name := "gosdktestname01"

	c := map[string]string{
		"AZURE_CLIENT_ID":       os.Getenv("AZURE_CLIENT_ID"),
		"AZURE_CLIENT_SECRET":   os.Getenv("AZURE_CLIENT_SECRET"),
		"AZURE_SUBSCRIPTION_ID": os.Getenv("AZURE_SUBSCRIPTION_ID"),
		"AZURE_TENANT_ID":       os.Getenv("AZURE_TENANT_ID")}
	if err := checkEnvVar(&c); err != nil {
		log.Fatalf("Error: %v", err)
		return
	}
	spt, err := helpers.NewServicePrincipalTokenFromCredentials(c, azure.PublicCloud.ResourceManagerEndpoint)
	if err != nil {
		log.Fatalf("Error: %v", err)
		return
	}

	ac := storage.NewAccountsClient(c["AZURE_SUBSCRIPTION_ID"])
	ac.Authorizer = spt

	cna, err := ac.CheckNameAvailability(
		storage.AccountCheckNameAvailabilityParameters{
			Name: to.StringPtr(name),
			Type: to.StringPtr("Microsoft.Storage/storageAccounts")})
	if err != nil {
		log.Fatalf("Error: %v", err)
		return
	}
	if !to.Bool(cna.NameAvailable) {
		fmt.Printf("%s is unavailable -- try with another name\n", name)
		return
	}
	fmt.Printf("%s is available\n\n", name)

	cp := storage.AccountCreateParameters{
		Sku: &storage.Sku{
			Name: storage.StandardLRS,
			Tier: storage.Standard},
		Location: to.StringPtr("westus")}
	cancel := make(chan struct{})
	if _, err = ac.Create(resourceGroup, name, cp, cancel); err != nil {
		fmt.Printf("Create '%s' storage account failed: %v\n", name, err)
		return
	}
	fmt.Printf("Successfully created '%s' storage account in '%s' resource group\n\n", name, resourceGroup)

	r, err := ac.Delete(resourceGroup, name)
	if err != nil {
		fmt.Printf("Delete of '%s' failed with status %s\n...%v\n", name, r.Status, err)
		return
	}
	fmt.Printf("Deletion of '%s' storage account in '%s' resource group succeeded -- %s\n", name, resourceGroup, r.Status)
}
Example #15
0
File: storage.go Project: bac/juju
// createVolume updates the provided VirtualMachine's StorageProfile with the
// parameters for creating a new data disk. We don't actually interact with
// the Azure API until after all changes to the VirtualMachine are made.
func (v *azureVolumeSource) createVolume(
	vm *compute.VirtualMachine,
	p storage.VolumeParams,
	storageAccount *armstorage.Account,
) (*storage.Volume, *storage.VolumeAttachment, error) {

	lun, err := nextAvailableLUN(vm)
	if err != nil {
		return nil, nil, errors.Annotate(err, "choosing LUN")
	}

	dataDisksRoot := dataDiskVhdRoot(storageAccount)
	dataDiskName := p.Tag.String()
	vhdURI := dataDisksRoot + dataDiskName + vhdExtension

	sizeInGib := mibToGib(p.Size)
	dataDisk := compute.DataDisk{
		Lun:          to.Int32Ptr(lun),
		DiskSizeGB:   to.Int32Ptr(int32(sizeInGib)),
		Name:         to.StringPtr(dataDiskName),
		Vhd:          &compute.VirtualHardDisk{to.StringPtr(vhdURI)},
		Caching:      compute.ReadWrite,
		CreateOption: compute.Empty,
	}

	var dataDisks []compute.DataDisk
	if vm.Properties.StorageProfile.DataDisks != nil {
		dataDisks = *vm.Properties.StorageProfile.DataDisks
	}
	dataDisks = append(dataDisks, dataDisk)
	vm.Properties.StorageProfile.DataDisks = &dataDisks

	// Data disks associate VHDs to machines. In Juju's storage model,
	// the VHD is the volume and the disk is the volume attachment.
	volume := storage.Volume{
		p.Tag,
		storage.VolumeInfo{
			VolumeId: dataDiskName,
			Size:     gibToMib(sizeInGib),
			// We don't currently support persistent volumes in
			// Azure, as it requires removal of "comp=media" when
			// deleting VMs, complicating cleanup.
			Persistent: true,
		},
	}
	volumeAttachment := storage.VolumeAttachment{
		p.Tag,
		p.Attachment.Machine,
		storage.VolumeAttachmentInfo{
			BusAddress: diskBusAddress(lun),
		},
	}
	return &volume, &volumeAttachment, nil
}
Example #16
0
func makePublicIPAddress(pipName, vmName, ipAddress string) network.PublicIPAddress {
	tags := map[string]*string{"juju-machine-name": &vmName}
	pip := network.PublicIPAddress{
		Name:       to.StringPtr(pipName),
		Tags:       &tags,
		Properties: &network.PublicIPAddressPropertiesFormat{},
	}
	if ipAddress != "" {
		pip.Properties.IPAddress = to.StringPtr(ipAddress)
	}
	return pip
}
Example #17
0
func makeSecurityRule(name, ipAddress, ports string) network.SecurityRule {
	return network.SecurityRule{
		Name: to.StringPtr(name),
		Properties: &network.SecurityRulePropertiesFormat{
			Protocol:                 network.TCP,
			DestinationAddressPrefix: to.StringPtr(ipAddress),
			DestinationPortRange:     to.StringPtr(ports),
			Access:                   network.Allow,
			Priority:                 to.Int32Ptr(200),
			Direction:                network.Inbound,
		},
	}
}
Example #18
0
// CreateRoute creates the described managed route
// route.Name will be ignored, although the cloud-provider may use nameHint
// to create a more user-meaningful name.
func (az *Cloud) CreateRoute(clusterName string, nameHint string, kubeRoute *cloudprovider.Route) error {
	glog.V(2).Infof("create: creating route. clusterName=%q instance=%q cidr=%q", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR)

	routeTable, existsRouteTable, err := az.getRouteTable()
	if err != nil {
		return err
	}
	if !existsRouteTable {
		routeTable = network.RouteTable{
			Name:                       to.StringPtr(az.RouteTableName),
			Location:                   to.StringPtr(az.Location),
			RouteTablePropertiesFormat: &network.RouteTablePropertiesFormat{},
		}

		glog.V(3).Infof("create: creating routetable. routeTableName=%q", az.RouteTableName)
		_, err = az.RouteTablesClient.CreateOrUpdate(az.ResourceGroup, az.RouteTableName, routeTable, nil)
		if err != nil {
			return err
		}

		routeTable, err = az.RouteTablesClient.Get(az.ResourceGroup, az.RouteTableName, "")
		if err != nil {
			return err
		}
	}

	targetIP, err := az.getIPForMachine(kubeRoute.TargetNode)
	if err != nil {
		return err
	}

	routeName := mapNodeNameToRouteName(kubeRoute.TargetNode)
	route := network.Route{
		Name: to.StringPtr(routeName),
		RoutePropertiesFormat: &network.RoutePropertiesFormat{
			AddressPrefix:    to.StringPtr(kubeRoute.DestinationCIDR),
			NextHopType:      network.RouteNextHopTypeVirtualAppliance,
			NextHopIPAddress: to.StringPtr(targetIP),
		},
	}

	glog.V(3).Infof("create: creating route: instance=%q cidr=%q", kubeRoute.TargetNode, kubeRoute.DestinationCIDR)
	_, err = az.RoutesClient.CreateOrUpdate(az.ResourceGroup, az.RouteTableName, *route.Name, route, nil)
	if err != nil {
		return err
	}

	glog.V(2).Infof("create: route created. clusterName=%q instance=%q cidr=%q", clusterName, kubeRoute.TargetNode, kubeRoute.DestinationCIDR)
	return nil
}
Example #19
0
func (s *storageSuite) accountKeysSender() *azuretesting.MockSender {
	keys := []armstorage.AccountKey{{
		KeyName:     to.StringPtr(fakeStorageAccountKey + "-name"),
		Value:       to.StringPtr(fakeStorageAccountKey),
		Permissions: armstorage.FULL,
	}, {
		KeyName:     to.StringPtr("key2-name"),
		Value:       to.StringPtr("key2"),
		Permissions: armstorage.FULL,
	}}
	result := armstorage.AccountListKeysResult{Keys: &keys}
	keysSender := azuretesting.NewSenderWithValue(&result)
	keysSender.PathPattern = ".*/storageAccounts/.*/listKeys"
	return keysSender
}
Example #20
0
func createAccount(resourceGroup, name string) {
	c, err := helpers.LoadCredentials()
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	ac := storage.NewAccountsClient(c["subscriptionID"])

	spt, err := helpers.NewServicePrincipalTokenFromCredentials(c, azure.PublicCloud.ResourceManagerEndpoint)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}
	ac.Authorizer = spt

	cna, err := ac.CheckNameAvailability(
		storage.AccountCheckNameAvailabilityParameters{
			Name: to.StringPtr(name),
			Type: to.StringPtr("Microsoft.Storage/storageAccounts")})
	if err != nil {
		log.Fatalf("Error: %v", err)
		return
	}
	if !to.Bool(cna.NameAvailable) {
		fmt.Printf("%s is unavailable -- try again\n", name)
		return
	}
	fmt.Printf("%s is available\n\n", name)

	cp := storage.AccountCreateParameters{}
	cp.Location = to.StringPtr("westus")
	cp.Properties = &storage.AccountPropertiesCreateParameters{AccountType: storage.StandardLRS}

	cancel := make(chan struct{})
	_, err = ac.Create(resourceGroup, name, cp, cancel)
	if err != nil {
		fmt.Printf("Create failed: %v\n", err)
		return
	}

	fmt.Printf("Successfully created %s.%s\n\n", resourceGroup, name)

	r, err := ac.Delete(resourceGroup, name)
	if err != nil {
		fmt.Printf("Delete of %s.%s failed with status %s\n...%v\n", resourceGroup, name, r.Status, err)
		return
	}
	fmt.Printf("Deletion of %s.%s succeeded -- %s\n", resourceGroup, name, r.Status)
}
func Test(t *testing.T) {
	configStr := `
    {
        "aadClientId": "foo",
        "aadClientSecret": "bar"
    }`
	result := containerregistry.RegistryListResult{
		Value: &[]containerregistry.Registry{
			{
				Name: to.StringPtr("foo"),
			},
			{
				Name: to.StringPtr("bar"),
			},
			{
				Name: to.StringPtr("baz"),
			},
		},
	}
	fakeClient := &fakeClient{
		results: result,
	}

	provider := &acrProvider{
		registryClient: fakeClient,
	}
	provider.loadConfig([]byte(configStr))

	creds := provider.Provide()

	if len(creds) != len(*result.Value) {
		t.Errorf("Unexpected list: %v, expected length %d", creds, len(*result.Value))
	}
	for _, cred := range creds {
		if cred.Username != "foo" {
			t.Errorf("expected 'foo' for username, saw: %v", cred.Username)
		}
		if cred.Password != "bar" {
			t.Errorf("expected 'bar' for password, saw: %v", cred.Username)
		}
	}
	for _, val := range *result.Value {
		registryName := *val.Name + ".azurecr.io"
		if _, found := creds[registryName]; !found {
			t.Errorf("Missing expected registry: %s", registryName)
		}
	}
}
Example #22
0
func (a AzureClient) CreateVirtualNetworkIfNotExists(resourceGroup, name, location string) error {
	f := logutil.Fields{
		"name":     name,
		"location": location}

	log.Info("Querying if virtual network already exists.", f)

	if exists, err := a.virtualNetworkExists(resourceGroup, name); err != nil {
		return err
	} else if exists {
		log.Info("Virtual network already exists.", f)
		return nil
	}

	log.Debug("Creating virtual network.", f)
	_, err := a.virtualNetworksClient().CreateOrUpdate(resourceGroup, name,
		network.VirtualNetwork{
			Location: to.StringPtr(location),
			Properties: &network.VirtualNetworkPropertiesFormat{
				AddressSpace: &network.AddressSpace{
					AddressPrefixes: to.StringSlicePtr(defaultVnetAddressPrefixes),
				},
			},
		}, nil)
	return err
}
Example #23
0
func (s *environSuite) TestBootstrap(c *gc.C) {
	defer envtesting.DisableFinishBootstrap()()

	ctx := envtesting.BootstrapContext(c)
	env := prepareForBootstrap(c, ctx, s.provider, &s.sender)

	s.sender = s.initResourceGroupSenders()
	s.sender = append(s.sender, s.startInstanceSenders(true)...)
	s.requests = nil
	result, err := env.Bootstrap(
		ctx, environs.BootstrapParams{
			ControllerConfig: testing.FakeControllerConfig(),
			AvailableTools:   makeToolsList("quantal"),
			BootstrapSeries:  "quantal",
		},
	)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(result.Arch, gc.Equals, "amd64")
	c.Assert(result.Series, gc.Equals, "quantal")

	c.Assert(len(s.requests), gc.Equals, numExpectedStartInstanceRequests+1)
	s.vmTags[tags.JujuIsController] = to.StringPtr("true")
	s.assertStartInstanceRequests(c, s.requests[1:], assertStartInstanceRequestsParams{
		availabilitySetName: "juju-controller",
		imageReference:      &quantalImageReference,
		diskSizeGB:          32,
		osProfile:           &linuxOsProfile,
	})
}
Example #24
0
func (s *TemplateBuilder) SetMarketPlaceImage(publisher, offer, sku, version string) error {
	resource, err := s.getResourceByType(resourceVirtualMachine)
	if err != nil {
		return err
	}

	profile := resource.Properties.StorageProfile
	profile.ImageReference = &compute.ImageReference{
		Publisher: to.StringPtr(publisher),
		Offer:     to.StringPtr(offer),
		Sku:       to.StringPtr(sku),
		Version:   to.StringPtr(version),
	}

	return nil
}
Example #25
0
func (a AzureClient) createStorageAccount(resourceGroup, location string, storageType storage.SkuName) (*storage.AccountProperties, error) {
	name := randomAzureStorageAccountName() // if it's not random enough, then you're unlucky

	f := logutil.Fields{
		"name":     name,
		"location": location,
		"sku":      storageType,
	}

	log.Info("Creating storage account.", f)
	_, err := a.storageAccountsClient().Create(resourceGroup, name,
		storage.AccountCreateParameters{
			Location: to.StringPtr(location),
			Sku:      &storage.Sku{Name: storageType},
		}, nil)
	if err != nil {
		return nil, err
	}

	s, err := a.storageAccountsClient().GetProperties(resourceGroup, name)
	if err != nil {
		return nil, err
	}
	return s.Properties, nil
}
Example #26
0
func makeDeployment(name string) resources.DeploymentExtended {
	dependsOn := []resources.BasicDependency{{
		ResourceType: to.StringPtr("Microsoft.Compute/availabilitySets"),
		ResourceName: to.StringPtr("mysql"),
	}}
	dependencies := []resources.Dependency{{
		ResourceType: to.StringPtr("Microsoft.Compute/virtualMachines"),
		DependsOn:    &dependsOn,
	}}
	return resources.DeploymentExtended{
		Name: to.StringPtr(name),
		Properties: &resources.DeploymentPropertiesExtended{
			ProvisioningState: to.StringPtr("Succeeded"),
			Dependencies:      &dependencies,
		},
	}
}
Example #27
0
func (s *TemplateBuilder) ToJSON() (*string, error) {
	bs, err := json.MarshalIndent(s.template, jsonPrefix, jsonIndent)

	if err != nil {
		return nil, err
	}
	return to.StringPtr(string(bs)), err
}
Example #28
0
func (s *storageSuite) accountSender() *azuretesting.MockSender {
	envTags := map[string]*string{
		"juju-model-uuid": to.StringPtr(testing.ModelTag.Id()),
	}
	account := armstorage.Account{
		Name: to.StringPtr(storageAccountName),
		Type: to.StringPtr("Standard_LRS"),
		Tags: &envTags,
		Properties: &armstorage.AccountProperties{
			PrimaryEndpoints: &armstorage.Endpoints{
				Blob: to.StringPtr(fmt.Sprintf("https://%s.blob.storage.azurestack.local/", storageAccountName)),
			},
		},
	}
	accountSender := azuretesting.NewSenderWithValue(account)
	accountSender.PathPattern = ".*/storageAccounts/" + storageAccountName + ".*"
	return accountSender
}
Example #29
0
func makeIPConfiguration(privateIPAddress string) network.InterfaceIPConfiguration {
	ipConfiguration := network.InterfaceIPConfiguration{
		Properties: &network.InterfaceIPConfigurationPropertiesFormat{},
	}
	if privateIPAddress != "" {
		ipConfiguration.Properties.PrivateIPAddress = to.StringPtr(privateIPAddress)
	}
	return ipConfiguration
}
Example #30
0
func (s *environSuite) TestDestroyControllerErrors(c *gc.C) {
	groups := []resources.ResourceGroup{
		{Name: to.StringPtr("group1")},
		{Name: to.StringPtr("group2")},
	}
	result := resources.ResourceGroupListResult{Value: &groups}

	makeErrorSender := func(err string) *azuretesting.MockSender {
		errorSender := &azuretesting.MockSender{
			Sender:      mocks.NewSender(),
			PathPattern: ".*/resourcegroups/group[12].*",
		}
		errorSender.SetError(errors.New(err))
		return errorSender
	}

	env := s.openEnviron(c)
	s.requests = nil
	s.sender = azuretesting.Senders{
		s.makeSender(".*/resourcegroups", result), // GET
		makeErrorSender("foo"),                    // DELETE
		makeErrorSender("bar"),                    // DELETE
	}
	destroyErr := env.DestroyController(s.controllerUUID)
	// checked below, once we know the order of deletions.

	c.Assert(s.requests, gc.HasLen, 3)
	c.Assert(s.requests[0].Method, gc.Equals, "GET")
	c.Assert(s.requests[1].Method, gc.Equals, "DELETE")
	c.Assert(s.requests[2].Method, gc.Equals, "DELETE")

	// Groups are deleted concurrently, so there's no known order.
	groupsDeleted := []string{
		path.Base(s.requests[1].URL.Path),
		path.Base(s.requests[2].URL.Path),
	}
	c.Assert(groupsDeleted, jc.SameContents, []string{"group1", "group2"})

	c.Check(destroyErr, gc.ErrorMatches,
		`deleting resource group "group1":.*; `+
			`deleting resource group "group2":.*`)
	c.Check(destroyErr, gc.ErrorMatches, ".*foo.*")
	c.Check(destroyErr, gc.ErrorMatches, ".*bar.*")
}