[OCI] Python script to get the IP address of a compute instance in Cloud Shell

This article is about [Writing Python scripts to run from the OCI Console Cloud Shell](https://medium.com/oracledevs/writing-python-scripts-to-run-from-the-oci-console-cloud-shell- This is the execution of the contents of a0be1091384c).

OCI Cloud Shell OCI Cloud Shell is a web browser-based Shell terminal accessible from the OCI web console. Cloud Shell has the following features:

--Pre-authenticated OCI CLI --No configuration required to start using CLI in Cloud Shell --A complete Linux shell with key developer tools to interact with Oracle Cloud Infrastructure services and a pre-installed language runtime --OCI SDK and Oracle Instant Client for each language --5 GB storage for home directory --You can save your work between Cloud Shell sessions --Console persistent frames that remain active when navigating to different pages of the console

Compute instance IP address acquisition script example)

list_ipaddress.py


#!/usr/bin/env python
 
import oci
 
delegation_token = open('/etc/oci/delegation_token', 'r').read()
signer = oci.auth.signers.InstancePrincipalsDelegationTokenSigner(
  delegation_token=delegation_token
)

search_client = oci.resource_search.ResourceSearchClient({},signer=signer)
compute_client = oci.core.ComputeClient({},signer=signer)
network_client = oci.core.VirtualNetworkClient({},signer=signer)
 
resp = search_client.search_resources(
  oci.resource_search.models.StructuredSearchDetails(
  type="Structured",
  query="query instance resources"
  )
)
 
for instance in resp.data.items:
  resp = compute_client.list_vnic_attachments(
  compartment_id=instance.compartment_id,
  instance_id=instance.identifier
  )
 
  for vnic_attachment in resp.data:
    vnic = network_client.get_vnic(vnic_attachment.vnic_id).data
    print("\t".join([
    instance.display_name,
    vnic.display_name,
    vnic.private_ip,
    vnic.public_ip
    ]))

Execution example

$ python ./list_ipaddress.py
fmwf    fmwf    10.0.0.4       150.136.236.XXX
db01    db01    10.0.0.3       150.136.37.XXX
gpu01   gpu01   10.0.0.5       150.136.89.XXX
fn      fn      10.0.0.2        158.101.118.XXX

Script supplement

singer When writing a Python script that runs inside the Cloud Shell, you can use the existing authentication of the Cloud Shell. You can omit the separate API key settings required to run the script. Load an existing instance principal delegation token and generate a signer.

#!/usr/bin/env python
 
import oci
 
delegation_token = open('/etc/oci/delegation_token', 'r').read()
signer = oci.auth.signers.InstancePrincipalsDelegationTokenSigner(
  delegation_token=delegation_token
)

Create an authenticated client

Search for all instances in the current region Inquire about instance details and get an IP address API client definition

search_client = oci.resource_search.ResourceSearchClient({},signer=signer)
compute_client = oci.core.ComputeClient({},signer=signer)
network_client = oci.core.VirtualNetworkClient({},signer=signer)

Get an IP address

Find all attached vnics for each instance Get both public and private IP addresses for each vnic

for instance in resp.data.items:
  resp = compute_client.list_vnic_attachments(
  compartment_id=instance.compartment_id,
  instance_id=instance.identifier
  )
 
  for vnic_attachment in resp.data:
    vnic = network_client.get_vnic(vnic_attachment.vnic_id).data
    print("\t".join([
    instance.display_name,
    vnic.display_name,
    vnic.private_ip,
    vnic.public_ip
    ]))

Reference information

Recommended Posts

[OCI] Python script to get the IP address of a compute instance in Cloud Shell
I tried to create a Python script to get the value of a cell in Microsoft Excel
Get the caller of a function in Python
Get a datetime instance at any time of the day in Python
Memo of the program to get the date in two digits with javascript, Ruby, Python, shell script
How to pass the execution result of a shell command in a list in Python
How to get the number of digits in Python
Python script to get a list of input examples for the AtCoder contest
How to get a list of files in the same directory with python
Get the number of specific elements in a python list
How to get the last (last) value in a list in Python
How to get a list of built-in exceptions in python
Get the script path in Python
Get the value of a specific key up to the specified index in the dictionary list in Python
How to pass the execution result of a shell command in a list in Python (non-blocking version)
Process the contents of the file in order with a shell script
How to determine the existence of a selenium element in Python
Try to get a list of breaking news threads in Python.
Conditional branch due to the existence of a shell script file
How to check the memory size of a variable in Python
Create a shell script to run the python file multiple times
How to check the memory size of a dictionary in Python
How to get the vertex coordinates of a feature in ArcPy
How to update the python version of Cloud Shell on GCP
Create a function to get the contents of the database in Go
Get the number of readers of a treatise on Mendeley in Python
Run the Python interpreter in a script
How to get a stacktrace in python
To get a local IP address programmatically
[python] Get a list of instance variables
Get your own IP address in Python
Write a script in Shell and Python to notify you in Slack when the process is finished
Get a capture of the entire web page in Selenium Python VBA
Script to register the IP address used by wercker in Security Group
I made a program to check the size of a file in Python
Get the return value of an external shell script (ls) with python3
Make a copy of the list in Python
How to get the files in the [Python] folder
Output in the form of a python array
Get a glimpse of machine learning in Python
Various ways to read the last line of a csv file in Python
Convert the cURL API to a Python script (using IBM Cloud object storage)
I made a script to record the active window using win32gui of Python
A tool to insert the country name and country code in the IP address part
[Introduction to Python] How to get the index of data with a for statement
I created a script to check if English is entered in the specified position of the JSON file in Python.
How to get the variable name itself in python
[python] Get the list of classes defined in the module
A memorandum to run a python script in a bat file
Get the return code of the Python script from bat
Get the size (number of elements) of UnionFind in Python
Script to get the expiration date of the SSL certificate
Get the URL of the HTTP redirect destination in Python
A reminder about the implementation of recommendations in Python
To do the equivalent of Ruby's ObjectSpace._id2ref in Python
Python Note: The mystery of assigning a variable to a variable
Get the value of a specific key in a list from the dictionary type in the list with Python
How to identify the element with the smallest number of characters in a Python list?
How to check in Python if one of the elements of a list is in another list
A story about trying to introduce Linter in the middle of a Python (Flask) project
Don't take an instance of a Python exception class directly as an argument to the exception class!