get instances from security group azure sdk

308 Views Asked by At

I want to list all my security groups but i want to check if any security group has instances or no, if yes i want to get this instances. How can i do that in code ? I just build function to get all security group.

  @Override
public List<LocalSecurityGroupV2> getSecurityGroups(final List<String> securityGroupIds) {
    return securityGroupIds
            .stream()
            .map(this::findSecurityGroupById)
            .collect(Collectors.toList());
}
2

There are 2 best solutions below

2
On

Can you please elaborate what do you mean by instances? Is this you are looking for?

Gets all network security groups in a subscription: https://learn.microsoft.com/en-us/rest/api/virtualnetwork/networksecuritygroups/listall

Gets all network security groups in a resource group: https://learn.microsoft.com/en-us/rest/api/virtualnetwork/networksecuritygroups/list

0
On

We could do that with Azure Java SDK. For authentication please refer to Authenticate with the Azure management libraries for Java.

The following is the demo code, I tested on my side.

String client = "clientId";
String tenant = "tenantId";
String key = "scret key";
ApplicationTokenCredentials credentials = new ApplicationTokenCredentials(client,
            tenant,
            key,
            AzureEnvironment.AZURE);
Azure azure = Azure.configure().authenticate(credentials).withDefaultSubscription();
List <VirtualMachine> vmlist = azure.virtualMachines().list();
List<String> networkInterfaceList = new ArrayList<String>();
PagedList<NetworkSecurityGroup> list = azure.networkSecurityGroups().listByResourceGroup("resourceGroupName");

//add the networkinterface to the list
for (NetworkSecurityGroup nsg :list
         ) {

     for (String networkInterface :nsg.networkInterfaceIds()
         ) {

           networkInterfaceList.add(networkInterface);

        }

    };


List<VirtualMachine> virtualMachineList = new ArrayList<VirtualMachine>();
for (VirtualMachine vm :vmlist
         ) {
        for (String vmInterface:vm.networkInterfaceIds()
             ) {
            if(networkInterfaceList.contains(vmInterface))
            {
                if(!virtualMachineList.contains(vm))
                {
                    virtualMachineList.add(vm);
                    System.out.println(vm.computerName());
                }

            }
        }

    }