CloudFormation - 总是使用最新的AMI

18

这篇博客文章Query for the latest Amazon Linux AMI IDs using AWS Systems Manager Parameter Store | AWS Compute Blog介绍了如何在CloudFormation模板中引用发行版的最新版本。

# Use public Systems Manager Parameter
Parameters:
  LatestAmiId:
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: '/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2'

Resources:
 Instance:
    Type: 'AWS::EC2::Instance'
    Properties:
      ImageId: !Ref LatestAmiId

对于其他发行版(如RedHat和CentOS),这将如何运作?使用哪个参数存储路径?

2个回答

17

正如@John Rotenstein所说,SSM似乎只有Amazon Linux AMI。但是您仍然可以使用DescribeImages获取其他AMI。然后,您可以创建一个自定义资源来查询它,并将结果用作AMI值。

Resources:
  DescribeImagesRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: DescribeImages
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Action: ec2:DescribeImages
                Effect: Allow
                Resource: "*"
  GetLatestAMI:
    Type: AWS::Lambda::Function
    Properties:
      Runtime: python3.6
      Handler: index.handler
      Role: !Sub ${DescribeImagesRole.Arn}
      Timeout: 60
      Code:
        ZipFile: |
          import boto3
          import cfnresponse
          import json
          import traceback

          def handler(event, context):
            try:
              response = boto3.client('ec2').describe_images(
                  Owners=[event['ResourceProperties']['Owner']],
                  Filters=[
                    {'Name': 'name', 'Values': [event['ResourceProperties']['Name']]},
                    {'Name': 'architecture', 'Values': [event['ResourceProperties']['Architecture']]},
                    {'Name': 'root-device-type', 'Values': ['ebs']},
                  ],
              )

              amis = sorted(response['Images'],
                            key=lambda x: x['CreationDate'],
                            reverse=True)
              id = amis[0]['ImageId']

              cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, id)
            except:
              traceback.print_last()
              cfnresponse.send(event, context, cfnresponse.FAIL, {}, "ok")
  CentOSAmi:
    Type: Custom::FindAMI
    Properties:
      ServiceToken: !Sub ${GetLatestAMI.Arn}
      Owner: "679593333241"
      Name: "CentOS Linux 7 x86_64 HVM EBS *"
      Architecture: "x86_64"
您需要更新CentOSAmi中的值,以便找到正确的AMI,然后使用输出结果:
ImageId: !Ref CentOSAmi

3

这些参数存储AMI值似乎是由AWS手动管理的。我只发现以下参考资料:

更新:现在有更多可用的服务:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接