I would like to know how can I manage data that I can get as an output from gcloud commands embedded in the Python script. For example, I prepared simple script in Python. I am executing it from the Google Cloud Shell Editor. Code looks like below:
import subprocess
project = "gcloud info --format='value(config.project)'"
subprocess.call(project, shell=True)
subprocess.run(["gcloud config set project projectID"], shell=True)
result = subprocess.run(["gcloud compute instances os-inventory list-instances"], shell=True)
print(result)
As an output in the terminal I can see list of VMs. I would like to filter out only VMs with a specific property, name or IP number. How can I manage these output, the class of that variable result
is <class 'subprocess.CompletedProcess'>
.
Script output looks like below:
NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS
server00 europe-west2-c e2-medium 10.x.x.x x.x.x.x RUNNING
server01 europe-west2-c e2-medium 10.x.x.x x.x.x.x RUNNING
Try using result.stdout
.
You may need to add capture_output=True
to the subprocess.run call as well. So do:
subprocess.run(["gcloud config set project projectID"], capture_output=True, text=True, shell=True)
That will give you the stdout text which you can then split on newlines, iterate over the array created, filter on whatever you need, etc.
For filtering, you could either do it on the subprocess command, or post processing. So for example, if you wanted to only see resulting VMs that are in the us-central1 region, you could change your subprocess command from:
["gcloud config set project projectID"]
to
["gcloud config set project projectID | grep us-central1"]
Alternately, to post-process you could do:
project = "gcloud info --format='value(config.project)'"
subprocess.call(project, shell=True)
subprocess.run(["gcloud config set project projectID"], shell=True)
result = subprocess.run(["gcloud compute instances os-inventory list-instances"], shell=True)
arr = result.stdout.split("\n")
for line in arr:
if "us-central1" in line:
print(line)