diff --git a/ecs-cluster-infrastructure-instance-refresh-lambda.tf b/ecs-cluster-infrastructure-instance-refresh-lambda.tf index 50aac4c..60cdd04 100644 --- a/ecs-cluster-infrastructure-instance-refresh-lambda.tf +++ b/ecs-cluster-infrastructure-instance-refresh-lambda.tf @@ -98,7 +98,9 @@ resource "aws_lambda_function" "ecs_cluster_infrastructure_instance_refresh" { environment { variables = { - asgName = aws_autoscaling_group.infrastructure_ecs_cluster[0].name + asgName = aws_autoscaling_group.infrastructure_ecs_cluster[0].name + launchTemplateName = aws_launch_template.infrastructure_ecs_cluster[0].name + amiVersion = local.infrastructure_ecs_cluster_ami_version } } diff --git a/ecs-cluster-infrastructure.tf b/ecs-cluster-infrastructure.tf index 86f9e90..ec62f0a 100644 --- a/ecs-cluster-infrastructure.tf +++ b/ecs-cluster-infrastructure.tf @@ -176,7 +176,7 @@ resource "aws_autoscaling_group" "infrastructure_ecs_cluster" { launch_template { id = aws_launch_template.infrastructure_ecs_cluster[0].id - version = aws_launch_template.infrastructure_ecs_cluster[0].latest_version + version = "$Latest" } vpc_zone_identifier = local.infrastructure_ecs_cluster_publicly_avaialble ? [ diff --git a/lambdas/ecs-asg-instance-refresh/function.py b/lambdas/ecs-asg-instance-refresh/function.py index be2592a..7283afd 100644 --- a/lambdas/ecs-asg-instance-refresh/function.py +++ b/lambdas/ecs-asg-instance-refresh/function.py @@ -3,9 +3,47 @@ import os asgName = os.environ['asgName'] +launchTemplateName = os.environ['launchTemplateName'] +amiVersion = os.environ['amiVersion'] def lambda_handler(event, context): asgClient = boto3.client('autoscaling') + ec2Client = boto3.client('ec2') + + # Update launch template to use the latest AMI + response = ec2Client.describe_images( + Owners=['amazon'], + Filters=[ + {'Name': 'name', 'Values': [amiVersion]}, + {'Name': 'state', 'Values': ['available']}, + {'Name': 'architecture', 'Values': ['x86_64']} + ] + ) + + images = sorted( + response['Images'], + key=lambda x: x['CreationDate'], + reverse=True + ) + if not images: + raise Exception("No AMIs found!") + + latest_ami_id = images[0]['ImageId'] + print(f"Latest ECS-optimized AMI: {latest_ami_id}") + + try: + response = ec2Client.modify_launch_template( + LaunchTemplateName=launchTemplateName, + LaunchTemplateData={ + 'ImageId': latest_ami_id + } + ) + print(f"Launch template updated successfully: {response}") + except Exception as e: + print(f"Error updating launch template: {e}") + raise + + # Start instance refresh try: response = asgClient.start_instance_refresh( AutoScalingGroupName=asgName,