How to get all ip attached to compute using python oci

1.9k views Asked by At

I want to use python oci package to get information about environment. how to list all IPs addresses (both public or private) attached to compute node? list_instances() does not provide this part of compute details unfortunately. thanks.

3

There are 3 answers

0
bmuthuv On BEST ANSWER

Please use this code. Basically you have to lookup VNIC Attachment object and filter VNIC_ID based on InstanceId. VNIC_ID can be used for looking up IP Addresses subsequently.

I have used data[0] to indicate the first attachment. You could use a loop to go through all attachments and print the IP.

    compute_client = oci.core.ComputeClient(config={}, signer=signer)
    network_client = oci.core.VirtualNetworkClient(
        config={}, signer=signer)
    vnic_id = compute_client.list_vnic_attachments(
        cd_compartment_id, instance_id=instanceId).data[0].vnic_id
    private_ip = network_client.get_vnic(vnic_id).data.private_ip
0
mrtaylor2112 On

As shared by @Char above, this oci-python-sdk example should help you here.

You can find a list of all supported services by SDK for Python here - https://docs.cloud.oracle.com/en-us/iaas/Content/API/SDKDocs/pythonsdk.htm

Additionally, full documentation for OCI Python SDK can be found here - https://docs.cloud.oracle.com/en-us/iaas/tools/python/2.21.5/

1
ircama On

Assuming that you have the display name of an OCI compute instance and you need its private and public IP addresses, provided that you already created an API key in your profile and that you configured your ~/.oci/config with valid pem private key downloaded when creating the API Key, the following Python code can help:

import oci

display_name = "your display name"

config = oci.config.from_file()
identity = oci.identity.IdentityClient(config)
user = identity.get_user(config["user"]).data
instances = oci.core.ComputeClient(config).list_instances(
    compartment_id=user.compartment_id).data
instance_id = {i.display_name: i.id for i in instances}[display_name]
compute_client = oci.core.ComputeClient(config)
vnic_data = compute_client.list_vnic_attachments(
    compartment_id=user.compartment_id, instance_id=instance_id).data
network_client = oci.core.VirtualNetworkClient(config)
vnic_list = [network_client.get_vnic(vnic_attachment.vnic_id).data
    for vnic_attachment in vnic_data]
public_ip = {i.display_name: i.public_ip for i in vnic_list}[display_name]
private_ip = {i.display_name: i.private_ip for i in vnic_list}[display_name]
print(public_ip, private_ip)

This implies:

pip3 install oci oci-cli