Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#!/usr/bin/env python
import base64
import json
import os
import re
import yaml
YAML_CONFIG_FILE = os.environ.get('APPLICATION_CONFIG')
with open(YAML_CONFIG_FILE, 'r') as YAML_CONFIG:
APP_CONFIG = yaml.load(YAML_CONFIG)
with open('scripts/ami_lookup.yaml', 'r') as YAML_AMI:
AMI_DICT = yaml.load(YAML_AMI)
ENVIRONMENT = APP_CONFIG['environment']
AMI_NAME = APP_CONFIG['ami_name']
CONFIG = {}
CONFIG['image_id'] = AMI_DICT[ENVIRONMENT][AMI_NAME]
# grab 'spinners' from 'applications/spinners/production.yaml'
CONFIG['application_name'] = os.environ.get('APPLICATION_CONFIG').split('/')[-2]
CONFIG['environment'] = ENVIRONMENT
# tags
APP_CONFIG.setdefault('tags', {})
APP_CONFIG['tags']['environment'] = ENVIRONMENT
APP_CONFIG['tags']['Name'] = CONFIG['application_name']
# get the revision
if not os.environ.get('REVISION') or os.environ.get('REVISION', '').lower() == '${revision}':
raise Exception('Missing REVISION environment variable for this build.')
# build userdata
userdata = """export REVISION={revision}
export TAGS='{tags}'
export APPLICATION_NAME={app_name}
{userdata}""".format(
revision=os.environ.get('REVISION'),
tags=json.dumps(APP_CONFIG['tags']),
app_name=CONFIG['application_name'],
userdata=APP_CONFIG.get('userdata', '')
)
"""
Replace placeholder values in userdata.
Assuming: os.environ['REVISION'] = 123
"BUILD_NUMBER=%%REVISION%%" becomes "BUILD_NUMBER=123"
"""
for placeholder in re.findall(r'%%(.*)%%', userdata):
userdata = re.sub(r'%%{0}%%'.format(placeholder), os.environ.get(placeholder), userdata)
CONFIG['base64_userdata'] = base64.b64encode(userdata)
print yaml.dump(CONFIG)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment