The GCP API is the programmatic interface for creating, reading, updating, and deleting Google Cloud Platform resources. It exposes current resource configuration for automation, migration, and policy checks. section 3.6 section 10.2.1
Use the API to support infrastructure workflows:
- Implement factory modules with separate create, read, update, and delete functions for each resource. section 3.6
- Retrieve live IAM policies, user emails, roles, and identifiers before importing existing resources into Terraform state. section 10.2.1
- Query machine-type catalogs for vCPU and memory data, then enforce infrastructure cost policies in tests. section 12.1.1
- Prefer provider-specific client libraries when a general infrastructure library cannot retrieve all required GCP resources. section 10.2.1
Importing active IAM resources
A refactoring workflow queries the GCP API for the current IAM policy, extracts members and roles, imports the existing resources into Terraform, removes the old state entries, and confirms that the next plan reports no changes. section 10.2.1
Listing 12.1 Retrieving vCPU count for machine type from the GCP API
import googleapiclient.discovery
class MachineType(): #1
def __init__(self, gcp_json): #1
self.name = gcp_json['name'] #1
self.cpus = gcp_json['guestCpus'] #1
self.ram = self._convert_mb_to_gb( #2
gcp_json['memoryMb']) #2
self.maxPersistentDisks = gcp_json[ #2
'maximumPersistentDisks'] #2
self.maxPersistentDiskSizeGb = gcp_json[ #2
'maximumPersistentDisksSizeGb'] #2
self.isSharedCpu = gcp_json['isSharedCpu'] #2
def _convert_mb_to_gb(self, mb): #2
GIGABYTE = 1.0/1024 #2
return GIGABYTE * mb #2
def get_machine_type(project, zone, type):
service = googleapiclient.discovery.build(
'compute', 'v1')
result = service.machineTypes().list( #3
project=project, #3
zone=zone, #3
filter=f'name:"{type}"').execute() #3
types = result['items'] if 'items' in result else None
if len(types) != 1:
return None
return MachineType(types[0]) #4
The listing shows a Python client response being converted into a machine-type object containing CPUs, memory, disk limits, and shared-CPU status. section 12.1.1
