A cloud provider API is a programmatic interface for querying or managing provider resources. In infrastructure code, it can expose low-level metadata—such as network, subnet, or IP-range attributes—to higher-level resources through an abstraction layer. section 4.2.2 section 4.2.3
Use a cloud provider API to:
- Decouple infrastructure modules by retrieving identifiers that a higher-level resource cannot reference directly. section 10.2.2
- Keep configuration responsive to changes in low-level resources, such as a renamed network or changed IP address range. section 4.2.3
- Validate deployed infrastructure by comparing active resource status with the intended infrastructure configuration. section 6.4.1
- Mock provider responses when unit-testing imperative automation without creating active resources. section 6.2.3
Network metadata for a server
A server asks the provider API for its network or subnet attributes, parses the returned metadata, and calculates configuration such as the fifth IP address. Updating the network first lets the server consume the new range without embedding the network’s implementation details. section 4.2.3
Provider-backed integration test
Render the configuration, deploy resources to a testing environment, query the provider API for the active server’s state, assert that it is running, and destroy the test resources. section 6.4.1
Listing 10.10 Using dependency inversion for the network name in the cluster
import googleapiclient.discovery #1
def _get_network_from_gcp(): #2
service = googleapiclient.discovery.build( #1
'compute', 'v1') #1
result = service.subnetworks().list( #3
project=PROJECT, #3
region=REGION, #3
filter=f'name:"{TEAM}-{ENVIRONMENT}-*"').execute() #3
subnetworks = result['items'] if 'items' in result else None
if len(subnetworks) != 1: #4
print("Network not found") #4
exit(1) #4
return subnetworks[0]['network'].split('/')[-1], \ #5
subnetworks[0]['name'] #5
def cluster(name=cluster_name, #6
node_name=cluster_nodes,
service_account=cluster_service_account,
region=REGION):
network, subnet = _get_network_from_gcp() #7
return [
{
'google_container_cluster': { #8
VERSION: [
{
'name': name,
'network': network, #9
'subnetwork': subnet #9
}
]
},
'google_container_node_pool': { #8
VERSION: [ #8
{ #8
'cluster': #8
'${google_container_cluster.' + #8
f'{VERSION}' + '.name}' #8
} #8
] #8
}, #8
'google_service_account': { #8
VERSION: [
{
'account_id': service_account,
'display_name': service_account
}
]
}
}
]
Shows a higher-level cluster resource querying the GCP API for a uniquely matching subnet and handling a missing or ambiguous result. section 10.2.2
