use of com.microsoft.azure.management.network.PublicIPAddress in project azure-sdk-for-java by Azure.
the class ManageApplicationGateway 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 rgName = SdkContext.randomResourceName("rgNEAG", 15);
final String pipName = SdkContext.randomResourceName("pip" + "-", 18);
final String userName = "tirekicker";
final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com";
int backendPools = 2;
int vmCountInAPool = 4;
Region[] regions = { Region.US_EAST, Region.UK_WEST };
String[] addressSpaces = { "172.16.0.0/16", "172.17.0.0/16" };
String[][] publicIpCreatableKeys = new String[backendPools][vmCountInAPool];
String[][] ipAddresses = new String[backendPools][vmCountInAPool];
try {
//=============================================================
// Create a resource group (Where all resources gets created)
//
ResourceGroup resourceGroup = azure.resourceGroups().define(rgName).withRegion(Region.US_EAST).create();
System.out.println("Created a new resource group - " + resourceGroup.id());
//=============================================================
// Create a public IP address for the Application Gateway
System.out.println("Creating a public IP address for the application gateway ...");
PublicIPAddress publicIPAddress = azure.publicIPAddresses().define(pipName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).create();
System.out.println("Created a public IP address");
// Print the virtual network details
Utils.print(publicIPAddress);
//=============================================================
// Create backend pools
// Prepare a batch of Creatable definitions
List<Creatable<VirtualMachine>> creatableVirtualMachines = new ArrayList<>();
for (int i = 0; i < backendPools; i++) {
//=============================================================
// Create 1 network creatable per region
// Prepare Creatable Network definition (Where all the virtual machines get added to)
String networkName = SdkContext.randomResourceName("vnetNEAG-", 20);
Creatable<Network> networkCreatable = azure.networks().define(networkName).withRegion(regions[i]).withExistingResourceGroup(resourceGroup).withAddressSpace(addressSpaces[i]);
//=============================================================
// Create 1 storage creatable per region (For storing VMs disk)
String storageAccountName = SdkContext.randomResourceName("stgneag", 20);
Creatable<StorageAccount> storageAccountCreatable = azure.storageAccounts().define(storageAccountName).withRegion(regions[i]).withExistingResourceGroup(resourceGroup);
String linuxVMNamePrefix = SdkContext.randomResourceName("vm-", 15);
for (int j = 0; j < vmCountInAPool; j++) {
//=============================================================
// Create 1 public IP address creatable
Creatable<PublicIPAddress> publicIPAddressCreatable = azure.publicIPAddresses().define(String.format("%s-%d", linuxVMNamePrefix, j)).withRegion(regions[i]).withExistingResourceGroup(resourceGroup).withLeafDomainLabel(String.format("%s-%d", linuxVMNamePrefix, j));
publicIpCreatableKeys[i][j] = publicIPAddressCreatable.key();
//=============================================================
// Create 1 virtual machine creatable
Creatable<VirtualMachine> virtualMachineCreatable = azure.virtualMachines().define(String.format("%s-%d", linuxVMNamePrefix, j)).withRegion(regions[i]).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork(networkCreatable).withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressCreatable).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2).withNewStorageAccount(storageAccountCreatable);
creatableVirtualMachines.add(virtualMachineCreatable);
}
}
//=============================================================
// Create two backend pools of virtual machines
StopWatch stopwatch = new StopWatch();
System.out.println("Creating virtual machines (two backend pools)");
stopwatch.start();
CreatedResources<VirtualMachine> virtualMachines = azure.virtualMachines().create(creatableVirtualMachines);
stopwatch.stop();
System.out.println("Created virtual machines (two backend pools)");
for (VirtualMachine virtualMachine : virtualMachines.values()) {
System.out.println(virtualMachine.id());
}
System.out.println("Virtual machines created: (took " + (stopwatch.getTime() / 1000) + " seconds) to create == " + virtualMachines.size() + " == virtual machines (4 virtual machines per backend pool)");
//=======================================================================
// Get IP addresses from created resources
System.out.println("IP Addresses in the backend pools are - ");
for (int i = 0; i < backendPools; i++) {
for (int j = 0; j < vmCountInAPool; j++) {
PublicIPAddress pip = (PublicIPAddress) virtualMachines.createdRelatedResource(publicIpCreatableKeys[i][j]);
pip.refresh();
ipAddresses[i][j] = pip.ipAddress();
System.out.println(String.format("[backend pool = %d][vm = %d] = %s", i, j, ipAddresses[i][j]));
}
System.out.println("======");
}
//=======================================================================
// Create an application gateway
System.out.println("================= CREATE ======================");
System.out.println("Creating an application gateway");
stopwatch.reset();
stopwatch.start();
final String sslCertificatePfxPath = ManageApplicationGateway.class.getClassLoader().getResource("myTest._pfx").getPath();
final String sslCertificatePfxPath2 = ManageApplicationGateway.class.getClassLoader().getResource("myTest2._pfx").getPath();
ApplicationGateway applicationGateway = azure.applicationGateways().define("myFirstAppGateway").withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).defineRequestRoutingRule("HTTP-80-to-8080").fromPublicFrontend().fromFrontendHttpPort(80).toBackendHttpPort(8080).toBackendIPAddress(ipAddresses[0][0]).toBackendIPAddress(ipAddresses[0][1]).toBackendIPAddress(ipAddresses[0][2]).toBackendIPAddress(ipAddresses[0][3]).attach().defineRequestRoutingRule("HTTPs-443-to-8080").fromPublicFrontend().fromFrontendHttpsPort(443).withSslCertificateFromPfxFile(new File(sslCertificatePfxPath)).withSslCertificatePassword("Abc123").toBackendHttpPort(8080).toBackendIPAddress(ipAddresses[1][0]).toBackendIPAddress(ipAddresses[1][1]).toBackendIPAddress(ipAddresses[1][2]).toBackendIPAddress(ipAddresses[1][3]).attach().withExistingPublicIPAddress(publicIPAddress).create();
stopwatch.stop();
System.out.println("Application gateway created: (took " + (stopwatch.getTime() / 1000) + " seconds)");
Utils.print(applicationGateway);
//=======================================================================
// Update an application gateway
// configure the first routing rule for SSL offload
System.out.println("================= UPDATE ======================");
System.out.println("Updating the application gateway");
stopwatch.reset();
stopwatch.start();
applicationGateway.update().withoutRequestRoutingRule("HTTP-80-to-8080").defineRequestRoutingRule("HTTPs-1443-to-8080").fromPublicFrontend().fromFrontendHttpsPort(1443).withSslCertificateFromPfxFile(new File(sslCertificatePfxPath2)).withSslCertificatePassword("Abc123").toBackendHttpPort(8080).toBackendIPAddress(ipAddresses[0][0]).toBackendIPAddress(ipAddresses[0][1]).toBackendIPAddress(ipAddresses[0][2]).toBackendIPAddress(ipAddresses[0][3]).withHostName("www.contoso.com").withCookieBasedAffinity().attach().apply();
stopwatch.stop();
System.out.println("Application gateway updated: (took " + (stopwatch.getTime() / 1000) + " seconds)");
Utils.print(applicationGateway);
return true;
} catch (Exception f) {
System.out.println(f.getMessage());
f.printStackTrace();
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().deleteByName(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;
}
use of com.microsoft.azure.management.network.PublicIPAddress in project cloudbreak by hortonworks.
the class AzureMetadataCollector method collect.
@Override
public List<CloudVmMetaDataStatus> collect(AuthenticatedContext authenticatedContext, List<CloudResource> resources, List<CloudInstance> vms) {
CloudResource resource = azureUtils.getTemplateResource(resources);
List<CloudVmMetaDataStatus> results = new ArrayList<>();
List<InstanceTemplate> templates = Lists.transform(vms, CloudInstance::getTemplate);
String resourceName = resource.getName();
Map<String, InstanceTemplate> templateMap = Maps.uniqueIndex(templates, from -> azureUtils.getPrivateInstanceId(resourceName, from.getGroupName(), Long.toString(from.getPrivateId())));
try {
for (Entry<String, InstanceTemplate> instance : templateMap.entrySet()) {
AzureClient azureClient = authenticatedContext.getParameter(AzureClient.class);
VirtualMachine vm = azureClient.getVirtualMachine(resourceName, instance.getKey());
String subnetId = vm.getPrimaryNetworkInterface().primaryIPConfiguration().subnetName();
String privateIp = null;
String publicIp = null;
Integer faultDomainCount = azureClient.getFaultDomainNumber(resourceName, vm.name());
String platform = authenticatedContext.getCloudContext().getPlatform().value();
String location = authenticatedContext.getCloudContext().getLocation().getRegion().value();
String hostgroupNm = instance.getValue().getGroupName();
StringBuilder localityIndicatorBuilder = new StringBuilder();
localityIndicatorBuilder.append(LOCALITY_SEPARATOR).append(platform).append(LOCALITY_SEPARATOR).append(location).append(LOCALITY_SEPARATOR).append(resourceName).append(LOCALITY_SEPARATOR).append(hostgroupNm).append(LOCALITY_SEPARATOR).append(faultDomainCount);
AzureUtils.removeBlankSpace(localityIndicatorBuilder);
List<String> networkInterfaceIdList = vm.networkInterfaceIds();
for (String networkInterfaceId : networkInterfaceIdList) {
NetworkInterface networkInterface = azureClient.getNetworkInterfaceById(networkInterfaceId);
privateIp = networkInterface.primaryPrivateIP();
PublicIPAddress publicIpAddress = networkInterface.primaryIPConfiguration().getPublicIPAddress();
List<LoadBalancerBackend> backends = networkInterface.primaryIPConfiguration().listAssociatedLoadBalancerBackends();
List<LoadBalancerInboundNatRule> inboundNatRules = networkInterface.primaryIPConfiguration().listAssociatedLoadBalancerInboundNatRules();
if (!backends.isEmpty() || !inboundNatRules.isEmpty()) {
publicIp = azureClient.getLoadBalancerIps(resource.getName(), azureUtils.getLoadBalancerId(resource.getName())).get(0);
}
if (publicIpAddress != null && publicIpAddress.ipAddress() != null) {
publicIp = publicIpAddress.ipAddress();
}
}
String instanceId = instance.getKey();
CloudInstanceMetaData md = new CloudInstanceMetaData(privateIp, publicIp, faultDomainCount == null ? null : localityIndicatorBuilder.toString());
InstanceTemplate template = templateMap.get(instanceId);
if (template != null) {
Map<String, Object> params = new HashMap<>(1);
params.put(CloudInstance.SUBNET_ID, subnetId);
// TODO use shhkey here
CloudInstance cloudInstance = new CloudInstance(instanceId, template, null, params);
CloudVmInstanceStatus status = new CloudVmInstanceStatus(cloudInstance, InstanceStatus.CREATED);
results.add(new CloudVmMetaDataStatus(status, md));
}
}
} catch (RuntimeException e) {
throw new CloudConnectorException(e.getMessage(), e);
}
return results;
}
use of com.microsoft.azure.management.network.PublicIPAddress in project azure-sdk-for-java by Azure.
the class TestVirtualMachineNics method createResource.
@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
// Prepare the resource group definition
final String rgName = "rg" + this.testId;
Creatable<ResourceGroup> resourceGroupCreatable = virtualMachines.manager().resourceManager().resourceGroups().define(rgName).withRegion(Region.US_EAST);
// Prepare the virtual network definition [shared by primary and secondary network interfaces]
final String vnetName = "vnet" + this.testId;
Creatable<Network> networkCreatable = this.networkManager.networks().define(vnetName).withRegion(Region.US_EAST).withNewResourceGroup(resourceGroupCreatable).withAddressSpace("10.0.0.0/28");
// Prepare the secondary network interface definition
final String secondaryNicName = "nic" + this.testId;
Creatable<NetworkInterface> secondaryNetworkInterfaceCreatable = this.networkManager.networkInterfaces().define(secondaryNicName).withRegion(Region.US_EAST).withNewResourceGroup(resourceGroupCreatable).withNewPrimaryNetwork(networkCreatable).withPrimaryPrivateIPAddressStatic("10.0.0.5");
// .withNewPrimaryPublicIPAddress();
// [Secondary NIC cannot have PublicIP - Only primary network interface can reference a public IP address]
// Prepare the secondary network interface definition
final String secondaryNicName2 = "nic2" + this.testId;
Creatable<NetworkInterface> secondaryNetworkInterfaceCreatable2 = this.networkManager.networkInterfaces().define(secondaryNicName2).withRegion(Region.US_EAST).withNewResourceGroup(resourceGroupCreatable).withNewPrimaryNetwork(networkCreatable).withPrimaryPrivateIPAddressStatic("10.0.0.6");
// Create Virtual Machine
final String vmName = "vm" + this.testId;
final String primaryPipName = "pip" + vmName;
VirtualMachine virtualMachine = virtualMachines.define(vmName).withRegion(Region.US_EAST).withNewResourceGroup(resourceGroupCreatable).withNewPrimaryNetwork(networkCreatable).withPrimaryPrivateIPAddressStatic("10.0.0.4").withNewPrimaryPublicIPAddress(primaryPipName).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_14_04_LTS).withRootUsername("testuser").withRootPassword("12NewPA$$w0rd!").withSize(VirtualMachineSizeTypes.STANDARD_A9).withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable).withNewSecondaryNetworkInterface(secondaryNetworkInterfaceCreatable2).create();
Assert.assertTrue(virtualMachine.networkInterfaceIds().size() == 3);
NetworkInterface primaryNetworkInterface = virtualMachine.getPrimaryNetworkInterface();
Assert.assertEquals(primaryNetworkInterface.primaryPrivateIP(), "10.0.0.4");
PublicIPAddress primaryPublicIPAddress = primaryNetworkInterface.primaryIPConfiguration().getPublicIPAddress();
Assert.assertTrue(primaryPublicIPAddress.fqdn().startsWith(primaryPipName));
return virtualMachine;
}
use of com.microsoft.azure.management.network.PublicIPAddress in project azure-sdk-for-java by Azure.
the class TestVirtualMachineSsh method createResource.
@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
final String vmName = "vm" + this.testId;
final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com";
final String publicIpDnsLabel = vmName;
PublicIPAddress pip = pips.define(publicIpDnsLabel).withRegion(Region.US_EAST).withNewResourceGroup().withLeafDomainLabel(publicIpDnsLabel).create();
VirtualMachine vm = virtualMachines.define(vmName).withRegion(pip.regionName()).withExistingResourceGroup(pip.resourceGroupName()).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withExistingPrimaryPublicIPAddress(pip).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_14_04_LTS).withRootUsername("testuser").withRootPassword("12NewPA$$w0rd!").withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
pip.refresh();
Assert.assertTrue(pip.hasAssignedNetworkInterface());
JSch jsch = new JSch();
Session session = null;
if (!MockIntegrationTestBase.IS_MOCKED) {
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
// jsch.addIdentity(sshFile, filePassword);
session = jsch.getSession("testuser", publicIpDnsLabel + "." + "eastus.cloudapp.azure.com", 22);
session.setPassword("12NewPA$$w0rd!");
session.setConfig(config);
session.connect();
} catch (Exception e) {
Assert.fail("SSH connection failed" + e.getMessage());
} finally {
if (session != null) {
session.disconnect();
}
}
Assert.assertNotNull(vm.inner().osProfile().linuxConfiguration().ssh());
Assert.assertTrue(vm.inner().osProfile().linuxConfiguration().ssh().publicKeys().size() > 0);
}
return vm;
}
use of com.microsoft.azure.management.network.PublicIPAddress in project azure-sdk-for-java by Azure.
the class TestVirtualMachineCustomData method createResource.
@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
final String vmName = "vm" + this.testId;
final String publicIpDnsLabel = SdkContext.randomResourceName("abc", 16);
// Prepare the custom data
//
String cloudInitFilePath = getClass().getClassLoader().getResource("cloud-init").getPath();
// In Windows remove leading slash
cloudInitFilePath = cloudInitFilePath.replaceFirst("^/(.:/)", "$1");
byte[] cloudInitAsBytes = Files.readAllBytes(Paths.get(cloudInitFilePath));
byte[] cloudInitEncoded = Base64.encodeBase64(cloudInitAsBytes);
String cloudInitEncodedString = new String(cloudInitEncoded);
PublicIPAddress pip = pips.define(publicIpDnsLabel).withRegion(Region.US_EAST).withNewResourceGroup().withLeafDomainLabel(publicIpDnsLabel).create();
VirtualMachine vm = virtualMachines.define(vmName).withRegion(pip.regionName()).withExistingResourceGroup(pip.resourceGroupName()).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withExistingPrimaryPublicIPAddress(pip).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername("testuser").withRootPassword("12NewPA$$w0rd!").withCustomData(cloudInitEncodedString).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
pip.refresh();
Assert.assertTrue(pip.hasAssignedNetworkInterface());
if (!MockIntegrationTestBase.IS_MOCKED) {
JSch jsch = new JSch();
Session session = null;
ChannelExec channel = null;
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session = jsch.getSession("testuser", publicIpDnsLabel + "." + "eastus.cloudapp.azure.com", 22);
session.setPassword("12NewPA$$w0rd!");
session.setConfig(config);
session.connect();
// Try running the package installed via init script
//
channel = (ChannelExec) session.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
channel.setCommand("pwgen;");
channel.connect();
String msg;
while ((msg = in.readLine()) != null) {
Assert.assertFalse(msg.startsWith("The program 'pwgen' is currently not installed"));
}
} catch (Exception e) {
Assert.fail("SSH connection failed" + e.getMessage());
} finally {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
return vm;
}
Aggregations