Search in sources :

Example 46 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-tools-for-java by Microsoft.

the class WebAppUtils method createAppService.

public static WebApp createAppService(IProgressIndicator progressIndicator, CreateAppServiceModel model) throws IOException, WebAppException, InterruptedException, AzureCmdException {
    AzureManager azureManager = AuthMethodManager.getInstance().getAzureManager();
    // not signed in
    if (azureManager == null) {
        return null;
    }
    Azure azure = azureManager.getAzure(model.subscriptionDetail.getSubscriptionId());
    AppServicePlan appServicePlan = null;
    if (model.isAppServicePlanCreateNew) {
        AppServicePlan.DefinitionStages.WithGroup ds1 = azure.appServices().appServicePlans().define(model.appServicePlanNameCreateNew).withRegion(model.appServicePlanLocationCreateNew.name());
        AppServicePlan.DefinitionStages.WithPricingTier ds2;
        if (model.isResourceGroupCreateNew) {
            ds2 = ds1.withNewResourceGroup(model.resourceGroupNameCreateNew);
        } else {
            ds2 = ds1.withExistingResourceGroup(model.resourceGroup);
        }
        appServicePlan = ds2.withPricingTier(model.appServicePricingTierCreateNew).withOperatingSystem(OperatingSystem.WINDOWS).create();
    } else {
        appServicePlan = model.appServicePlan;
    }
    WebApp.DefinitionStages.Blank definitionStages = azure.webApps().define(model.webAppName);
    WebAppBase.DefinitionStages.WithCreate<WebApp> withCreate;
    WebApp.DefinitionStages.ExistingWindowsPlanWithGroup ds1 = definitionStages.withExistingWindowsPlan(appServicePlan);
    if (model.isResourceGroupCreateNew) {
        withCreate = ds1.withNewResourceGroup(model.resourceGroupNameCreateNew);
    } else {
        withCreate = ds1.withExistingResourceGroup(model.resourceGroup);
    }
    if (model.jdkDownloadUrl == null) {
        // no custom jdk
        withCreate = withCreate.withJavaVersion(JavaVersion.JAVA_8_NEWEST).withWebContainer(model.webContainer);
    }
    WebApp myWebApp = withCreate.create();
    if (model.jdkDownloadUrl != null) {
        progressIndicator.setText("Deploying custom jdk...");
        WebAppUtils.deployCustomJdk(myWebApp, model.jdkDownloadUrl, model.webContainer, progressIndicator);
    }
    // update cache
    if (model.isResourceGroupCreateNew) {
        ResourceGroup rg = azure.resourceGroups().getByName(model.resourceGroupNameCreateNew);
        if (rg == null) {
            throw new AzureCmdException(String.format("azure.resourceGroups().getByName(%s) returned null"), model.resourceGroupNameCreateNew);
        }
        AzureModelController.addNewResourceGroup(model.subscriptionDetail, rg);
        AzureModelController.addNewWebAppToJustCreatedResourceGroup(rg, myWebApp);
        if (model.isAppServicePlanCreateNew) {
            AzureModelController.addNewAppServicePlanToJustCreatedResourceGroup(rg, appServicePlan);
        } else {
            // add empty list
            AzureModelController.addNewAppServicePlanToJustCreatedResourceGroup(rg, null);
        }
    } else {
        ResourceGroup rg = model.resourceGroup;
        AzureModelController.addNewWebAppToExistingResourceGroup(rg, myWebApp);
        if (model.isAppServicePlanCreateNew) {
            //AppServicePlan asp = azure.appServices().appServicePlans().getById(myWebApp.appServicePlanId());
            AzureModelController.addNewAppServicePlanToExistingResourceGroup(rg, appServicePlan);
        }
    }
    return myWebApp;
}
Also used : Azure(com.microsoft.azure.management.Azure) AzureManager(com.microsoft.azuretools.sdkmanage.AzureManager) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup)

Example 47 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-sdk-for-java by Azure.

the class ManageDns method runSample.

/**
     * Main function which runs the actual sample.
     * @param azure instance of the azure client
     * @return true if sample runs successfully
     */
public static boolean runSample(Azure azure) {
    final String customDomainName = "THE CUSTOM DOMAIN THAT YOU OWN (e.g. contoso.com)";
    final String rgName = SdkContext.randomResourceName("rgNEMV_", 24);
    final String appServicePlanName = SdkContext.randomResourceName("jplan1_", 15);
    final String webAppName = SdkContext.randomResourceName("webapp1-", 20);
    try {
        ResourceGroup resourceGroup = azure.resourceGroups().define(rgName).withRegion(Region.US_EAST2).create();
        //============================================================
        // Creates root DNS Zone
        System.out.println("Creating root DNS zone " + customDomainName + "...");
        DnsZone rootDnsZone = azure.dnsZones().define(customDomainName).withExistingResourceGroup(resourceGroup).create();
        System.out.println("Created root DNS zone " + rootDnsZone.name());
        Utils.print(rootDnsZone);
        //============================================================
        // Sets NS records in the parent zone (hosting custom domain) to make Azure DNS the authoritative
        // source for name resolution for the zone
        System.out.println("Go to your registrar portal and configure your domain " + customDomainName + " with following name server addresses");
        for (String nameServer : rootDnsZone.nameServers()) {
            System.out.println(" " + nameServer);
        }
        System.out.println("Press a key after finishing above step");
        System.in.read();
        //============================================================
        // Creates a web App
        System.out.println("Creating Web App " + webAppName + "...");
        WebApp webApp = azure.webApps().define(webAppName).withRegion(Region.US_EAST2).withExistingResourceGroup(rgName).withNewWindowsPlan(PricingTier.BASIC_B1).defineSourceControl().withPublicGitRepository("https://github.com/jianghaolu/azure-site-test").withBranch("master").attach().create();
        System.out.println("Created web app " + webAppName);
        Utils.print(webApp);
        //============================================================
        // Creates a CName record and bind it with the web app
        // Step 1: Adds CName Dns record to root DNS zone that specify web app host domain as an
        // alias for www.[customDomainName]
        System.out.println("Updating DNS zone by adding a CName record...");
        rootDnsZone = rootDnsZone.update().withCNameRecordSet("www", webApp.defaultHostName()).apply();
        System.out.println("DNS zone updated");
        Utils.print(rootDnsZone);
        // Waiting for a minute for DNS CName entry to propagate
        System.out.println("Waiting a minute for CName record entry to propagate...");
        Thread.sleep(60 * 1000);
        // Step 2: Adds a web app host name binding for www.[customDomainName]
        //         This binding action will fail if the CName record propagation is not yet completed
        System.out.println("Updating Web app with host name binding...");
        webApp.update().defineHostnameBinding().withThirdPartyDomain(customDomainName).withSubDomain("www").withDnsRecordType(CustomHostNameDnsRecordType.CNAME).attach().apply();
        System.out.println("Web app updated");
        Utils.print(webApp);
        //============================================================
        // Creates a virtual machine with public IP
        System.out.println("Creating a virtual machine with public IP...");
        VirtualMachine virtualMachine1 = azure.virtualMachines().define(SdkContext.randomResourceName("employeesvm-", 20)).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(SdkContext.randomResourceName("empip-", 20)).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername("testuser").withAdminPassword("12NewPA$$w0rd!").withSize(VirtualMachineSizeTypes.STANDARD_D1_V2).create();
        System.out.println("Virtual machine created");
        //============================================================
        // Update DNS zone by adding a A record in root DNS zone pointing to virtual machine IPv4 address
        PublicIPAddress vm1PublicIPAddress = virtualMachine1.getPrimaryPublicIPAddress();
        System.out.println("Updating root DNS zone " + customDomainName + "...");
        rootDnsZone = rootDnsZone.update().defineARecordSet("employees").withIPv4Address(vm1PublicIPAddress.ipAddress()).attach().apply();
        System.out.println("Updated root DNS zone " + rootDnsZone.name());
        Utils.print(rootDnsZone);
        // Prints the CName and A Records in the root DNS zone
        //
        System.out.println("Getting CName record set in the root DNS zone " + customDomainName + "...");
        PagedList<CNameRecordSet> cnameRecordSets = rootDnsZone.cNameRecordSets().list();
        for (CNameRecordSet cnameRecordSet : cnameRecordSets) {
            System.out.println("Name: " + cnameRecordSet.name() + " Canonical Name: " + cnameRecordSet.canonicalName());
        }
        System.out.println("Getting ARecord record set in the root DNS zone " + customDomainName + "...");
        PagedList<ARecordSet> aRecordSets = rootDnsZone.aRecordSets().list();
        for (ARecordSet aRecordSet : aRecordSets) {
            System.out.println("Name: " + aRecordSet.name());
            for (String ipv4Address : aRecordSet.ipv4Addresses()) {
                System.out.println("  " + ipv4Address);
            }
        }
        //============================================================
        // Creates a child DNS zone
        String partnerSubDomainName = "partners." + customDomainName;
        System.out.println("Creating child DNS zone " + partnerSubDomainName + "...");
        DnsZone partnersDnsZone = azure.dnsZones().define(partnerSubDomainName).withExistingResourceGroup(resourceGroup).create();
        System.out.println("Created child DNS zone " + partnersDnsZone.name());
        Utils.print(partnersDnsZone);
        //============================================================
        // Adds NS records in the root dns zone to delegate partners.[customDomainName] to child dns zone
        System.out.println("Updating root DNS zone " + rootDnsZone + "...");
        DnsRecordSet.UpdateDefinitionStages.WithNSRecordNameServerOrAttachable<DnsZone.Update> nsRecordStage = rootDnsZone.update().defineNSRecordSet("partners").withNameServer(partnersDnsZone.nameServers().get(0));
        for (int i = 1; i < partnersDnsZone.nameServers().size(); i++) {
            nsRecordStage = nsRecordStage.withNameServer(partnersDnsZone.nameServers().get(i));
        }
        nsRecordStage.attach().apply();
        System.out.println("Root DNS zone updated");
        Utils.print(rootDnsZone);
        //============================================================
        // Creates a virtual machine with public IP
        System.out.println("Creating a virtual machine with public IP...");
        VirtualMachine virtualMachine2 = azure.virtualMachines().define(SdkContext.randomResourceName("partnersvm-", 20)).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(SdkContext.randomResourceName("ptnerpip-", 20)).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername("testuser").withAdminPassword("12NewPA$$w0rd!").withSize(VirtualMachineSizeTypes.STANDARD_D1_V2).create();
        System.out.println("Virtual machine created");
        //============================================================
        // Update child DNS zone by adding a A record pointing to virtual machine IPv4 address
        PublicIPAddress vm2PublicIPAddress = virtualMachine2.getPrimaryPublicIPAddress();
        System.out.println("Updating child DNS zone " + partnerSubDomainName + "...");
        partnersDnsZone = partnersDnsZone.update().defineARecordSet("@").withIPv4Address(vm2PublicIPAddress.ipAddress()).attach().apply();
        System.out.println("Updated child DNS zone " + partnersDnsZone.name());
        Utils.print(partnersDnsZone);
        //============================================================
        // Removes A record entry from the root DNS zone
        System.out.println("Removing A Record from root DNS zone " + rootDnsZone.name() + "...");
        rootDnsZone = rootDnsZone.update().withoutARecordSet("employees").apply();
        System.out.println("Removed A Record from root DNS zone");
        Utils.print(rootDnsZone);
        //============================================================
        // Deletes the DNS zone
        System.out.println("Deleting child DNS zone " + partnersDnsZone.name() + "...");
        azure.dnsZones().deleteById(partnersDnsZone.id());
        System.out.println("Deleted child DNS zone " + partnersDnsZone.name());
        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().beginDeleteByName(rgName);
            System.out.println("Deleted Resource Group: " + rgName);
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}
Also used : ARecordSet(com.microsoft.azure.management.dns.ARecordSet) CNameRecordSet(com.microsoft.azure.management.dns.CNameRecordSet) PublicIPAddress(com.microsoft.azure.management.network.PublicIPAddress) DnsZone(com.microsoft.azure.management.dns.DnsZone) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) WebApp(com.microsoft.azure.management.appservice.WebApp) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 48 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-sdk-for-java by Azure.

the class ManageVirtualMachinesInParallel method runSample.

/**
     * Main function which runs the actual sample.
     * @param azure instance of the azure client
     * @return true if sample runs successfully
     */
public static boolean runSample(Azure azure) {
    final int vmCount = 10;
    final Region region = Region.US_EAST;
    final String rgName = SdkContext.randomResourceName("rgCOPP", 24);
    final String networkName = SdkContext.randomResourceName("vnetCOMV", 24);
    final String storageAccountName = SdkContext.randomResourceName("stgCOMV", 20);
    final String userName = "tirekicker";
    final String password = "12NewPA$$w0rd!";
    try {
        // Create a resource group [Where all resources gets created]
        ResourceGroup resourceGroup = azure.resourceGroups().define(rgName).withRegion(region).create();
        // Prepare Creatable Network definition [Where all the virtual machines get added to]
        Creatable<Network> creatableNetwork = azure.networks().define(networkName).withRegion(region).withExistingResourceGroup(resourceGroup).withAddressSpace("172.16.0.0/16");
        // Prepare Creatable Storage account definition [For storing VMs disk]
        Creatable<StorageAccount> creatableStorageAccount = azure.storageAccounts().define(storageAccountName).withRegion(region).withExistingResourceGroup(resourceGroup);
        // Prepare a batch of Creatable Virtual Machines definitions
        List<Creatable<VirtualMachine>> creatableVirtualMachines = new ArrayList<>();
        for (int i = 0; i < vmCount; i++) {
            Creatable<VirtualMachine> creatableVirtualMachine = azure.virtualMachines().define("VM-" + i).withRegion(region).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork(creatableNetwork).withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2).withNewStorageAccount(creatableStorageAccount);
            creatableVirtualMachines.add(creatableVirtualMachine);
        }
        StopWatch stopwatch = new StopWatch();
        System.out.println("Creating the virtual machines");
        stopwatch.start();
        Collection<VirtualMachine> virtualMachines = azure.virtualMachines().create(creatableVirtualMachines).values();
        stopwatch.stop();
        System.out.println("Created virtual machines");
        for (VirtualMachine virtualMachine : virtualMachines) {
            System.out.println(virtualMachine.id());
        }
        System.out.println("Virtual Machines create: (took " + (stopwatch.getTime() / 1000) + " seconds) ");
        return true;
    } catch (Exception f) {
        System.out.println(f.getMessage());
        f.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().beginDeleteByName(rgName);
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}
Also used : ArrayList(java.util.ArrayList) StopWatch(org.apache.commons.lang3.time.StopWatch) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) Network(com.microsoft.azure.management.network.Network) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) Creatable(com.microsoft.azure.management.resources.fluentcore.model.Creatable) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 49 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-tools-for-java by Microsoft.

the class CreateArmStorageAccountForm method okPressed.

@Override
protected void okPressed() {
    if (nameTextField.getText().length() < 3 || nameTextField.getText().length() > 24 || !nameTextField.getText().matches("[a-z0-9]+")) {
        DefaultLoader.getUIHelper().showError("Invalid storage account name. The name should be between 3 and 24 characters long and " + "can contain only lowercase letters and numbers.", "Azure Explorer");
        return;
    }
    final boolean isNewResourceGroup = createNewRadioButton.getSelection();
    final String resourceGroupName = isNewResourceGroup ? resourceGrpField.getText() : resourceGrpCombo.getText();
    String replication = replicationComboBox.getData(replicationComboBox.getText()).toString();
    String region = ((Location) regionComboBox.getData(regionComboBox.getText())).name();
    Kind kind = (Kind) kindCombo.getData(kindCombo.getText());
    if (subscription == null) {
        String name = nameTextField.getText();
        AccessTier accessTier = (AccessTier) accessTierComboBox.getData(accessTierComboBox.getText());
        SubscriptionDetail subscriptionDetail = (SubscriptionDetail) subscriptionComboBox.getData(subscriptionComboBox.getText());
        setSubscription(subscriptionDetail);
        DefaultLoader.getIdeHelper().runInBackground(null, "Creating storage account", false, true, "Creating storage account " + name + "...", new Runnable() {

            @Override
            public void run() {
                try {
                    AzureSDKManager.createStorageAccount(subscriptionDetail.getSubscriptionId(), name, region, isNewResourceGroup, resourceGroupName, kind, accessTier, false, replication);
                    // update resource groups cache if new resource group was created when creating storage account
                    if (isNewResourceGroup) {
                        AzureManager azureManager = AuthMethodManager.getInstance().getAzureManager();
                        if (azureManager != null) {
                            ResourceGroup rg = azureManager.getAzure(subscriptionDetail.getSubscriptionId()).resourceGroups().getByName(resourceGroupName);
                            AzureModelController.addNewResourceGroup(subscriptionDetail, rg);
                        }
                    }
                    if (onCreate != null) {
                        onCreate.run();
                    }
                } catch (Exception e) {
                    DefaultLoader.getIdeHelper().invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            PluginUtil.displayErrorDialog(PluginUtil.getParentShell(), Messages.err, "An error occurred while creating the storage account: " + e.getMessage());
                        }
                    });
                }
            }
        });
    } else {
        //creating from 'create vm'
        newStorageAccount = new com.microsoft.tooling.msservices.model.storage.StorageAccount(nameTextField.getText(), subscription.getSubscriptionId());
        newStorageAccount.setResourceGroupName(resourceGroupName);
        newStorageAccount.setNewResourceGroup(isNewResourceGroup);
        newStorageAccount.setType(replication);
        newStorageAccount.setLocation(region);
        newStorageAccount.setKind(kind);
        if (onCreate != null) {
            onCreate.run();
        }
    }
    super.okPressed();
}
Also used : AzureManager(com.microsoft.azuretools.sdkmanage.AzureManager) AccessTier(com.microsoft.azure.management.storage.AccessTier) InvocationTargetException(java.lang.reflect.InvocationTargetException) Kind(com.microsoft.azure.management.storage.Kind) SubscriptionDetail(com.microsoft.azuretools.authmanage.models.SubscriptionDetail) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Location(com.microsoft.azure.management.resources.Location)

Example 50 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-tools-for-java by Microsoft.

the class CreateRedisCacheForm method fillLocationsAndResourceGrps.

private void fillLocationsAndResourceGrps(SubscriptionDetail selectedSub) {
    cbLocations.removeAll();
    List<Location> locations = AzureModel.getInstance().getSubscriptionToLocationMap().get(selectedSub);
    if (locations != null) {
        sortedLocations = locations.stream().sorted(Comparator.comparing(Location::displayName)).collect(Collectors.toList());
        for (Location location : sortedLocations) {
            cbLocations.add(location.displayName());
        }
        if (sortedLocations.size() > 0) {
            cbLocations.select(0);
            selectedLocationValue = sortedLocations.get(0).name();
        }
    }
    cbUseExisting.removeAll();
    List<ResourceGroup> groups = AzureModel.getInstance().getSubscriptionToResourceGroupMap().get(selectedSub);
    if (groups != null) {
        sortedGroups = groups.stream().map(ResourceGroup::name).sorted().collect(Collectors.toList());
        for (String group : sortedGroups) {
            cbUseExisting.add(group);
        }
        if (sortedGroups.size() > 0) {
            cbUseExisting.select(0);
            if (rdoUseExisting.getSelection()) {
                newResGrp = false;
                selectedResGrpValue = sortedGroups.get(0);
            }
        }
    }
}
Also used : ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Location(com.microsoft.azure.management.resources.Location)

Aggregations

ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)53 Test (org.junit.Test)22 Region (com.microsoft.azure.management.resources.fluentcore.arm.Region)13 SubscriptionDetail (com.microsoft.azuretools.authmanage.models.SubscriptionDetail)12 ArrayList (java.util.ArrayList)10 Network (com.microsoft.azure.management.network.Network)9 StorageAccount (com.microsoft.azure.management.storage.StorageAccount)9 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)8 Creatable (com.microsoft.azure.management.resources.fluentcore.model.Creatable)7 AzureManager (com.microsoft.azuretools.sdkmanage.AzureManager)7 Azure (com.microsoft.azure.management.Azure)6 AppServicePlan (com.microsoft.azure.management.appservice.AppServicePlan)6 WebApp (com.microsoft.azure.management.appservice.WebApp)6 HashMap (java.util.HashMap)5 StopWatch (org.apache.commons.lang3.time.StopWatch)5 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)4 Location (com.microsoft.azure.management.resources.Location)4 CloudException (com.microsoft.azure.CloudException)3 Period (org.joda.time.Period)3 ApplicationGateway (com.microsoft.azure.management.network.ApplicationGateway)2