Skip to content

Instantly share code, notes, and snippets.

@ankona
Created May 4, 2016 17:36
Show Gist options
  • Save ankona/a3e84f9b760f98ce9701872f7912b35b to your computer and use it in GitHub Desktop.
Save ankona/a3e84f9b760f98ce9701872f7912b35b to your computer and use it in GitHub Desktop.
starter script to use boto / aws API to deploy a cloudformation script
import os
import time
import boto3
from botocore.exceptions import ClientError
def get_api_id_from_stack(stack_name):
api_id = ""
try:
cloudformation = boto3.client('cloudformation')
resp = cloudformation.describe_stack_resources(StackName=stack_name)
for r in resp['StackResources']:
if r['ResourceType'] == "AWS::ApiGateway::RestApi":
api_id = r['PhysicalResourceId']
break
except:
print 'missing api name'
return api_id
def deploy_api_to_stage(env, stack_name):
api_id = get_api_id_from_stack(stack_name)
def get_stack_details(stack_name):
stack_response = None
try:
client = boto3.client('cloudformation')
stack_response = client.describe_stacks(StackName=stack_name)
except ClientError, e:
# {'response': {'ResponseMetadata': {'HTTPStatusCode': 400, 'RequestId': '0260b50f-1140-11e6-afe2-6d45d439b6fc'},
# 'Error': {'Message': 'Stack with id cfcareers-chriscfX does not exist', 'Code': 'ValidationError', 'Type': 'Sender'}}}
if e.response['Error']['Message'].find("does not exist"):
print 'stack {0} not found...'.format(stack_name)
else:
raise
else:
stack_arn = stack_response['Stacks'][0]['StackId']
print stack_arn
return stack_response['Stacks'][0]
def deploy_cloudformation_script(env, stack_name, template_body, cf_parameters):
client = boto3.client('cloudformation')
stack_arn = ""
stack_details = get_stack_details(stack_name)
if stack_details:
stack_arn = stack_details['StackId']
if stack_details['StackStatus'] in ['CREATE_IN_PROGRESS', 'UPDATE_IN_PROGRESS']:
print 'stack is currently being created/updated...'
return
if len(stack_arn) > 0:
try:
print 'updating stack...'
resp = client.update_stack(StackName=stack_name,
TemplateBody=template_body,
Parameters=cf_parameters,
Capabilities=['CAPABILITY_IAM'],
Tags=[{'Key': 'environment', 'Value': env}])
except ClientError, e:
if e.response['Error']['Message'] == "No updates are to be performed.":
print('No updates are to be performed')
else:
raise
else:
try:
print 'creating stack...'
resp = client.create_stack(StackName=stack_name,
TemplateBody=template_body,
Parameters=cf_parameters,
Capabilities=['CAPABILITY_IAM'],
Tags=[{'Key': 'environment', 'Value': env}])
print resp
except ClientError, e:
if e.response['Error']['Message'] == "No updates are to be performed.":
print('No updates are to be performed')
else:
raise
while True:
time.sleep(5)
stack_details = get_stack_details(stack_name)
if stack_details:
#print stack_details
if stack_details['StackStatus'] in ['CREATE_COMPLETE', 'UPDATE_COMPLETE']:
print 'stack script completed.'
break
elif stack_details['StackStatus'] in ['CREATE_IN_PROGRESS', 'UPDATE_IN_PROGRESS']:
print 'stack script in progress.'
else:
print 'uh oh. check stack status: '
break
#__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
#f = open(os.path.join(__location__, 'job_search_cf.template'));
f = open('my_cf.template')
template_body = f.read()
env = 'dev'
stack = 'mystackname'
parameters = [{"ParameterKey": "Environment", "ParameterValue": env}]
deploy_cloudformation_script(env, "{0}-{1}".format(stack, env), template_body, parameters)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment