Skip to main content

CDK Construct for managing SSM Documents

Project description

CDK SSM Document

Source Test GitHub Docs

npm package PyPI package

Downloads npm PyPI

AWS CDK L3 construct for managing SSM Documents.

CloudFormation's support for SSM Documents currently is lacking updating functionality. Instead of updating a document, CFN will replace it. The old document is destroyed and a new one is created with a different name. This is problematic because:

  • When names potentially change, you cannot directly reference a document
  • Old versions are permanently lost

This construct provides document support in a way you'd expect it:

  • Changes on documents will cerate new versions
  • Versions cannot be deleted

Installation

This package has peer dependencies, which need to be installed along in the expected version.

For TypeScript/NodeJS, add these to your dependencies in package.json. For Python, add these to your requirements.txt:

  • cdk-ssm-document
  • aws-cdk-lib (^2.0.0)
  • cdk-iam-floyd (^0.300.0)
  • constructs (^10.0.0)

CDK compatibility

  • Version 3.x is compatible with the CDK v2.
  • Version 2.x is compatible with the CDK v1. There won't be regular updates for this.

Usage

Creating a document from a YAML or JSON file

# Example automatically generated from non-compiling source. May contain errors.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Document } from 'cdk-ssm-document';
import fs = require('fs');
import path = require('path');

export class TestStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props: cdk.StackProps) {
    super(scope, id, props);

    const file = path.join(__dirname, '../documents/hello-world.yml');
    new Document(this, 'SSM-Document-HelloWorld', {
      name: 'HelloWorld',
      content: fs.readFileSync(file).toString(),
    });
  }
}

Creating a document via inline definition

# Example automatically generated from non-compiling source. May contain errors.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Document } from 'cdk-ssm-document';
import fs = require('fs');
import path = require('path');

export class TestStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props: cdk.StackProps) {
    super(scope, id, props);

    new Document(this, 'SSM-Document-HelloWorld', {
      name: 'HelloWorld',
      content: {
        schemaVersion: '2.2',
        description: 'Echo Hello World!',
        parameters: {
          text: {
            default: 'Hello World!',
            description: 'Text to echo',
            type: 'String',
          },
        },
        mainSteps: [
          {
            name: 'echo',
            action: 'aws:runShellScript',
            inputs: {
              runCommand: ['echo "{{text}}"'],
            },
            precondition: {
              StringEquals: ['platformType', 'Linux'],
            },
          },
        ],
      },
    });
  }
}

Deploy all YAML/JSON files from a directory

# Example automatically generated from non-compiling source. May contain errors.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Document } from 'cdk-ssm-document';
import fs = require('fs');
import path = require('path');

export class TestStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props: cdk.StackProps) {
    super(scope, id, props);

    const dir = path.join(__dirname, '../documents');
    const files = fs.readdirSync(dir);

    for (const i in files) {
      const name = files[i];
      const shortName = name.split('.').slice(0, -1).join('.'); // removes file extension
      const file = `${dir}/${name}`;

      new Document(this, `SSM-Document-${shortName}`, {
        name: shortName,
        content: fs.readFileSync(file).toString(),
      });
    }
  }
}

Deploying many documents in a single stack

When you want to create multiple documents in the same stack, you will quickly exceed the SSM API rate limit. One ugly but working solution for this is to ensure that only a single document is created/updated at a time by adding resource dependencies. When document C depends on document B and B depends on document A, the documents will be created/updated in that order.

# Example automatically generated from non-compiling source. May contain errors.
const docA = new Document(this, 'doc-A', {...})
const docB = new Document(this, 'doc-B', {...})
const docC = new Document(this, 'doc-C', {...})

docC.node.addDependency(docB);
docB.node.addDependency(docA);

When looping through a directory of documents it could look like this:

# Example automatically generated from non-compiling source. May contain errors.
var last: Document | undefined = undefined;
for (const i in files) {
  const doc = new Document(this, `SSM-Document-${shortName}`, {...});
  if (typeof last !== 'undefined') {
    last.node.addDependency(doc);
  }
  last = doc;
}

Using the Lambda as a custom resource in CloudFormation - without CDK

If you're still not convinced to use the AWS CDK, you can still use the Lambda as a custom resource in your CFN template. Here is how:

  1. Create a zip file for the Lambda:

    To create a zip from the Lambda source run:

    lambda/build
    

    This will generate the file lambda/code.zip.

  2. Upload the Lambda function:

    Upload this zip file to an S3 bucket via cli, Console or however you like.

    Example via cli:

    aws s3 cp lambda/code.zip s3://example-bucket/code.zip
    
  3. Deploy a CloudFormation stack utilizing the zip as a custom resource provider:

    Example CloudFormation template:

    ---
    AWSTemplateFormatVersion: "2010-09-09"
    Resources:
      SSMDocExecutionRole:
        Type: AWS::IAM::Role
        Properties:
          RoleName: CFN-Resource-Custom-SSM-Document
          AssumeRolePolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Principal:
                  Service: lambda.amazonaws.com
                Action: sts:AssumeRole
          ManagedPolicyArns:
            - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
            - Ref: SSMDocExecutionPolicy
    
      SSMDocExecutionPolicy:
        Type: AWS::IAM::ManagedPolicy
        Properties:
          ManagedPolicyName: CFN-Resource-Custom-SSM-Document
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - ssm:ListDocuments
                  - ssm:ListTagsForResource
                Resource: "*"
              - Effect: Allow
                Action:
                  - ssm:CreateDocument
                  - ssm:AddTagsToResource
                Resource: "*"
                Condition:
                  StringEquals:
                    aws:RequestTag/CreatedByCfnCustomResource: CFN::Resource::Custom::SSM-Document
              - Effect: Allow
                Action:
                  - ssm:DeleteDocument
                  - ssm:DescribeDocument
                  - ssm:GetDocument
                  - ssm:ListDocumentVersions
                  - ssm:ModifyDocumentPermission
                  - ssm:UpdateDocument
                  - ssm:UpdateDocumentDefaultVersion
                  - ssm:AddTagsToResource
                  - ssm:RemoveTagsFromResource
                Resource: "*"
                Condition:
                  StringEquals:
                    aws:ResourceTag/CreatedByCfnCustomResource: CFN::Resource::Custom::SSM-Document
    
      SSMDocFunction:
        Type: AWS::Lambda::Function
        Properties:
          FunctionName: CFN-Resource-Custom-SSM-Document-Manager
          Code:
            S3Bucket: example-bucket
            S3Key: code.zip
          Handler: index.handler
          Runtime: nodejs10.x
          Timeout: 3
          Role: !GetAtt SSMDocExecutionRole.Arn
    
      MyDocument:
        Type: Custom::SSM-Document
        Properties:
          Name: MyDocument
          ServiceToken: !GetAtt SSMDocFunction.Arn
          StackName: !Ref AWS::StackName
          UpdateDefaultVersion: true # default: true
          Content:
            schemaVersion: "2.2"
            description: Echo Hello World!
            parameters:
              text:
                type: String
                description: Text to echo
                default: Hello World!
            mainSteps:
              - name: echo
                action: aws:runShellScript
                inputs:
                  runCommand:
                    - echo "{{text}}"
                precondition:
                  StringEquals:
                    - platformType
                    - Linux
          DocumentType: Command # default: Command
          TargetType: / # default: /
          Tags:
            CreatedByCfnCustomResource: CFN::Resource::Custom::SSM-Document # required, see above policy conditions
    

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cdk-ssm-document-3.0.0.tar.gz (354.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cdk_ssm_document-3.0.0-py3-none-any.whl (353.0 kB view details)

Uploaded Python 3

File details

Details for the file cdk-ssm-document-3.0.0.tar.gz.

File metadata

  • Download URL: cdk-ssm-document-3.0.0.tar.gz
  • Upload date:
  • Size: 354.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/50.3.0 requests-toolbelt/0.9.1 tqdm/4.50.0 CPython/3.7.9

File hashes

Hashes for cdk-ssm-document-3.0.0.tar.gz
Algorithm Hash digest
SHA256 08dbd8ece7d2c8baba23b703c60f74c9de152c11ae3d1db5a246f648778ae841
MD5 abc632224e5b707c638377e22a0c2275
BLAKE2b-256 780134db249c0a2b5edad62b0388b4a3f69f21192cd4aeba8249ce9d9ca5fccd

See more details on using hashes here.

File details

Details for the file cdk_ssm_document-3.0.0-py3-none-any.whl.

File metadata

  • Download URL: cdk_ssm_document-3.0.0-py3-none-any.whl
  • Upload date:
  • Size: 353.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/50.3.0 requests-toolbelt/0.9.1 tqdm/4.50.0 CPython/3.7.9

File hashes

Hashes for cdk_ssm_document-3.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 05c2b417788338c8c810e4dc2690ddf96d428691ede73edd726f1c2f9de27b48
MD5 d30d69f012014a4545b6868506ebc42c
BLAKE2b-256 f62b694d5c1479630d94e0c8101abcd47980a22be0c09dce7ed5fd34c967d4e8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page