...
 
Commits (5)
from datetime import timedelta, timezone, datetime
from time import strftime
import pprint
import logging
# Take a duration in seconds and work out the datetime value for the datetime at that date and time ago
def datetime_this_seconds_ago(duration):
......@@ -9,6 +10,8 @@ def datetime_this_seconds_ago(duration):
def seconds_from_hours(hours):
return (60*60)*hours
# TODO: Place holder
def log(message):
pprint.pprint(message)
print(message)
def set_logger():
return logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S%z')
This diff is collapsed.
import click
from akinaka_client.aws_client import AWS_Client
from akinaka_libs import helpers
from time import gmtime, strftime
import logging
helpers.set_logger()
@click.group()
@click.option("--region", required=True, help="Region your resources are located in")
@click.option("--role-arn", required=True, help="Role ARN which contains necessary assume permissions")
@click.option("--save-deploy-status", "save_deploy_status", default="true", help="Save of the deploy status in SSM Parameter Store.")
@click.pass_context
def update(ctx, region, role_arn):
ctx.obj = {'region': region, 'role_arn': role_arn}
def update(ctx, region, role_arn, save_deploy_status):
ctx.obj = {'region': region, 'role_arn': role_arn, 'save_deploy_status': save_deploy_status}
pass
def set_deploy_status(verb, region, role_arn, reset=None):
logging.info("Checking deployment status...")
aws_client = AWS_Client()
ssm_client = aws_client.create_client('ssm', region, role_arn)
......@@ -22,7 +26,7 @@ def set_deploy_status(verb, region, role_arn, reset=None):
deploying_state = "false"
if verb == "start" and deploying_state != "false" and reset != True:
print("Refusing to deploy, since it looks like we're already deploying at this timestamp: {}".format(deploying_state))
logging.error("Abort! Looks like that we have deployed at this timestamp: {}".format(deploying_state))
exit(1)
elif verb == "stop":
new_state = "false"
......@@ -36,6 +40,7 @@ def set_deploy_status(verb, region, role_arn, reset=None):
Type="String",
Overwrite=True
)
logging.info("Deployment status updated!")
@update.command()
......@@ -43,7 +48,9 @@ def set_deploy_status(verb, region, role_arn, reset=None):
def reset(ctx):
region = ctx.obj.get('region')
role_arn = ctx.obj.get('role_arn')
set_deploy_status("stop", region, role_arn, True)
save_deploy_status = ctx.obj.get('save_deploy_status')
if save_deploy_status == 'true':
set_deploy_status("stop", region, role_arn, True)
@update.command()
......@@ -55,10 +62,11 @@ def reset(ctx):
@click.option("--scale-to", "scale_to", help="Optionally set the number for the ASG to scale back up to. Defaults to 1")
def asg(ctx, ami, lb, asg_name, target_group, scale_to):
if [lb, asg_name, target_group].count(None) < 2:
print("--lb, --asg, and --target-group are mutually exclusive. Please use only one")
logging.error("--lb, --asg, and --target-group are mutually exclusive. Please use only one")
region = ctx.obj.get('region')
role_arn = ctx.obj.get('role_arn')
save_deploy_status = ctx.obj.get('save_deploy_status')
from .asg import update_asg
......@@ -66,7 +74,8 @@ def asg(ctx, ami, lb, asg_name, target_group, scale_to):
# working out the ASG to update from the load balancer, so as not to allow interruption to the
# processs until we've also updated the targetgroup
if lb or target_group:
set_deploy_status("start", region, role_arn)
if save_deploy_status == 'true':
set_deploy_status("start", region, role_arn)
asg = update_asg.ASG(ami, region, role_arn, lb, asg_name, target_group, scale_to)
asg.do_update()
......@@ -89,6 +98,6 @@ def targetgroup(ctx, new_asg_target):
set_deploy_status("stop", region, role_arn)
exit(0)
except Exception as e:
print(e)
logging.error("{}".format(e))
exit(1)
#!/usr/bin/env python3
from akinaka_client.aws_client import AWS_Client
from akinaka_libs import helpers
import logging
aws_client = AWS_Client()
helpers.set_logger()
class TargetGroup():
def __init__(self, region, role_arn, new_asg):
......@@ -12,43 +15,46 @@ class TargetGroup():
def switch_asg(self):
target_group_arns = []
inactive_asg = []
active_asg = []
passive = []
active = []
asg_client = aws_client.create_client('autoscaling', self.region, self.role_arn)
auto_scaling_groups = asg_client.describe_auto_scaling_groups()
for asg in auto_scaling_groups['AutoScalingGroups']:
# If the ASG's TargetGroupARNs attribute is empty, it's the inactive one
if len(asg['TargetGroupARNs']) < 1 and asg['AutoScalingGroupName'] == self.new_asg:
inactive_asg.append(asg)
# If the ASG's TargetGroupARNs attribute is not empty, it's the active one
elif len(asg['TargetGroupARNs']) > 0:
active_asg.append(asg)
# Exit program if there is no existing active auto scaling groups to perform a switch over\
if len(inactive_asg) < 1 or len(active_asg) < 1:
print('No auto scaling groups are available for this switch over.')
exit(1)
# Get the target group ARNs from the active auto scaling group
for arn in active_asg:
target_group_arns = arn['TargetGroupARNs']
# Add the asg (http, https) to the target group ARNs
# https://docs.aws.amazon.com/cli/latest/reference/autoscaling/attach-load-balancer-target-groups.html
for asg in inactive_asg:
asg_client.attach_load_balancer_target_groups(
AutoScalingGroupName=asg['AutoScalingGroupName'],
TargetGroupARNs=target_group_arns
)
# Remove the asg (http, https) from the target group
# https://docs.aws.amazon.com/cli/latest/reference/autoscaling/detach-load-balancer-target-groups.html
for asg in active_asg:
asg_client.detach_load_balancer_target_groups(
AutoScalingGroupName=asg['AutoScalingGroupName'],
TargetGroupARNs=target_group_arns
)
asgs = asg_client.describe_auto_scaling_groups()
# Determine the color of the auto scaling group
c = self.new_asg.split('-')
color = c[-1]
new_color = None
# Determine the "active" auto scaling group name
if color == 'blue':
new_color = 'green'
else:
new_color = 'blue'
c[-1] = new_color
active_asg = "-".join(c)
for asg in asgs['AutoScalingGroups']:
# print("{}, {}".format(asg['AutoScalingGroupName'], asg['TargetGroupARNs']))
if asg['AutoScalingGroupName'] == self.new_asg and len(asg['TargetGroupARNs']) < 1:
passive.append(asg)
if asg['AutoScalingGroupName'] == active_asg and len(asg['TargetGroupARNs']) > 0:
active.append(asg)
for a in active:
target_group_arns = a['TargetGroupARNs']
logging.info("Attaching auto scaling group to target group: {}".format(self.new_asg))
asg_client.attach_load_balancer_target_groups(
AutoScalingGroupName=self.new_asg,
TargetGroupARNs=target_group_arns
)
logging.info("Detaching auto scaling group from target group: {}".format(active_asg))
asg_client.detach_load_balancer_target_groups(
AutoScalingGroupName=active_asg,
TargetGroupARNs=target_group_arns
)
return