Created
June 9, 2016 21:49
-
-
Save victortrac/9611df4739aeaff5ae6b2f63229480f3 to your computer and use it in GitHub Desktop.
Replace instances in a GCE Managed Instance Group when Templates are updated
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
import time | |
from googleapiclient import discovery | |
from oauth2client.client import GoogleCredentials | |
def get_google_auth(service, version='v2'): | |
credentials = GoogleCredentials.get_application_default() | |
service_conn = discovery.build(service, version, credentials=credentials) | |
return service_conn | |
def get_instances_in_ig(conn, project, ig): | |
zone = ig.get('zone').split('/')[-1] | |
for i in conn.instanceGroups().listInstances(instanceGroup=ig.get('name'), project=project, zone=zone, body="").execute().get('items'): | |
yield i['instance'] | |
def main(project, ig_prefix): | |
compute_conn = get_google_auth('compute', 'v1') | |
ig_updater_conn = get_google_auth('replicapoolupdater', 'v1beta1') | |
all_instance_groups = compute_conn.instanceGroupManagers().aggregatedList(project=project).execute() | |
for location, igms in all_instance_groups.get('items', {}).items(): | |
for igm in igms.get('instanceGroupManagers', []): | |
if igm.get('name', "").startswith(ig_prefix): | |
_zone = igm['zone'].split('/')[-1] | |
managed_instances = compute_conn.instanceGroupManagers().listManagedInstances( | |
project=project, | |
zone=_zone, | |
instanceGroupManager=igm['name']).execute() | |
for i in managed_instances.get('managedInstances', []): | |
_instance_name = i.get('instance', "").split('/')[-1] | |
_instance = compute_conn.instances().get(project=project, zone=_zone, instance=_instance_name).execute() | |
for metadata in _instance['metadata']['items']: | |
if metadata.get('key') == 'instance-template': | |
_instance_template_url = metadata.get('value', "") | |
if igm['instanceTemplate'].split('/')[-1] != _instance_template_url.split('/')[-1]: | |
# Current instance template doesn't match IGM. Start rolling update. | |
_body = { | |
'actionType': 'RECREATE', | |
'instanceTemplate': igm['instanceTemplate'], | |
'instanceGroupManager': igm['selfLink'] | |
} | |
print('Updating instance {} with template {}'.format(_instance['name'], igm['instanceTemplate'])) | |
print(ig_updater_conn.rollingUpdates().insert(project=project, zone=_zone, body=_body).execute()) | |
time.sleep(60) | |
if __name__ == "__main__": | |
if len(sys.argv) != 3: | |
print('Must supply a project & a managed instance-group prefix to update') | |
sys.exit(1) | |
project = sys.argv[1] | |
group_prefix = sys.argv[2] | |
main(project, group_prefix) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment