CloudFormation - всегда используйте последнюю версию AMI

Сообщение в блоге Запросить последние идентификаторы AMI Amazon Linux с помощью хранилища параметров AWS Systems Manager | Блог AWS Compute описывает, как всегда ссылаться на последнюю версию дистрибутива в шаблоне 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? Какой путь к хранилищу параметров использовать?


person benji    schedule 02.04.2019    source источник


Ответы (2)


Как сказал @John Rotenstein, SSM, похоже, имеет только AMI Amazon Linux. Но вы все равно можете получить другие с помощью DescribeImages. Затем вы можете создать настраиваемый ресурс, чтобы запросить его для вас и использовать результат в качестве значения 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
person kichik    schedule 03.04.2019

Эти значения AMI хранилища параметров, по-видимому, вручную управляются AWS. Я нашел только ссылки на:

person John Rotenstein    schedule 02.04.2019