AWSTemplateFormatVersion: '2010-09-09'
Description: This example template describes a custom AWS KMS customer master key
  (CMK). **WARNING** This template creates AWS resources. You will be billed for the
  AWS resources used if you create a stack from this template.
Parameters:
  CMKAlias:
    AllowedPattern: '[-a-zA-Z0-9/_]+'
    ConstraintDescription: please specify a valid alias.
    Description: 'Please specify the alias for the KMS CMK: maximum = 256 characters,
      use alphanumeric and ''_-/'' characters.'
    MaxLength: '256'
    MinLength: '1'
    Type: String
  CMKDescription:
    ConstraintDescription: please specify a valid description.
    Description: 'Please specify the description for the KMS CMK: maximum = 8192 characters.'
    MaxLength: '8192'
    MinLength: '1'
    Type: String
Resources:
  Key:
    Type: AWS::KMS::Key
    Properties:
      Description: !Ref 'CMKDescription'
      KeyPolicy:
        Id: my-example-key-policy
        Statement:
        - Action:
          - kms:Create*
          - kms:Describe*
          - kms:Enable*
          - kms:List*
          - kms:Put*
          - kms:Update*
          - kms:Revoke*
          - kms:Disable*
          - kms:Get*
          - kms:Delete*
          - kms:ScheduleKeyDeletion
          - kms:CancelKeyDeletion
          Effect: Allow
          Principal:
            AWS: !Sub 'arn:aws:iam::${AWS::AccountId}:root'
          Resource: '*'
          Sid: Allow administration of the key
        - Action:
          - kms:Encrypt
          - kms:Decrypt
          - kms:ReEncrypt*
          - kms:GenerateDataKey*
          - kms:DescribeKey
          Effect: Allow
          Principal:
            AWS: !Sub 'arn:aws:iam::${AWS::AccountId}:root'
          Resource: '*'
          Sid: Allow use of the key
        Version: '2012-10-17'
  KeyAlias:
    Type: AWS::KMS::Alias
    Properties:
      AliasName: !Sub 'alias/${CMKAlias}'
      TargetKeyId: !Ref 'Key'
Outputs:
  CMKARN:
    Description: Amazon Resource Name (ARN) of the custom KMS CMK.
    Export:
      Name: !Sub '${AWS::StackName}-CMKARN'
    Value: !Sub 'arn:aws:kms:${AWS::Region}:${AWS::AccountId}:key/${Key}'
  CMKID:
    Description: ID of the custom KMS CMK created by this stack.
    Value: !Ref 'Key'

