Reputation: 1195
I use python sdk of gcp to get compute engine list and I want to judge the the operating system of google compute engine is linux or windows, but there is no any operating system informatioin in all fields of compute engine.
import sys
import json
from google.oauth2 import service_account
from google.cloud import compute_v1
class VM:
def __init__(self, cred_json_path):
self.cred_json_path = cred_json_path
self.credentials = self.create_credentials()
self.page_size = 500
def create_credentials(self):
return service_account.Credentials.from_service_account_file(self.cred_json_path)
def list_instance(self):
compute_client = compute_v1.InstancesClient(credentials=self.credentials)
results = []
for _, instances in compute_client.aggregated_list(request={"project": self.credentials.project_id, "max_results": self.page_size}):
for instance in instances.instances:
# TODO
# I want to judge the operating system information for every instance is linux or windows here.
results.append(instance)
return results
def show(self):
instance_list = self.list_instance()
for instance in instance_list:
print(json.dumps(instance))
def main(cred_json_path):
vm = VM(cred_json_path)
vm.show()
if __name__ == '__main__':
main(sys.argv[1])
Is there any solution? Thanks.
Upvotes: 1
Views: 149
Reputation: 29
GCP SDK's compute_v1 seems to have a get_guest_attributes method. When attempting to use it:
compute_guest_data = compute_client.get_guest_attributes(project=GCPClass.project, zone=Zone, instance=obj)
I was able to retrieve:
kind: "compute#guestAttributes"
self_link: "https://www.googleapis.com/compute/v1/projects/prjname/zones/zonename/instances/instancename/guestAttributes/"
variable_key: ""
variable_value: "x86_64"
I'm not sure if the SDK allows setting the queryPath, it seems to me that get_guest_attributes should accept another parameter for queryPath/Key. For now, requests to the rescue, referencing the Google documentation, I came up with:
url = (f"https://compute.googleapis.com/compute/v1/projects/{GCPClass.project}/zones/{Zone}/instances/{obj}/"f"getGuestAttributes?queryPath=guestInventory/LongName")
auth_token = GCPClass.get_auth_token()
os_info_response = requests.get(url, headers={"Authorization": f"Bearer {auth_token}"})
if os_info_response.ok:
data = os_info_response.json()
guest_os = data.get("queryValue", {}).get("items", [{}])[0].get("value")
print("Guest OS:", guest_os)
else:
print("Failed to retrieve guest attributes.")
print(f"Status code: {os_info_response.status_code}")
This returned the guest os info properly.
Here's my get_auth_token for reference:
def get_auth_token(self):
scopes = ["https://www.googleapis.com/auth/compute"]
creds = service_account.Credentials.from_service_account_info(json.loads(self.gcp_auth_data), scopes=scopes)
request = Request()
creds.refresh(request)
return creds.token
Upvotes: 0