Skip to main content

CDK Construct for managing SSM Documents

Project description

CDK SSM Document

CDK docs npm version PyPI version NuGet version GitHub

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 saved with a different name. This is problematic because:

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

This construct provides document support in a way it should have been implemented in the first place:

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

Usage

Creating a document from a YAML or JSON file

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.core as cdk
from cdk_ssm_document import Document
import fs as fs
import path as path

class TestStack(cdk.Stack):
    def __init__(self, scope, id, *, description=None, env=None, stackName=None, tags=None):
        super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags)

        file = path.join(__dirname, "../documents/hello-world-yaml.yml")
        Document(self, "SSM-Document-HelloWorld",
            name="HelloWorld",
            content=fs.read_file_sync(file).to_string()
        )

Creating a document via inline definition

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.core as cdk
from cdk_ssm_document import Document
import fs as fs
import path as path

class TestStack(cdk.Stack):
    def __init__(self, scope, id, *, description=None, env=None, stackName=None, tags=None):
        super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags)

        Document(self, "SSM-Document-HelloWorld",
            name="HelloWorld",
            content={
                "schema_version": "2.2",
                "description": "Echo Hello World!",
                "parameters": {
                    "text": {
                        "default": "Hello World!",
                        "description": "Text to echo",
                        "type": "String"
                    }
                },
                "main_steps": [{
                    "name": "echo",
                    "action": "aws:runShellScript",
                    "inputs": {
                        "run_command": ["echo \"{{text}}\""
                        ]
                    },
                    "precondition": {
                        "StringEquals": ["platformType", "Linux"
                        ]
                    }
                }
                ]
            }
        )

Deploy all YAML/JSON files from a directory

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.core as cdk
from cdk_ssm_document import Document
import fs as fs
import path as path

class TestStack(cdk.Stack):
    def __init__(self, scope, id, *, description=None, env=None, stackName=None, tags=None):
        super().__init__(scope, id, description=description, env=env, stackName=stackName, tags=tags)

        dir = path.join(__dirname, "../documents")
        files = fs.readdir_sync(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(),
                    });
                }

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 fie 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/CreatedBy: 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/CreatedBy: 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:
            CreatedBy: CFN::Resource::Custom::SSM-Document # required, see above policy conditions
    

Roadmap

  • Automated Tests
  • Tagging support in a more standardized way

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-0.2.0.tar.gz (37.7 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-0.2.0-py3-none-any.whl (35.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: cdk-ssm-document-0.2.0.tar.gz
  • Upload date:
  • Size: 37.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.6.0 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.7.5

File hashes

Hashes for cdk-ssm-document-0.2.0.tar.gz
Algorithm Hash digest
SHA256 02f74b2d53cd8287bfb17dd2f0f1d554a919dc5d49e42fc0e7dbc8821ebbd251
MD5 f916af8073505c2617b68103ebbde2d7
BLAKE2b-256 1482e115f238fa498a6b9cba698ce17ec39e5756dd04023c3080b9c59fcf9887

See more details on using hashes here.

File details

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

File metadata

  • Download URL: cdk_ssm_document-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 35.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.6.0 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.7.5

File hashes

Hashes for cdk_ssm_document-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f1ae4e19e169db86d115a6bb714a89361ff006d98ff05968ccca15dc94fab950
MD5 dd5104824a67bd45c1ab16ccc3d269db
BLAKE2b-256 be984c36a68e40c9fad42719d6f617ce1d3420603e021c7d2fbbfb1a23423b90

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