Skip to content

Instantly share code, notes, and snippets.

@Burekasim
Created February 24, 2022 15:37
Show Gist options
  • Save Burekasim/fb7fd860a88db6bf015b3c2294e60223 to your computer and use it in GitHub Desktop.
Save Burekasim/fb7fd860a88db6bf015b3c2294e60223 to your computer and use it in GitHub Desktop.
Python script to associate a static ip to gcp instance
import requests
import googleapiclient.discovery
from oauth2client.client import GoogleCredentials
from time import sleep
from random import randint
'''
permissions
compute.addresses.get
compute.addresses.list
compute.addresses.use
compute.instances.addAccessConfig
compute.instances.deleteAccessConfig
compute.subnetworks.useExternalIp
'''
def metadata(param: str):
response = requests.get('http://metadata.google.internal/0.1/meta-data/{}'.format(param))
if response.ok:
return str(response.text)
else:
return ''
if __name__ == '__main__':
credentials = GoogleCredentials.get_application_default()
compute = googleapiclient.discovery.build('compute', 'v1')
service = googleapiclient.discovery.build('cloudresourcemanager', 'v1', credentials=credentials)
instance_id = metadata('instance-id')
project_id = metadata('project-id')
zone = metadata('zone').split('/')[-1]
ips_dict = compute.addresses().list(project=project_id, region='us-east1',
filter='status=RESERVED AND labels.myip=1').execute()
static_ip_list = [item['address'] for item in ips_dict['items']]
request = compute.instances().deleteAccessConfig(project=project_id, zone=zone, instance=instance_id,
networkInterface='nic0', accessConfig='External NAT').execute()
body = {
"type": 'ONE_TO_ONE_NAT',
"name": 'External NAT',
"natIP": static_ip_list[0],
"networkTier": 'PREMIUM',
"kind": 'compute#accessConfig'
}
retries = 10
for _ in range(retries):
try:
create_access_config = compute.instances().addAccessConfig(project=project_id, zone=zone,
instance=instance_id, networkInterface='nic0',
body=body).execute()
if create_access_config:
break
except googleapiclient.errors.HttpError:
sleep(randint(1, 90) / 10)
retries -= 1
else:
print('Could not attach static ip.')
print(f'Successfuly attached ip: {static_ip_list[0]}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment