|
| 1 | +# Copyright 2025 The MathWorks, Inc. |
| 2 | +AWSTemplateFormatVersion: '2010-09-09' |
| 3 | + |
| 4 | +Transform: AWS::LanguageExtensions |
| 5 | + |
| 6 | +Description: 'MathWorks Reference Architectures: AMI Copy Template - Copies a specified AMI from a source region into the current region.' |
| 7 | + |
| 8 | +Metadata: |
| 9 | + AWS::CloudFormation::Interface: |
| 10 | + ParameterGroups: |
| 11 | + - Label: |
| 12 | + default: "AMI Copy Configuration" |
| 13 | + Parameters: |
| 14 | + - SourceAmiId |
| 15 | + - SourceRegion |
| 16 | + - AmiName |
| 17 | + - ReferenceTag |
| 18 | + - MWTemplateUrl |
| 19 | + ParameterLabels: |
| 20 | + SourceAmiId: |
| 21 | + default: "Source AMI ID" |
| 22 | + SourceRegion: |
| 23 | + default: "Source Region" |
| 24 | + AmiName: |
| 25 | + default: "AMI Name" |
| 26 | + ReferenceTag: |
| 27 | + default: "Link to reference documentation for the copied AMI" |
| 28 | + MWTemplateUrl: |
| 29 | + default: "MathWorks Reference Architecture Template URL." |
| 30 | + |
| 31 | +Parameters: |
| 32 | + SourceAmiId: |
| 33 | + Type: String |
| 34 | + Description: The ID of the AMI to copy from the source region. |
| 35 | + AllowedPattern: ^ami-[a-f0-9]{8,17}$ |
| 36 | + ConstraintDescription: Must be a valid AMI ID (e.g., ami-xxxxxxxxxxxxxxxxx). |
| 37 | + |
| 38 | + SourceRegion: |
| 39 | + Type: String |
| 40 | + Description: The AWS region where the source AMI resides. |
| 41 | + AllowedPattern: ^[a-z-]+-\d{1}$ |
| 42 | + |
| 43 | + AmiName: |
| 44 | + Type: String |
| 45 | + Description: Name for the copied AMI. |
| 46 | + Default: '' |
| 47 | + ReferenceTag: |
| 48 | + Type: String |
| 49 | + Description: Optional reference link saved as tag on the copied AMI. |
| 50 | + Default: '' |
| 51 | + MWTemplateUrl: |
| 52 | + Type: String |
| 53 | + Description: >- |
| 54 | + (Optional) S3 URL of MathWorks Reference Architecture CFT that the copied AMI will be used with. |
| 55 | + Default: '' |
| 56 | + |
| 57 | +Resources: |
| 58 | + AmiCopyLambda: |
| 59 | + Type: AWS::Lambda::Function |
| 60 | + Properties: |
| 61 | + Code: |
| 62 | + ZipFile: | |
| 63 | + import boto3 |
| 64 | + import cfnresponse |
| 65 | +
|
| 66 | + def lambda_handler(event, context): |
| 67 | + response_data = {} |
| 68 | + try: |
| 69 | + if event['RequestType'] == 'Create': |
| 70 | + props = event['ResourceProperties'] |
| 71 | + source_ami = props['SourceAmiId'] |
| 72 | + source_region = props['SourceRegion'] |
| 73 | + target_name = props.get('AmiName', '') |
| 74 | + reference = props['ReferenceTag'] |
| 75 | +
|
| 76 | + ec2_source = boto3.client('ec2', region_name=source_region) |
| 77 | + ec2_dest = boto3.client('ec2') |
| 78 | +
|
| 79 | + images = ec2_source.describe_images(ImageIds=[source_ami])['Images'] |
| 80 | + if not images: |
| 81 | + raise Exception(f"Source AMI {source_ami} not found in region {source_region}") |
| 82 | + source_name = images[0].get('Name', f"Copied-{source_ami}") |
| 83 | + description = f"Copied from {source_ami} {source_name} in {source_region}" |
| 84 | + |
| 85 | + if not target_name: |
| 86 | + target_name = f"Copied from {source_name}" |
| 87 | + if not reference: |
| 88 | + reference = "https://github.com/mathworks-ref-arch/iac-building-blocks/tree/main/aws/ami-copy-lambda" |
| 89 | +
|
| 90 | + response = ec2_dest.copy_image( |
| 91 | + Name=target_name, |
| 92 | + SourceImageId=source_ami, |
| 93 | + SourceRegion=source_region, |
| 94 | + Description=description |
| 95 | + ) |
| 96 | +
|
| 97 | + copied_ami_id = response['ImageId'] |
| 98 | + response_data['CopiedAmiId'] = copied_ami_id |
| 99 | +
|
| 100 | + ec2_dest.create_tags( |
| 101 | + Resources=[copied_ami_id], |
| 102 | + Tags=[ |
| 103 | + {'Key': 'SourceAmiId', 'Value': source_ami}, |
| 104 | + {'Key': 'Reference', 'Value': reference} |
| 105 | + ] |
| 106 | + ) |
| 107 | + cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data) |
| 108 | + else: |
| 109 | + print(f"No action for event type: {event['RequestType']}") |
| 110 | + cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data) |
| 111 | + except Exception as e: |
| 112 | + response_data['Error'] = str(e) |
| 113 | + cfnresponse.send(event, context, cfnresponse.FAILED, response_data) |
| 114 | +
|
| 115 | + Handler: index.lambda_handler |
| 116 | + Runtime: python3.13 |
| 117 | + Timeout: 300 |
| 118 | + Role: !GetAtt AmiCopyLambdaRole.Arn |
| 119 | + |
| 120 | + AmiCopyLambdaRole: |
| 121 | + Type: AWS::IAM::Role |
| 122 | + Properties: |
| 123 | + AssumeRolePolicyDocument: |
| 124 | + Version: '2012-10-17' |
| 125 | + Statement: |
| 126 | + - Effect: Allow |
| 127 | + Principal: |
| 128 | + Service: [lambda.amazonaws.com] |
| 129 | + Action: ['sts:AssumeRole'] |
| 130 | + Path: / |
| 131 | + Policies: |
| 132 | + - PolicyName: ami-copy-lambda-policy |
| 133 | + PolicyDocument: |
| 134 | + Version: '2012-10-17' |
| 135 | + Statement: |
| 136 | + - Sid: CloudWatchLogs |
| 137 | + Effect: Allow |
| 138 | + Action: |
| 139 | + - logs:CreateLogGroup |
| 140 | + - logs:CreateLogStream |
| 141 | + - logs:PutLogEvents |
| 142 | + Resource: '*' |
| 143 | + - Sid: AmiCopy |
| 144 | + Effect: Allow |
| 145 | + Action: |
| 146 | + - ec2:CopyImage |
| 147 | + - ec2:DescribeImages |
| 148 | + Resource: '*' |
| 149 | + - Sid: AmiTagging |
| 150 | + Effect: Allow |
| 151 | + Action: |
| 152 | + - ec2:CreateTags |
| 153 | + Resource: '*' |
| 154 | + |
| 155 | + AmiCopyTrigger: |
| 156 | + Type: Custom::AmiCopyLambdaTrigger |
| 157 | + DependsOn: |
| 158 | + - AmiCopyLambda |
| 159 | + - AmiCopyLambdaRole |
| 160 | + Properties: |
| 161 | + ServiceToken: !GetAtt AmiCopyLambda.Arn |
| 162 | + SourceAmiId: !Ref SourceAmiId |
| 163 | + SourceRegion: !Ref SourceRegion |
| 164 | + AmiName: !Ref AmiName |
| 165 | + ReferenceTag: !Ref ReferenceTag |
| 166 | + |
| 167 | +Outputs: |
| 168 | + CopiedAmiId: |
| 169 | + Description: The ID of the copied AMI in the current region. |
| 170 | + Value: !GetAtt AmiCopyTrigger.CopiedAmiId |
| 171 | + CopiedAmiConsoleLink: |
| 172 | + Description: Console link to view the copied AMI. You can use this link to check the readiness of the copied AMI. |
| 173 | + Value: !Sub |
| 174 | + - "https://console.aws.amazon.com/ec2/home?region=${AWS::Region}#ImageDetails:imageId=${CopiedAmiId}" |
| 175 | + - CopiedAmiId: !GetAtt AmiCopyTrigger.CopiedAmiId |
| 176 | + LaunchClusterWithCopiedAmi: |
| 177 | + Condition: ShowDeploymentLink |
| 178 | + Description: Launch a new cluster stack using the copied AMI in your account. This link will open the CloudFormation console to create a new stack, with the custom AMI ID prepopulated. You should only click this link when the AMI is ready, which may take 5-15 minutes. |
| 179 | + Value: !Sub |
| 180 | + - "https://${AWS::Region}.console.aws.amazon.com/cloudformation/home?region=${AWS::Region}#/stacks/create/review?templateURL=${MWTemplateUrl}¶m_customAmiId=${CopiedAmiId}¶m_InstanceAmiCustom=${CopiedAmiId}" |
| 181 | + - |
| 182 | + MWTemplateUrl: !Ref MWTemplateUrl |
| 183 | + CopiedAmiId: !GetAtt AmiCopyTrigger.CopiedAmiId |
| 184 | + |
| 185 | +Conditions: |
| 186 | + ShowDeploymentLink: !Not [!Equals [!Ref MWTemplateUrl, ""]] |
0 commit comments