AWS Cloudformation以启用Performance Insights

时间:2018-02-22 00:25:32

标签: amazon-rds amazon-cloudformation

是否有人知道CloudFormation是否提供Performance Insights(适用于AWS Aurora)? 它在Terraform performance_insights_enabled中可用,但我无法在CloudFormation中找到相应的内容。

由于

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:1)

当前无法使用本机CFN,但是由于您可以在CFN模板(即Type: 'Custom::EnablePerformanceInsights')中执行自定义Lambda代码,因此可以在模板中执行以下操作:

  EnablePerformanceInsights:
    Type: 'Custom::EnablePerformanceInsights'
    Properties:
      ServiceToken: !Sub 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:enable-performance-insights-${LambdaStackGuid}'
      DBInstanceId: !Ref 'RDSInstance'
      PerformanceInsightsKMSKeyId: !Ref 'DefaultKMSKeyArn'
      PerformanceInsightsRetentionPeriod: 7

您的职能和角色定义可能是:

  ModifyRDSInstanceLambdaRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service:
            - 'lambda.amazonaws.com'
          Action:
          - 'sts:AssumeRole'
      Path: '/'
      Policies:
      - PolicyName: 'AmazonLambdaServicePolicy'
        PolicyDocument:
          Version: '2012-10-17'
          Statement:
          - Effect: Allow
            Action:
            - 'logs:CreateLogGroup'
            - 'logs:CreateLogStream'
            - 'logs:PutLogEvents'
            - 'rds:*'
            - 'kms:*'
            Resource: '*'

  EnablePerformanceInsightsLambda:
    Type: 'AWS::Lambda::Function'
    Properties:
      FunctionName: !Join [ '-', [ 'enable-performance-insights', !Select [ 2, !Split [ '/', !Ref 'AWS::StackId' ]]]]
      Handler: 'enable-performance-insights.lambda_handler'
      Code:
        S3Bucket: !Ref 'S3Bucket'
        S3Key: !Sub 'lambda-functions/enable-performance-insights.zip'
      Runtime: python2.7
      Role: !Ref 'ModifyRDSInstanceLambdaRole'
      Description: 'Enable RDS Performance Insights.'
      Timeout: 300

功能代码将导入boto3来处理AWS API:

import cfnresponse # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html
import boto3
import os
from retrying import retry
from uuid import uuid4


resource_id = str(uuid4())
region = os.getenv('AWS_REGION')
profile = os.getenv('AWS_PROFILE')

if profile:
    session = boto3.session.Session(profile_name=profile)
    boto3.setup_default_session(profile_name=profile)

client = boto3.client('rds', region_name=region)


@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000, stop_max_delay=300000)
def enable_performance_insights(DBInstanceId=None, PerformanceInsightsKMSKeyId=None, PerformanceInsightsRetentionPeriod=None):
    response = client.modify_db_instance(
        DBInstanceIdentifier=DBInstanceId,
        EnablePerformanceInsights=True,
        PerformanceInsightsKMSKeyId=PerformanceInsightsKMSKeyId,
        PerformanceInsightsRetentionPeriod=int(PerformanceInsightsRetentionPeriod),
        ApplyImmediately=True
    )
    assert response
    return response


@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000, stop_max_delay=300000)
def disable_performance_insights(DBInstanceId=None):
    response = client.modify_db_instance(
        DBInstanceIdentifier=DBInstanceId,
        EnablePerformanceInsights=False,
        ApplyImmediately=True
    )
    assert response
    return response


def lambda_handler(event, context):
    print(event, context, boto3.__version__)

    try:
        DBInstanceIds = event['ResourceProperties']['DBInstanceId'].split(',')
    except:
        DBInstanceIds = []

    PerformanceInsightsKMSKeyId = event['ResourceProperties']['PerformanceInsightsKMSKeyId']
    PerformanceInsightsRetentionPeriod = event['ResourceProperties']['PerformanceInsightsRetentionPeriod']

    try:
        ResourceId = event['PhysicalResourceId']
    except:
        ResourceId = resource_id

    responseData = {}

    if event['RequestType'] == 'Delete':
        try:
            for DBInstanceId in DBInstanceIds:
                response = disable_performance_insights(DBInstanceId=DBInstanceId)
                print(response)
        except Exception as e:
            print(e)

        cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, physicalResourceId=ResourceId)
        return

    try:
        for DBInstanceId in DBInstanceIds:
            response = enable_performance_insights(
                DBInstanceId=DBInstanceId,
                PerformanceInsightsKMSKeyId=PerformanceInsightsKMSKeyId,
                PerformanceInsightsRetentionPeriod=PerformanceInsightsRetentionPeriod
            )
            print(response)
    except Exception as e:
        print(e)

    cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, physicalResourceId=ResourceId)

(从工作堆栈中复制/编辑)