com.microsoft.azure.management.network.NetworkSecurityGroup Java Examples

The following examples show how to use com.microsoft.azure.management.network.NetworkSecurityGroup. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NetworkInterfaceImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
protected void beforeCreating() {
    NetworkSecurityGroup networkSecurityGroup = null;
    if (creatableNetworkSecurityGroupKey != null) {
        networkSecurityGroup = this.<NetworkSecurityGroup>taskResult(creatableNetworkSecurityGroupKey);
    } else if (existingNetworkSecurityGroupToAssociate != null) {
        networkSecurityGroup = existingNetworkSecurityGroupToAssociate;
    }

    // Associate an NSG if needed
    if (networkSecurityGroup != null) {
        this.inner().withNetworkSecurityGroup(new NetworkSecurityGroupInner().withId(networkSecurityGroup.id()));
    }

    NicIPConfigurationImpl.ensureConfigurations(this.nicIPConfigurations.values());

    // Reset and update IP configs
    this.inner().withIpConfigurations(innersFromWrappers(this.nicIPConfigurations.values()));
}
 
Example #2
Source File: NicIPConfigurationBaseImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public NetworkSecurityGroup getNetworkSecurityGroup() {
    Network network = this.getNetwork();
    if (network == null) {
        return null;
    }

    String subnetName = this.subnetName();
    if (subnetName == null) {
        return null;
    }

    Subnet subnet = network.subnets().get(subnetName);
    if (subnet == null) {
        return null;
    }

    return subnet.getNetworkSecurityGroup();
}
 
Example #3
Source File: Utils.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Print network security group.
 *
 * @param resource a network security group
 */
public static void print(NetworkSecurityGroup resource) {
    StringBuilder info = new StringBuilder();
    info.append("NSG: ").append(resource.id())
            .append("Name: ").append(resource.name())
            .append("\n\tResource group: ").append(resource.resourceGroupName())
            .append("\n\tRegion: ").append(resource.region())
            .append("\n\tTags: ").append(resource.tags());

    // Output security rules
    for (NetworkSecurityRule rule : resource.securityRules().values()) {
        info.append("\n\tRule: ").append(rule.name())
                .append("\n\t\tAccess: ").append(rule.access())
                .append("\n\t\tDirection: ").append(rule.direction())
                .append("\n\t\tFrom address: ").append(rule.sourceAddressPrefix())
                .append("\n\t\tFrom port range: ").append(rule.sourcePortRange())
                .append("\n\t\tTo address: ").append(rule.destinationAddressPrefix())
                .append("\n\t\tTo port: ").append(rule.destinationPortRange())
                .append("\n\t\tProtocol: ").append(rule.protocol())
                .append("\n\t\tPriority: ").append(rule.priority());
    }

    System.out.println(info.toString());
}
 
Example #4
Source File: AzureTests.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Tests basic generic resources retrieval.
 * @throws Exception
 */
@Test
public void testGenericResources() throws Exception {
    // Create some resources
    NetworkSecurityGroup nsg = azure.networkSecurityGroups().define(SdkContext.randomResourceName("nsg", 13))
        .withRegion(Region.US_EAST)
        .withNewResourceGroup()
        .create();
    azure.publicIPAddresses().define(SdkContext.randomResourceName("pip", 13))
        .withRegion(Region.US_EAST)
        .withExistingResourceGroup(nsg.resourceGroupName())
        .create();

    PagedList<GenericResource> resources = azure.genericResources().listByResourceGroup(nsg.resourceGroupName());
    Assert.assertEquals(2, resources.size());
    GenericResource firstResource = resources.get(0);

    GenericResource resourceById = azure.genericResources().getById(firstResource.id());
    GenericResource resourceByDetails = azure.genericResources().get(
            firstResource.resourceGroupName(),
            firstResource.resourceProviderNamespace(),
            firstResource.resourceType(),
            firstResource.name());
    Assert.assertTrue(resourceById.id().equalsIgnoreCase(resourceByDetails.id()));
    azure.resourceGroups().beginDeleteByName(nsg.resourceGroupName());
}
 
Example #5
Source File: AzurePlatformResources.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public CloudSecurityGroups securityGroups(CloudCredential cloudCredential, Region region, Map<String, String> filters) {
    AzureClient client = azureClientService.getClient(cloudCredential);
    Map<String, Set<CloudSecurityGroup>> result = new HashMap<>();
    PlatformResourceSecurityGroupFilterView filter = new PlatformResourceSecurityGroupFilterView(filters);
    String groupId = filter.getGroupId();
    if (groupId != null) {
        NetworkSecurityGroup networkSecurityGroup = getNetworkSecurityGroup(client, groupId);
        convertAndAddToResult(region, result, networkSecurityGroup);
    } else {
        for (NetworkSecurityGroup securityGroup : client.getSecurityGroups().list()) {
            convertAndAddToResult(region, result, securityGroup);
        }
    }
    if (result.isEmpty() && Objects.nonNull(region)) {
        result.put(region.value(), new HashSet<>());
    }
    return new CloudSecurityGroups(result);
}
 
Example #6
Source File: NSGInventoryCollector.java    From pacbot with Apache License 2.0 6 votes vote down vote up
public List<SecurityGroupVH> fetchNetworkSecurityGroupDetails(SubscriptionVH subscription,
		Map<String, Map<String, String>> tagMap) {
	List<SecurityGroupVH> securityGroupsList = new ArrayList<>();

	Azure azure = azureCredentialProvider.getClient(subscription.getTenant(),subscription.getSubscriptionId());
	PagedList<NetworkSecurityGroup> securityGroups = azure.networkSecurityGroups().list();
	for (NetworkSecurityGroup securityGroup : securityGroups) {
		SecurityGroupVH securityGroupVH = new SecurityGroupVH();
		securityGroupVH.setId(securityGroup.id());
		securityGroupVH.setKey(securityGroup.key());
		securityGroupVH.setName(securityGroup.name());
		securityGroupVH.setRegion(securityGroup.regionName());
		securityGroupVH.setResourceGroupName(securityGroup.resourceGroupName());
		securityGroupVH.setTags(Util.tagsList(tagMap, securityGroup.resourceGroupName(), securityGroup.tags()));
		securityGroupVH.setSubnetList(getNetworkSecuritySubnetDetails(securityGroup.listAssociatedSubnets()));
		securityGroupVH.setNetworkInterfaceIds(securityGroup.networkInterfaceIds());
		securityGroupVH.setSubscription(subscription.getSubscriptionId());
		securityGroupVH.setSubscriptionName(subscription.getSubscriptionName());
		setSecurityRules(securityGroup, securityGroupVH);
		securityGroupsList.add(securityGroupVH);

	}
	log.info("Target Type : {}  Total: {} ","Nsg",securityGroupsList.size());
	return securityGroupsList;
}
 
Example #7
Source File: AzurePlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private NetworkSecurityGroup getNetworkSecurityGroup(AzureClient client, String groupId) {
    try {
        NetworkSecurityGroup networkSecurityGroup = client.getSecurityGroups().getById(groupId);
        if (networkSecurityGroup == null) {
            throw new PermanentlyFailedException("Nothing found on Azure with id: " + groupId);
        }
        return networkSecurityGroup;
    } catch (InvalidParameterException e) {
        throw new PermanentlyFailedException(e.getMessage(), e);
    }
}
 
Example #8
Source File: VirtualMachineScaleSetNetworkInterfaceImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public NetworkSecurityGroup getNetworkSecurityGroup() {
    String nsgId = this.networkSecurityGroupId();
    if (nsgId == null) {
        return null;
    }
    return this.manager()
        .networkSecurityGroups()
        .getByResourceGroup(ResourceUtils.groupFromResourceId(nsgId),
            ResourceUtils.nameFromResourceId(nsgId));
}
 
Example #9
Source File: TestNSG.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public NetworkSecurityGroup updateResource(NetworkSecurityGroup resource) throws Exception {
    resource = resource.update()
            .withoutRule("rule1")
            .withTag("tag1", "value1")
            .withTag("tag2", "value2")
            .defineRule("rule3")
                .allowInbound()
                .fromAnyAddress()
                .fromAnyPort()
                .toAnyAddress()
                .toAnyPort()
                .withProtocol(SecurityRuleProtocol.UDP)
                .attach()
            .withoutRule("rule1")
            .updateRule("rule2")
                .denyInbound()
                .fromAddresses("100.0.0.0/29", "100.1.0.0/29")
                .fromPortRanges("88-90")
                .withPriority(300)
                .withDescription("bar!!!")
                .parent()
            .apply();
    Assert.assertTrue(resource.tags().containsKey("tag1"));
    Assert.assertTrue(resource.securityRules().get("rule2").sourceApplicationSecurityGroupIds().isEmpty());
    Assert.assertNull(resource.securityRules().get("rule2").sourceAddressPrefix());
    Assert.assertEquals(2, resource.securityRules().get("rule2").sourceAddressPrefixes().size());
    Assert.assertTrue(resource.securityRules().get("rule2").sourceAddressPrefixes().contains("100.1.0.0/29"));
    Assert.assertEquals(1, resource.securityRules().get("rule2").sourcePortRanges().size());
    Assert.assertEquals("88-90", resource.securityRules().get("rule2").sourcePortRanges().get(0));

    resource.updateTags()
            .withTag("tag3", "value3")
            .withoutTag("tag1")
            .applyTags();
    Assert.assertEquals("value3", resource.tags().get("tag3"));
    Assert.assertFalse(resource.tags().containsKey("tag1"));
    return resource;
}
 
Example #10
Source File: NetworkInterfaceImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public NetworkSecurityGroup getNetworkSecurityGroup() {
    if (this.networkSecurityGroup == null && this.networkSecurityGroupId() != null) {
        String id = this.networkSecurityGroupId();
        this.networkSecurityGroup = super.myManager
                .networkSecurityGroups()
                .getByResourceGroup(ResourceUtils.groupFromResourceId(id),
                ResourceUtils.nameFromResourceId(id));
    }
    return this.networkSecurityGroup;
}
 
Example #11
Source File: NetworkInterfaceImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public NetworkInterfaceImpl withNewNetworkSecurityGroup(Creatable<NetworkSecurityGroup> creatable) {
    if (this.creatableNetworkSecurityGroupKey == null) {
        this.creatableNetworkSecurityGroupKey = this.addDependency(creatable);
    }
    return this;
}
 
Example #12
Source File: AzureNetworkSecurityGroupScannerTest.java    From clouditor with Apache License 2.0 5 votes vote down vote up
@BeforeAll
static void setUpOnce() {
  discoverAssets(
      AzureNetworkSecurityGroupScanner::new,
      api -> {
        var nsg = createWithId(NetworkSecurityGroup.class, "id", new NetworkSecurityGroupInner());

        when(api.azure.networkSecurityGroups().list()).thenReturn(MockedPagedList.of(nsg));
      });
}
 
Example #13
Source File: SubnetImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public NetworkSecurityGroup getNetworkSecurityGroup() {
    String nsgId = this.networkSecurityGroupId();
    return (nsgId != null)
            ? this.parent().manager().networkSecurityGroups().getById(nsgId)
            : null;
}
 
Example #14
Source File: AzureNetworkSecurityGroupScanner.java    From clouditor with Apache License 2.0 5 votes vote down vote up
@Override
protected Asset transform(NetworkSecurityGroup nsg) throws ScanException {
  var asset = super.transform(nsg);

  var watcher =
      this.api
          .azure()
          .networkWatchers()
          .getById(
              "/subscriptions/"
                  + this.api.azure().subscriptionId()
                  + "/resourceGroups/NetworkWatcherRG/providers/Microsoft.Network/networkWatchers/NetworkWatcher_"
                  + nsg.regionName());

  if (watcher != null) {
    // this needs the Network Contributor role!
    enrich(
        asset,
        "flowLogSettings",
        nsg,
        x -> watcher.getFlowLogSettings(nsg.id()),
        x -> null,
        x -> null);
  }

  return asset;
}
 
Example #15
Source File: NetworkSecurityGroupImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<NetworkSecurityGroup> refreshAsync() {
    return super.refreshAsync().map(new Func1<NetworkSecurityGroup, NetworkSecurityGroup>() {
        @Override
        public NetworkSecurityGroup call(NetworkSecurityGroup networkSecurityGroup) {
            NetworkSecurityGroupImpl impl = (NetworkSecurityGroupImpl) networkSecurityGroup;

            impl.initializeChildrenFromInner();
            return impl;
        }
    });
}
 
Example #16
Source File: AzurePlatformResources.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void convertAndAddToResult(Region region, Map<String, Set<CloudSecurityGroup>> result, NetworkSecurityGroup securityGroup) {
    String actualRegionLabel = securityGroup.region().label();
    String actualRegionName = securityGroup.region().name();
    if (regionMatch(actualRegionLabel, region) || regionMatch(actualRegionName, region)) {
        Map<String, Object> properties = new HashMap<>();
        properties.put("resourceGroupName", securityGroup.resourceGroupName());
        properties.put("networkInterfaceIds", securityGroup.networkInterfaceIds());
        CloudSecurityGroup cloudSecurityGroup = new CloudSecurityGroup(securityGroup.name(), securityGroup.id(), properties);
        result.computeIfAbsent(actualRegionLabel, s -> new HashSet<>()).add(cloudSecurityGroup);
        result.computeIfAbsent(actualRegionName, s -> new HashSet<>()).add(cloudSecurityGroup);
    }
}
 
Example #17
Source File: AzureClient.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public NetworkSecurityGroup getSecurityGroupProperties(String resourceGroup, String securityGroup) {
    return handleAuthException(() -> azure.networkSecurityGroups().getByResourceGroup(resourceGroup, securityGroup));
}
 
Example #18
Source File: Utils.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
/**
 * Print network info.
 *
 * @param resource a network
 * @throws CloudException Cloud errors
 */
public static void print(Network resource) {
    StringBuilder info = new StringBuilder();
    info.append("Network: ").append(resource.id())
            .append("Name: ").append(resource.name())
            .append("\n\tResource group: ").append(resource.resourceGroupName())
            .append("\n\tRegion: ").append(resource.region())
            .append("\n\tTags: ").append(resource.tags())
            .append("\n\tAddress spaces: ").append(resource.addressSpaces())
            .append("\n\tDNS server IPs: ").append(resource.dnsServerIPs());

    // Output subnets
    for (Subnet subnet : resource.subnets().values()) {
        info.append("\n\tSubnet: ").append(subnet.name())
                .append("\n\t\tAddress prefix: ").append(subnet.addressPrefix());

        // Output associated NSG
        NetworkSecurityGroup subnetNsg = subnet.getNetworkSecurityGroup();
        if (subnetNsg != null) {
            info.append("\n\t\tNetwork security group ID: ").append(subnetNsg.id());
        }

        // Output associated route table
        RouteTable routeTable = subnet.getRouteTable();
        if (routeTable != null) {
            info.append("\n\tRoute table ID: ").append(routeTable.id());
        }

        // Output services with access
        Map<ServiceEndpointType, List<Region>> services = subnet.servicesWithAccess();
        if (services.size() > 0) {
            info.append("\n\tServices with access");
            for (Map.Entry<ServiceEndpointType, List<Region>> service : services.entrySet()) {
                info.append("\n\t\tService: ")
                        .append(service.getKey())
                        .append(" Regions: " + service.getValue() + "");
            }
        }
    }

    // Output peerings
    for (NetworkPeering peering : resource.peerings().list()) {
        info.append("\n\tPeering: ").append(peering.name())
                .append("\n\t\tRemote network ID: ").append(peering.remoteNetworkId())
                .append("\n\t\tPeering state: ").append(peering.state())
                .append("\n\t\tIs traffic forwarded from remote network allowed? ").append(peering.isTrafficForwardingFromRemoteNetworkAllowed())
                .append("\n\t\tGateway use: ").append(peering.gatewayUse());
    }
    System.out.println(info.toString());
}
 
Example #19
Source File: NetworkInterfaceImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public NetworkInterfaceImpl withExistingNetworkSecurityGroup(NetworkSecurityGroup networkSecurityGroup) {
    this.existingNetworkSecurityGroupToAssociate = networkSecurityGroup;
    return this;
}
 
Example #20
Source File: SubnetImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public SubnetImpl withExistingNetworkSecurityGroup(NetworkSecurityGroup nsg) {
    return withExistingNetworkSecurityGroup(nsg.id());
}
 
Example #21
Source File: AzureNetworkSecurityGroupScanner.java    From clouditor with Apache License 2.0 4 votes vote down vote up
public AzureNetworkSecurityGroupScanner() {
  super(NetworkSecurityGroup::id, NetworkSecurityGroup::name);
}
 
Example #22
Source File: TestNetwork.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
/**
 * Outputs info about a network.
 * @param resource a network
 */
public static void printNetwork(Network resource) {
    StringBuilder info = new StringBuilder();
    info.append("Network: ").append(resource.id())
            .append("Name: ").append(resource.name())
            .append("\n\tResource group: ").append(resource.resourceGroupName())
            .append("\n\tRegion: ").append(resource.region())
            .append("\n\tTags: ").append(resource.tags())
            .append("\n\tAddress spaces: ").append(resource.addressSpaces())
            .append("\n\tDNS server IPs: ").append(resource.dnsServerIPs());

    // Output subnets
    for (Subnet subnet : resource.subnets().values()) {
        info.append("\n\tSubnet: ").append(subnet.name())
            .append("\n\t\tAddress prefix: ").append(subnet.addressPrefix());

        // Show associated NSG
        NetworkSecurityGroup nsg = subnet.getNetworkSecurityGroup();
        if (nsg != null) {
            info.append("\n\tNetwork security group ID: ").append(nsg.id());
        }

        // Show associated route table
        RouteTable routeTable = subnet.getRouteTable();
        if (routeTable != null) {
            info.append("\n\tRoute table ID: ").append(routeTable.id());
        }

        // Output services with access
        Map<ServiceEndpointType, List<Region>> services = subnet.servicesWithAccess();
        if (services.size() > 0) {
            info.append("\n\tServices with access");
            for (Map.Entry<ServiceEndpointType, List<Region>> service : services.entrySet()) {
                info.append("\n\t\tService: ")
                        .append(service.getKey())
                        .append(" Regions: " + service.getValue() + "");
            }
        }
    }

    // Output peerings
    for (NetworkPeering peering : resource.peerings().list()) {
        info.append("\n\tPeering: ").append(peering.name())
            .append("\n\t\tRemote network ID: ").append(peering.remoteNetworkId())
            .append("\n\t\tPeering state: ").append(peering.state())
            .append("\n\t\tIs traffic forwarded from remote network allowed? ").append(peering.isTrafficForwardingFromRemoteNetworkAllowed())
            //TODO .append("\n\t\tIs access from remote network allowed? ").append(peering.isAccessBetweenNetworksAllowed())
            .append("\n\t\tGateway use: ").append(peering.gatewayUse());
    }

    System.out.println(info.toString());
}
 
Example #23
Source File: TestNetwork.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public Network updateResource(Network resource) throws Exception {
    NetworkSecurityGroup nsg = resource.manager().networkSecurityGroups().define("nsgB" + this.testId)
            .withRegion(resource.region())
            .withExistingResourceGroup(resource.resourceGroupName())
            .create();

    resource =  resource.update()
            .withTag("tag1", "value1")
            .withTag("tag2", "value2")
            .withAddressSpace("141.25.0.0/16")
            .withoutAddressSpace("10.1.0.0/28")
            .withSubnet("subnetC", "141.25.0.0/29")
            .withoutSubnet("subnetA")
            .updateSubnet("subnetB")
                .withAddressPrefix("141.25.0.8/29")
                .withoutNetworkSecurityGroup()
                .parent()
            .defineSubnet("subnetD")
                .withAddressPrefix("141.25.0.16/29")
                .withExistingNetworkSecurityGroup(nsg)
                .attach()
            .apply();
    Assert.assertTrue(resource.tags().containsKey("tag1"));

    // Verify address spaces
    Assert.assertEquals(2, resource.addressSpaces().size());
    Assert.assertFalse(resource.addressSpaces().contains("10.1.0.0/28"));

    // Verify subnets
    Assert.assertEquals(3, resource.subnets().size());
    Assert.assertFalse(resource.subnets().containsKey("subnetA"));

    Subnet subnet = resource.subnets().get("subnetB");
    Assert.assertNotNull(subnet);
    Assert.assertEquals("141.25.0.8/29", subnet.addressPrefix());
    Assert.assertNull(subnet.networkSecurityGroupId());

    subnet = resource.subnets().get("subnetC");
    Assert.assertNotNull(subnet);
    Assert.assertEquals("141.25.0.0/29", subnet.addressPrefix());
    Assert.assertNull(subnet.networkSecurityGroupId());

    subnet = resource.subnets().get("subnetD");
    Assert.assertNotNull(subnet);
    Assert.assertEquals("141.25.0.16/29", subnet.addressPrefix());
    Assert.assertTrue(nsg.id().equalsIgnoreCase(subnet.networkSecurityGroupId()));

    return resource;
}
 
Example #24
Source File: TestNSG.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public void print(NetworkSecurityGroup resource) {
    printNSG(resource);
}
 
Example #25
Source File: TestNSG.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public NetworkSecurityGroup createResource(NetworkSecurityGroups nsgs) throws Exception {
    final String newName = "nsg" + this.testId;
    final String resourceGroupName = "rg" + this.testId;
    final String nicName = "nic" + this.testId;
    final String asgName = SdkContext.randomResourceName("asg", 8);
    final Region region = Region.US_WEST;
    final SettableFuture<NetworkSecurityGroup> nsgFuture = SettableFuture.create();

    ApplicationSecurityGroup asg = nsgs.manager().applicationSecurityGroups().define(asgName)
            .withRegion(region)
            .withNewResourceGroup(resourceGroupName)
            .create();
    // Create
    Observable<Indexable> resourceStream = nsgs.define(newName)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroupName)
            .defineRule("rule1")
                .allowOutbound()
                .fromAnyAddress()
                .fromPort(80)
                .toAnyAddress()
                .toPort(80)
                .withProtocol(SecurityRuleProtocol.TCP)
                .attach()
            .defineRule("rule2")
                .allowInbound()
                .withSourceApplicationSecurityGroup(asg.id())
                .fromAnyPort()
                .toAnyAddress()
                .toPortRange(22, 25)
                .withAnyProtocol()
                .withPriority(200)
                .withDescription("foo!!")
                .attach()
            .createAsync();

    Utils.<NetworkSecurityGroup>rootResource(resourceStream)
            .subscribe(new Subscriber<NetworkSecurityGroup>() {
                   @Override
                   public void onCompleted() {
                        System.out.print("completed");
                   }

                   @Override
                   public void onError(Throwable throwable) {
                        nsgFuture.setException(throwable);
                   }

                   @Override
                   public void onNext(NetworkSecurityGroup networkSecurityGroup) {
                        nsgFuture.set(networkSecurityGroup);
                   }
               });

    NetworkSecurityGroup nsg = nsgFuture.get();

    NetworkInterface nic = nsgs.manager().networkInterfaces().define(nicName)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroupName)
            .withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic()
            .withExistingNetworkSecurityGroup(nsg)
            .create();

    nsg.refresh();

    // Verify
    Assert.assertTrue(nsg.region().equals(region));
    Assert.assertTrue(nsg.securityRules().size() == 2);

    // Confirm NIC association
    Assert.assertEquals(1, nsg.networkInterfaceIds().size());
    Assert.assertTrue(nsg.networkInterfaceIds().contains(nic.id()));

    Assert.assertEquals(1, nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds().size());
    Assert.assertEquals(asg.id(), nsg.securityRules().get("rule2").sourceApplicationSecurityGroupIds().iterator().next());

    return nsg;
}
 
Example #26
Source File: VirtualMachineOperationsTests.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Test
public void canCreateVirtualMachineWithNetworking() throws Exception {
    NetworkSecurityGroup nsg = this.networkManager.networkSecurityGroups().define("nsg")
        .withRegion(REGION)
        .withNewResourceGroup(RG_NAME)
        .defineRule("rule1")
            .allowInbound()
            .fromAnyAddress()
            .fromPort(80)
            .toAnyAddress()
            .toPort(80)
            .withProtocol(SecurityRuleProtocol.TCP)
            .attach()
        .create();

    Creatable<Network> networkDefinition = this.networkManager.networks().define("network1")
        .withRegion(REGION)
        .withNewResourceGroup(RG_NAME)
        .withAddressSpace("10.0.0.0/28")
        .defineSubnet("subnet1")
            .withAddressPrefix("10.0.0.0/29")
            .withExistingNetworkSecurityGroup(nsg)
            .attach();

    // Create
    VirtualMachine vm = computeManager.virtualMachines()
        .define(VMNAME)
            .withRegion(REGION)
            .withNewResourceGroup(RG_NAME)
            .withNewPrimaryNetwork(networkDefinition)
            .withPrimaryPrivateIPAddressDynamic()
            .withoutPrimaryPublicIPAddress()
            .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
            .withRootUsername("Foo12")
            .withRootPassword("abc!@#F0orL")
        .create();

    NetworkInterface primaryNic = vm.getPrimaryNetworkInterface();
    Assert.assertNotNull(primaryNic);
    NicIPConfiguration primaryIpConfig = primaryNic.primaryIPConfiguration();
    Assert.assertNotNull(primaryIpConfig);

    // Fetch the NSG the way before v1.2
    Assert.assertNotNull(primaryIpConfig.networkId());
    Network network = primaryIpConfig.getNetwork();
    Assert.assertNotNull(primaryIpConfig.subnetName());
    Subnet subnet = network.subnets().get(primaryIpConfig.subnetName());
    Assert.assertNotNull(subnet);
    nsg = subnet.getNetworkSecurityGroup();
    Assert.assertNotNull(nsg);
    Assert.assertEquals("nsg", nsg.name());
    Assert.assertEquals(1, nsg.securityRules().size());

    // Fetch the NSG the v1.2 way
    nsg = primaryIpConfig.getNetworkSecurityGroup();
    Assert.assertEquals("nsg", nsg.name());
}
 
Example #27
Source File: VirtualMachineScaleSetImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public VirtualMachineScaleSetImpl withExistingNetworkSecurityGroup(NetworkSecurityGroup networkSecurityGroup) {
    VirtualMachineScaleSetNetworkConfiguration nicConfig = this.primaryNicConfiguration();
    nicConfig.withNetworkSecurityGroup(new SubResource().withId(networkSecurityGroup.id()));
    return this;
}
 
Example #28
Source File: AzureNetworkSecurityGroupScanner.java    From clouditor with Apache License 2.0 4 votes vote down vote up
@Override
protected List<NetworkSecurityGroup> list() {
  return this.resourceGroup != null
      ? this.api.azure().networkSecurityGroups().listByResourceGroup(this.resourceGroup)
      : this.api.azure().networkSecurityGroups().list();
}
 
Example #29
Source File: VirtualMachineScaleSet.java    From azure-libraries-for-java with MIT License 2 votes vote down vote up
/**
 * Specifies the network security group for the virtual machine scale set.
 *
 * @param networkSecurityGroup the network security group to associate
 *
 * @return the next stage of the update
 */
WithApply withExistingNetworkSecurityGroup(NetworkSecurityGroup networkSecurityGroup);
 
Example #30
Source File: VirtualMachineScaleSet.java    From azure-libraries-for-java with MIT License 2 votes vote down vote up
/**
 * Specifies the network security group for the virtual machine scale set.
 *
 * @param networkSecurityGroup the network security group to associate
 *
 * @return the next stage of the definition
 */
WithCreate withExistingNetworkSecurityGroup(NetworkSecurityGroup networkSecurityGroup);