GithubHelp home page GithubHelp logo

udondan / cdk-ec2-key-pair Goto Github PK

View Code? Open in Web Editor NEW
94.0 4.0 21.0 763 KB

AWS CDK L3 construct for managing EC2 Key Pairs

License: Apache License 2.0

Makefile 4.79% Shell 0.37% TypeScript 92.24% JavaScript 2.60%
aws cdk aws-cdk aws-cdk-construct ec2 ec2-key-pair cloudformation cloudformation-custom-resource hacktoberfest

cdk-ec2-key-pair's Introduction

CDK EC2 Key Pair

Source Test GitHub Docs

npm package PyPI package

Downloads npm PyPI

AWS CDK L3 construct for managing EC2 Key Pairs.

Manages RSA and ED25519 Key Pairs in EC2 through a Lambda function.

Support for public key format in:

  • OpenSSH
  • ssh
  • PEM
  • PKCS#1
  • PKCS#8
  • RFC4253 (Base64 encoded)
  • PuTTY ppk

Note

Please be aware, CloudFormation now natively supports creating EC2 Key Pairs via AWS::EC2::KeyPair, so you can generally use CDK's own KeyPair construct. There are a few differences, though, and this is why the custom construct remains valuable:

  • Instead of SSM Parameter Store, keys are stored in AWS Secrets Manager
  • Secrets can be KMS encrypted - even different KMS keys for the private and public keys. Of course, SSM parameters can be encrypted too, CloudFormation just doesn't do it
  • Optionally, this construct can store and expose the public key, enabling the user to directly use it as input for other resources, e.g. for CloudFront signed urls

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-ec2-key-pair
  • aws-cdk-lib (^2.116.0)
  • constructs (^10.0.0)

Usage

import cdk = require('aws-cdk-lib');
import { Construct } from 'constructs';
import { KeyPair } from 'cdk-ec2-key-pair';

// ...

// Create the Key Pair
const key = new KeyPair(this, 'A-Key-Pair', {
  keyPairName: 'a-key-pair',
  description: 'This is a Key Pair',
  storePublicKey: true, // by default the public key will not be stored in Secrets Manager
});

// Grant read access to the private key to a role or user
key.grantReadOnPrivateKey(someRole);

// Grant read access to the public key to another role or user
key.grantReadOnPublicKey(anotherRole);

// Use Key Pair on an EC2 instance
new ec2.Instance(this, 'An-Instance', {
  keyPair: key,
  // ...
});

The private (and optionally the public) key will be stored in AWS Secrets Manager. The secret names by default are prefixed with ec2-ssh-key/. The private key is suffixed with /private, the public key is suffixed with /public. So in this example they will be stored as ec2-ssh-key/a-key-pair/private and ec2-ssh-key/a-key-pair/public.

To download the private key via AWS cli you can run:

aws secretsmanager get-secret-value \
  --secret-id ec2-ssh-key/a-key-pair/private \
  --query SecretString \
  --output text

Tag support

The construct supports tagging:

cdk.Tags.of(key).add('someTag', 'some value');

We also use tags to restrict update/delete actions to those, the construct created itself. The Lambda function, which backs the custom CFN resource, is not able to manipulate other keys/secrets. The tag we use for identifying these resources is CreatedByCfnCustomResource with value CFN::Resource::Custom::EC2-Key-Pair.

Updates

Since an EC2 KeyPair cannot be updated, you cannot change any property related to the KeyPair. The code has checks in place which will prevent any attempt to do so. If you try, the stack will end in a failed state. In that case you can safely continue the rollback in the AWS console and ignore the key resource.

You can, however, change properties that only relate to the secrets. These are the KMS keys used for encryption, the secretPrefix, description and removeKeySecretsAfterDays.

Encryption

Secrets in the AWS Secrets Manager by default are encrypted with the key alias/aws/secretsmanager.

To use a custom KMS key you can pass it to the Key Pair:

const kmsKey = new kms.Key(this, 'KMS-key');

const keyPair = new KeyPair(this, 'A-Key-Pair', {
  keyPairName: 'a-key-pair',
  kms: kmsKey,
});

This KMS key needs to be created in the same stack. You cannot use a key imported via ARN, because the keys access policy will need to be modified.

To use different KMS keys for the private and public key, use the kmsPrivateKey and kmsPublicKey instead:

const kmsKeyPrivate = new kms.Key(this, 'KMS-key-private');
const kmsKeyPublic = new kms.Key(this, 'KMS-key-public');

const keyPair = new KeyPair(this, 'A-Key-Pair', {
  keyPairName: 'a-key-pair',
  kmsPrivateKey: kmsKeyPrivate,
  kmsPublicKey: kmsKeyPublic,
});

Importing public key

You can create a key pair by importing the public key. Obviously, in this case the private key won't be available in secrets manager.

The public key has to be in OpenSSH format.

new KeyPair(this, 'Test-Key-Pair', {
  keyPairName: 'imported-key-pair',
  publicKey: 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCuMmbK...',
});

Using the key pair for CloudFront signed url/cookies

You can use this library for generating keys for CloudFront signed url/cookies.

Make sure to set publicKeyFormat to PublicKeyFormat.PEM as that is the format required for CloudFront. You also have to set exposePublicKey to true so you can actually get the public key.

const key = new KeyPair(this, 'Signing-Key-Pair', {
  keyPairName: 'CFN-signing-key',
  exposePublicKey: true,
  storePublicKey: true,
  publicKeyFormat: PublicKeyFormat.PEM,
});

const pubKey = new cloudfront.PublicKey(this, 'Signing-Public-Key', {
  encodedKey: key.publicKeyValue,
});
const trustedKeyGroupForCF = new cloudfront.KeyGroup(
  this,
  'Signing-Key-Group',
  {
    items: [pubKey],
  },
);

cdk-ec2-key-pair's People

Contributors

actions-user avatar ahammond avatar calleum avatar dependabot[bot] avatar lmammino avatar lokulin avatar renovate[bot] avatar tgjclearsight avatar udondan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

cdk-ec2-key-pair's Issues

Inconsistent names of name and keyPairName

Hi,

I was confused by the fact that the constructor property for the key name is still called name, but the access property is renamed to keyPairName. Also the release notes stated that the constructor property was renamed - or have I misunderstood something? It would be nice to have a consistent names to avoid this confusion.

Thanks!

Using this module in conjunction with aws_codepipeline renders cloudformation templates unusable

As in the title, when you utilize this module along with aws_codepipeline, if you render the cloudformation templates with "cdk synth", the resulting templates require you to set AssetParameters for the artifact hash, s3 bucket, and s3 version key. With no default value specified, the templates fail to install unless those values are set. While that may be possible programmatically, I haven't surmised how to generate those values from CDK.

cdk-iam-floyd considered harmful

When I try to use this construct in another construct, I end up in dependency hell because of cdk-iam-floyd. Would you accept a PR that removes it?

CDK version mismatch issues

Hi! Thank you for creating this library.

When doing our latest CI build it failed on yarn because:
error An unexpected error occurred: "expected hoisted manifest for \"cdk-ec2-key-pair#@aws-cdk/aws-lambda#@aws-cdk/aws-cloudwatch#@aws-cdk/core\"".

Googling this suggests removing yarn.lock will do, but it didnt. However, we were running pinned cdk versions 1.74.0 in our packages and there was a new version 1.75.0 available. Updating to 1.75.0 solved the issue.

It seems that this happened because cdk-ec2-key-pair has caret version dependencies on CDK libraries. CDK version mismatch keeps causing issues for us, which is why we pin them.

It hinders our use of this library as we generally do not wish to be forced to update to the newest cdk version everytime it is released (even though we keep pretty up to date)

edit: I had a suggestion to use peer dependencies instead but.. they were already there. Any ideas on how to solve this issue?

jsii.errors.JSIIError: Cannot redefine property: Symbol(__jsii__)

Hi, I'm using the Python version of the library.
Upon importing the construct using from cdk_ec2_key_pair import KeyPair I'm getting an error.
Here's the full output of cdk deploy:

jsii.errors.JavaScriptError: 
  TypeError: Cannot redefine property: Symbol(__jsii__)
      at Function.defineProperty (<anonymous>)
      at Object.tagJsiiConstructor (/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/jsii/_embedded/jsii/jsii-runtime.js:6488:12)
      at Kernel._addAssembly (/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/jsii/_embedded/jsii/jsii-runtime.js:7899:31)
      at Kernel.load (/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/jsii/_embedded/jsii/jsii-runtime.js:7669:14)
      at KernelHost.processRequest (/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/jsii/_embedded/jsii/jsii-runtime.js:7456:28)
      at KernelHost.run (/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/jsii/_embedded/jsii/jsii-runtime.js:7394:14)
      at Immediate._onImmediate (/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/jsii/_embedded/jsii/jsii-runtime.js:7397:37)
      at processImmediate (internal/timers.js:456:21)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "app.py", line 4, in <module>
    from cdk_region.cdk_region_stack import CdkRegionStack
  File "/Users/benfaingold/Projects/cdk-region/cdk_region/cdk_region_stack.py", line 5, in <module>
    from cdk_ec2_key_pair import KeyPair
  File "/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/cdk_ec2_key_pair/__init__.py", line 70, in <module>
    from ._jsii import *
  File "/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/cdk_ec2_key_pair/_jsii/__init__.py", line 16, in <module>
    import cdk_iam_floyd._jsii
  File "/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/cdk_iam_floyd/__init__.py", line 494, in <module>
    from ._jsii import *
  File "/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/cdk_iam_floyd/_jsii/__init__.py", line 13, in <module>
    __jsii_assembly__ = jsii.JSIIAssembly.load(
  File "/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/jsii/_runtime.py", line 43, in load
    _kernel.load(assembly.name, assembly.version, os.fspath(assembly_path))
  File "/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/jsii/_kernel/__init__.py", line 239, in load
    self.provider.load(LoadRequest(name=name, version=version, tarball=tarball))
  File "/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/jsii/_kernel/providers/process.py", line 333, in load
    return self._process.send(request, LoadResponse)
  File "/Users/benfaingold/Projects/cdk-region/.env/lib/python3.8/site-packages/jsii/_kernel/providers/process.py", line 321, in send
    raise JSIIError(resp.error) from JavaScriptError(resp.stack)
jsii.errors.JSIIError: Cannot redefine property: Symbol(__jsii__)
Subprocess exited with error 1

Can you help me understand why this is happening?

Private keypair doesn't save in Secrets Manager

Version 3.3.2. I'm generating a keypair as follows:

const cloudFrontKeyPair = new KeyPair(this, 'CloudFrontKeyPair', {
      name: 'resources-' + environmentPrefix,
      secretPrefix: <prefix>
      exposePublicKey: true,
      publicKeyFormat: PublicKeyFormat.PEM
    });

However, the private key isn't saved in SSM. The synthed cdk has the following statement:

  DemoServiceCloudFrontKeyPairEC2KeyPairresourcesdev<...>:
    Type: Custom::EC2-Key-Pair
    Properties:
      ServiceToken:
        Fn::GetAtt:
          - EC2KeyNameManagerLambda<...>
          - Arn
      Name: resources-dev
      Description: ""
      KmsPrivate: alias/aws/secretsmanager
      KmsPublic: alias/aws/secretsmanager
      PublicKey: ""
      StorePublicKey: false
      ExposePublicKey: true
      PublicKeyFormat: PEM
      RemoveKeySecretsAfterDays: 0
      SecretPrefix: <prefix>
      StackName: <stack>
      Tags:
        CreatedByCfnCustomResource: CFN::Resource::Custom::EC2-Key-Pair
    UpdateReplacePolicy: Delete
    DeletionPolicy: Delete
    Metadata:
      aws:cdk:path: <prefix>/EC2-Key-Pair-resources-dev/Default

but no AWS::SSM-type statements.

Add support for PEM public keys

This library can be useful also for creating key pairs for using signed urls for CloudFront.
The only thing needed is an option for having the public key in PEM format.
That's because CloudFormation for specifying public keys for signed url/cookie validation for CloudFront accepts just that format.

Tagging doesn't work

Hi,

I'm trying to add some tags to the generated secret in the SecretsManager and somehow can't get it to work in python. Any help will be highly appreciated.

Thanks!

The code is:

from aws_cdk import core
from cdk_ec2_key_pair import KeyPair


class KeyPairTestStack(core.Stack):
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        KeyPair(
            scope=self,
            id="hh",
            name="mykey",
            tags={
                "tag1": "value1",
                "tag2": "value2"
            }
        )


ENV_CC = core.Environment(account="xxx", region="eu-central-1")
app = core.App()
KeyPairTestStack(app, "myteststack", env=ENV_CC)
app.synth()

cdk synth generates me only "Created By" tag:

Resources:
  hhEC2KeyPairmykeyEDB74C8E:
    Type: Custom::EC2-Key-Pair
    Properties:
      ServiceToken:
        Fn::GetAtt:
          - EC2KeyNameManagerLambdaBE629145
          - Arn
      Name: mykey
      Description: ""
      KeyLength: 2048
      Kms: alias/aws/secretsmanager
      RemovePrivateKeyAfterDays: 0
      SecretPrefix: ec2-private-key/
      StackName: myteststack
      Tags:
        CreatedBy: CFN::Resource::Custom::EC2-Key-Pair
    UpdateReplacePolicy: Delete
    DeletionPolicy: Delete
    Metadata:
      aws:cdk:path: myteststack/hh/EC2-Key-Pair-mykey/Default
  EC2KeyPairManagerPolicyEBBC1576:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - ec2:CreateKeyPair
              - ec2:DeleteKeyPair
              - ec2:DescribeKeyPairs
            Effect: Allow
            Resource: "*"
          - Action: secretsmanager:ListSecrets
            Effect: Allow
            Resource: "*"
          - Action:
              - secretsmanager:CreateSecret
              - secretsmanager:TagResource
            Condition:
              StringLike:
                aws:RequestTag/CreatedBy: CFN::Resource::Custom::EC2-Key-Pair
            Effect: Allow
            Resource: "*"
          - Action:
              - secretsmanager:DeleteResourcePolicy
              - secretsmanager:DeleteSecret
              - secretsmanager:DescribeSecret
              - secretsmanager:GetResourcePolicy
              - secretsmanager:ListSecretVersionIds
              - secretsmanager:PutResourcePolicy
              - secretsmanager:PutSecretValue
              - secretsmanager:RestoreSecret
              - secretsmanager:UntagResource
              - secretsmanager:UpdateSecret
              - secretsmanager:UpdateSecretVersionStage
            Condition:
              StringLike:
                secretsmanager:ResourceTag/CreatedBy: CFN::Resource::Custom::EC2-Key-Pair
            Effect: Allow
            Resource: "*"
        Version: "2012-10-17"
      Description: Used by Lambda CFN-Resource-Custom-EC2-Key-Pair, which is a custom CFN resource, managing EC2 Key Pairs
      ManagedPolicyName: myteststack-CFN-Resource-Custom-EC2-Key-Pair
      Path: /
    Metadata:
      aws:cdk:path: myteststack/EC2-Key-Pair-Manager-Policy/Resource
  EC2KeyPairManagerRoleB243C519:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
        Version: "2012-10-17"
      Description: Used by Lambda CFN-Resource-Custom-EC2-Key-Pair, which is a custom CFN resource, managing EC2 Key Pairs
      ManagedPolicyArns:
        - Ref: EC2KeyPairManagerPolicyEBBC1576
        - Fn::Join:
            - ""
            - - "arn:"
              - Ref: AWS::Partition
              - :iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      RoleName: myteststack-CFN-Resource-Custom-EC2-Key-Pair
    Metadata:
      aws:cdk:path: myteststack/EC2-Key-Pair-Manager-Role/Resource
  EC2KeyNameManagerLambdaBE629145:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket:
          Ref: AssetParameterse50a85ce3b59c30e167fe1a3d4457c163479976cbc4d00d9db586785fa06d5a2S3BucketEAEA5028
        S3Key:
          Fn::Join:
            - ""
            - - Fn::Select:
                  - 0
                  - Fn::Split:
                      - "||"
                      - Ref: AssetParameterse50a85ce3b59c30e167fe1a3d4457c163479976cbc4d00d9db586785fa06d5a2S3VersionKeyE22B7168
              - Fn::Select:
                  - 1
                  - Fn::Split:
                      - "||"
                      - Ref: AssetParameterse50a85ce3b59c30e167fe1a3d4457c163479976cbc4d00d9db586785fa06d5a2S3VersionKeyE22B7168
      Handler: index.handler
      Role:
        Fn::GetAtt:
          - EC2KeyPairManagerRoleB243C519
          - Arn
      Runtime: nodejs10.x
      Description: "Custom CFN resource: Manage EC2 Key Pairs"
      FunctionName: myteststack-CFN-Resource-Custom-EC2-Key-Pair
      Timeout: 180
    DependsOn:
      - EC2KeyPairManagerRoleB243C519
    Metadata:
      aws:cdk:path: myteststack/EC2-Key-Name-Manager-Lambda/Resource
      aws:asset:path: asset.e50a85ce3b59c30e167fe1a3d4457c163479976cbc4d00d9db586785fa06d5a2.zip
      aws:asset:property: Code
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
      Modules: aws-cdk=1.73.0,@aws-cdk/assets=1.73.0,@aws-cdk/aws-applicationautoscaling=1.73.0,@aws-cdk/aws-autoscaling-common=1.73.0,@aws-cdk/aws-cloudformation=1.73.0,@aws-cdk/aws-cloudwatch=1.73.0,@aws-cdk/aws-codeguruprofiler=1.73.0,@aws-cdk/aws-ec2=1.73.0,@aws-cdk/aws-efs=1.73.0,@aws-cdk/aws-events=1.73.0,@aws-cdk/aws-iam=1.73.0,@aws-cdk/aws-kms=1.73.0,@aws-cdk/aws-lambda=1.73.0,@aws-cdk/aws-logs=1.73.0,@aws-cdk/aws-s3=1.73.0,@aws-cdk/aws-s3-assets=1.73.0,@aws-cdk/aws-sns=1.73.0,@aws-cdk/aws-sqs=1.73.0,@aws-cdk/aws-ssm=1.73.0,@aws-cdk/cloud-assembly-schema=1.73.0,@aws-cdk/core=1.73.0,@aws-cdk/cx-api=1.73.0,@aws-cdk/region-info=1.73.0,jsii-runtime=Python/3.7.7
    Metadata:
      aws:cdk:path: myteststack/CDKMetadata/Default
Parameters:
  AssetParameterse50a85ce3b59c30e167fe1a3d4457c163479976cbc4d00d9db586785fa06d5a2S3BucketEAEA5028:
    Type: String
    Description: S3 bucket for asset "e50a85ce3b59c30e167fe1a3d4457c163479976cbc4d00d9db586785fa06d5a2"
  AssetParameterse50a85ce3b59c30e167fe1a3d4457c163479976cbc4d00d9db586785fa06d5a2S3VersionKeyE22B7168:
    Type: String
    Description: S3 key for asset version "e50a85ce3b59c30e167fe1a3d4457c163479976cbc4d00d9db586785fa06d5a2"
  AssetParameterse50a85ce3b59c30e167fe1a3d4457c163479976cbc4d00d9db586785fa06d5a2ArtifactHash56A19821:
    Type: String
    Description: Artifact hash for asset "e50a85ce3b59c30e167fe1a3d4457c163479976cbc4d00d9db586785fa06d5a2"

Not Working with CDK v2 Project

SSIA.

CDK v2 is now stable.
https://github.com/aws/aws-cdk/releases/tag/v2.0.0
https://docs.aws.amazon.com/ja_jp/cdk/latest/guide/work-with-cdk-v2.html

$ npm install cdk-ec2-key-pair
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: **********@0.1.0
npm ERR! Found: [email protected]
npm ERR! node_modules/constructs
npm ERR!   constructs@"10.0.9" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer constructs@"^3.2.80" from [email protected]
npm ERR! node_modules/cdk-ec2-key-pair
npm ERR!   cdk-ec2-key-pair@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /home/******/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/******/.npm/_logs/2021-12-05T08_29_36_474Z-debug.log

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

github-actions
.github/workflows/publish.yml
  • actions/checkout v4
  • udondan/jsii-publish v0.15.0
  • udondan/jsii-publish v0.15.0
  • udondan/jsii-publish v0.15.0
  • udondan/jsii-publish v0.15.0
  • udondan/jsii-publish v0.15.0
.github/workflows/test.yml
  • actions/setup-node v3
  • actions/checkout v4
  • udondan/jsii-publish v0.15.0
  • udondan/jsii-publish v0.15.0
npm
lambda/package.json
  • aws-cloudformation-custom-resource ^3.1.1
  • node-forge 1.3.1
package.json
  • @types/node ^18.11.3
  • @types/aws-lambda ^8.10.92
  • @types/node-forge ^1.0.0
  • aws-cdk-lib ^2.0.0
  • aws-lambda ^1.0.7
  • @aws-sdk/client-ec2 ^3.398.0
  • @aws-sdk/client-secrets-manager ^3.398.0
  • jsii 5.2.8
  • jsii-pacmak 1.89.0
  • ts-node ^10.4.0
  • typescript ^5.2.2
  • constructs ^10.0.0
  • aws-cdk-lib ^2.0.0
  • constructs ^10.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

ssh key invalid format message

Hello,

thanks for this fantastic package.

When I download the private key from secrets manager and the connect to the instance I will get an error:

ssh -i root_key.pem ubuntu@myip
load pubkey "root_key.pem": invalid format

It still connects fine after this but what seems to resolve the issue is this command:

ssh-keygen -f root_key.pem -p -y

So even though I don't set a password the warning seems to be gone after connecting. Is that something you can do something about or is it an AWS SDK issue?

I got the hint here: https://serverfault.com/a/1025451

Omitting the -p option did not work like suggested here: I https://sjsadowski.com/invalid-format-ssh-key/

'Resource-Custom-EC2-Key-Pair' at 'roleName' failed to statisfy constraint

Hello, I get this error when I try to deploy it with NestedStack.

keyvault

in console:
MainStack | 6/9 | 5:57:20 PM | CREATE_FAILED | AWS::CloudFormation::Stack | app.NestedStack/app.NestedStackResource (appNestedStackappNestedStackResource9524848D) Embedded stack arn:aws:cloudformation:eu-central-1:60056366672 9:stack/MainStack-appNestedStackappNestedStackResource9524848D-7W6IBA0157RL/36f51f00-ade6-11ec-97e1-0aa0925c6abc was not successfully created: The following resource(s) failed to create: [EC2KeyPairManagerRoleB243C519].

v2.0.1 not working in GovCloud region

It looks like something in the EC2 Key Pair MAnager Policy is not getting set correctly for the "partition" .. It's defaulting to the aws commercial instead of pulling the aws-gov or whatever the partition label should be... Is this something in this code base or should I escalate this to the AWS CDK team?

17:30:13   0/8 | 10:30:11 PM | UPDATE_FAILED        | AWS::IAM::ManagedPolicy                   | EC2-Key-Pair-Manager-Policy (EC2KeyPairManagerPolicyEBBC1576) Partition "aws" is not valid for resource "arn:aws:ec2:*:*:key-pair/*". (Service: AmazonIdentityManagement; Status Code: 400; Error Code: MalformedPolicyDocument; Request ID: 5aea5c20-43e0-4ec5-9bcf-a9f8f92fde99; Proxy: null)
17:30:13  	new ManagedPolicy (/tmp/jsii-kernel-9ZDg2k/node_modules/@aws-cdk/aws-iam/lib/managed-policy.js:35:26)
17:30:13  	\_ KeyPair.ensureLambda (/tmp/jsii-kernel-9ZDg2k/node_modules/cdk-ec2-key-pair/lib/index.js:125:24)
17:30:13  	\_ new KeyPair (/tmp/jsii-kernel-9ZDg2k/node_modules/cdk-ec2-key-pair/lib/index.js:74:28)
17:30:13  	\_ /usr/local/lib/python3.7/site-packages/jsii/_embedded/jsii/jsii-runtime.js:3621:49
17:30:13  	\_ Kernel._wrapSandboxCode (/usr/local/lib/python3.7/site-packages/jsii/_embedded/jsii/jsii-runtime.js:4105:16)
17:30:13  	\_ Kernel._create (/usr/local/lib/python3.7/site-packages/jsii/_embedded/jsii/jsii-runtime.js:3621:26)
17:30:13  	\_ Kernel.create (/usr/local/lib/python3.7/site-packages/jsii/_embedded/jsii/jsii-runtime.js:3356:21)
17:30:13  	\_ KernelHost.processRequest (/usr/local/lib/python3.7/site-packages/jsii/_embedded/jsii/jsii-runtime.js:13162:28)
17:30:13  	\_ KernelHost.run (/usr/local/lib/python3.7/site-packages/jsii/_embedded/jsii/jsii-runtime.js:13100:14)
17:30:13  	\_ Immediate._onImmediate (/usr/local/lib/python3.7/site-packages/jsii/_embedded/jsii/jsii-runtime.js:13103:37)
17:30:13  	\_ processImmediate (internal/timers.js:461:21)

I see the cdk.out json cloudformation for that resource does indeed show the lack of partition awareness...

   "EC2KeyPairManagerPolicyEBBC1576": {
      "Type": "AWS::IAM::ManagedPolicy",
      "Properties": {
        "PolicyDocument": {
          "Statement": [
            {
              "Action": "ec2:DescribeKeyPairs",
              "Effect": "Allow",
              "Resource": "*"
            },
            {
              "Action": [
                "ec2:CreateKeyPair",
                "ec2:CreateTags"
              ],
              "Condition": {
                "StringLike": {
                  "aws:RequestTag/CreatedByCfnCustomResource": "CFN::Resource::Custom::EC2-Key-Pair"
                }
              },
              "Effect": "Allow",
              "Resource": "arn:aws:ec2:*:*:key-pair/*"
            },
            {
              "Action": [
                "ec2:CreateTags",
                "ec2:DeleteKeyPair",
                "ec2:DeleteTags"
              ],
              "Condition": {
                "StringLike": {
                  "ec2:ResourceTag/CreatedByCfnCustomResource": "CFN::Resource::Custom::EC2-Key-Pair"
                }
              },
              "Effect": "Allow",
              "Resource": "arn:aws:ec2:*:*:key-pair/*"
            },

[question] Is there a way to download the key to do ssh

Hi, I'm modifying the greegrass workshop to handle Java instead of python for internal education. I would like to automate the deployment as much as possible and hence auto create key (if not existent) to use with the two ec2 instances (greengrass and node red).

You project is spot on for me, however is there a way to download the keys in order to do ssh to the ec2 instances?

(around the same functionality as aws ec2 create-key-pair --key-name ee-default-keypair.pem | jq -r ".KeyMaterial" > ee-default-keypair.pem if it is possible)

Cheers,
Mario

IAM Role name too long

Hi,

thanks for the great work! We have the problem that we are hitting the 64 chars limitation for the name of the IAM Role, which is generated for the CR lambda function. Is there any way to customize this?

1 validation error detected: Value '[long-stack-name]-CFN-Resource-Custom-EC2-Key-Pair' at 'roleName' failed to satisfy constraint: Member must have length less than or equal to 64 (Service: AmazonIdentityManagement; Status Code: 400; Error Code: ValidationError; Request ID: 159aeed5-4122-43e2-91af-aee7aeb72118)

jsii version

Hello

  1. excellent job!
  2. I stumble across incompatibilities with jsii and my deployment failed. (just for info im numb in jsii so maybe is my mistake, if so please let me know)
    ERROR: cdk-ec2-key-pair 1.2.2 has requirement jsii~=1.1.0, but you'll have jsii 1.5.0

Thanks
R

import of module is not working

import aws_cdk.aws_ec2 as ec2
Exception ignored in: <function _NodeProcess.del at 0x7fcc7bd448b0>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/jsii/_kernel/providers/process.py", line 224, in del
self.stop()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/jsii/_kernel/providers/process.py", line 281, in stop
if not self._process.stdin.closed:
AttributeError: '_NodeProcess' object has no attribute '_process'
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/resources.py", line 173, in _path_from_reader
yield Path(reader.resource_path(norm_resource))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/jsii/_runtime.py", line 43, in load
_kernel.load(assembly.name, assembly.version, os.fspath(assembly_path))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/jsii/_kernel/init.py", line 269, in load
self.provider.load(LoadRequest(name=name, version=version, tarball=tarball))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/jsii/_kernel/providers/process.py", line 338, in load
return self._process.send(request, LoadResponse)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/jsii/_utils.py", line 24, in wrapped
stored.append(fgetter(self))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/jsii/_kernel/providers/process.py", line 333, in _process
process.start()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/jsii/_kernel/providers/process.py", line 250, in start
self._process = subprocess.Popen(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 951, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/subprocess.py", line 1821, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'node'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "", line 1, in
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aws_cdk/aws_ec2/init.py", line 1443, in
from ._jsii import *
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aws_cdk/aws_ec2/_jsii/init.py", line 11, in
import aws_cdk.aws_cloudwatch._jsii
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aws_cdk/aws_cloudwatch/init.py", line 495, in
from ._jsii import *
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aws_cdk/aws_cloudwatch/_jsii/init.py", line 11, in
import aws_cdk.aws_iam._jsii
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aws_cdk/aws_iam/init.py", line 484, in
from ._jsii import *
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aws_cdk/aws_iam/_jsii/init.py", line 11, in
import aws_cdk.core._jsii
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aws_cdk/core/init.py", line 937, in
from ._jsii import *
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aws_cdk/core/_jsii/init.py", line 11, in
import aws_cdk.cloud_assembly_schema._jsii
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aws_cdk/cloud_assembly_schema/init.py", line 75, in
from ._jsii import *
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/aws_cdk/cloud_assembly_schema/_jsii/init.py", line 11, in
jsii_assembly = jsii.JSIIAssembly.load(
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/jsii/_runtime.py", line 43, in load
_kernel.load(assembly.name, assembly.version, os.fspath(assembly_path))
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/contextlib.py", line 166, in exit
raise RuntimeError("generator didn't stop after throw()")
RuntimeError: generator didn't stop after throw()

Type 'ConstructNode' is missing the following properties from type 'Node'

Hi,

I am a AWS noob trying to learn EC2.

TS Error: Type 'ConstructNode' is missing the following properties from type 'Node'
JS Error when trying to cdk bootstrap: scope.node.addChild is not a function

I ended up in this situation by following this: https://aws.amazon.com/getting-started/guides/deploy-webapp-ec2

image

While the same code with this package.json works fine:
image

This seems like a mismatch in the versions of the constructs module. Any advice on how to approach these type of problems? I hope this is not gonna be the theme when trying to stitch shit together with EC2 on your own.

My intuition tells me the most cost efficient way about this is just to find a version combination that works.

Sorry if this is not the right place, but I have no idea where else to talk about this issue (any suggestions if so?)

Duplicate IAM policy/role name when deploying multi region

When deploying the key pair to a 2nd region, got below error:

A policy called SharedResources-dev-CFN-Resource-Custom-EC2-Key-Pair already exists. Duplicate names are not allowed

Looks like it is creating the same IAM role and policy again.

Could you please advise ?

names function but doesn't constrain name length

❯ npx cdk list

/Users/ahammond/Documents/ClickUp/cold-storage-cdk/node_modules/aws-cdk-lib/aws-lambda/lib/function.ts:662
        throw new Error(`Function name can not be longer than 64 characters but has ${props.functionName.length} characters.`);
              ^
Error: Function name can not be longer than 64 characters but has 74 characters.
    at new Function (/Users/ahammond/Documents/ClickUp/cold-storage-cdk/node_modules/aws-cdk-lib/aws-lambda/lib/function.ts:662:15)
    at KeyPair.ensureLambda (/Users/ahammond/Documents/ClickUp/cold-storage-cdk/node_modules/cdk-ec2-key-pair/lib/index.ts:369:16)
    at new KeyPair (/Users/ahammond/Documents/ClickUp/cold-storage-cdk/node_modules/cdk-ec2-key-pair/lib/index.ts:214:24)

Failed to create resource. You can't create this secret because a secret with this name is already scheduled for deletion

Hi, I've been updating my CDK project to include your excellent CDK library. However, I've stumbeled into a problem. I did create a keypair in secrets manager and downloaded it sucessfully. I've undeployed and tried to re-deploy and got that the secret was marked for deletion. I cannot see it in the secrets manager console. Is it a must to generate a unque name each time in order to not get into this conflict?

Cheers,
Mario :)

CDK output:

EC2KeyPaireedefaultkeypairMario0599CC7A) Resource creation Initiated
 41/61 | 8:41:08 AM | CREATE_FAILED        | Custom::EC2-Key-Pair                           | ee-default-keypair-Mario/EC2-Key-Pair-ee-default-keypair-Mario/Default (eedefaultkeypairMario
EC2KeyPaireedefaultkeypairMario0599CC7A) Failed to create resource. You can't create this secret because a secret with this name is already scheduled for deletion. | Full error in CloudWa
tch 2020/04/03/[$LATEST]3a3efa6d32f545bf82c323db4100bf5d
        new CustomResource (/c/progs/aws/greengrass-starter/node_modules/@aws-cdk/aws-cloudformation/lib/custom-resource.ts:163:21)
        \_ new KeyPair (/c/progs/aws/greengrass-starter/node_modules/cdk-ec2-key-pair/lib/index.ts:93:21)
        \_ new EdgeAnalyticsStack (/c/progs/aws/greengrass-starter/lib/edge-analytics-stack.ts:594:20)
        \_ Object.<anonymous> (/c/progs/aws/greengrass-starter/bin/edge-analytics.ts:29:1)
        \_ Module._compile (internal/modules/cjs/loader.js:1139:30)
        \_ Module.m._compile (/c/progs/aws/greengrass-starter/node_modules/ts-node/src/index.ts:837:23)
        \_ Module._extensions..js (internal/modules/cjs/loader.js:1159:10)
        \_ Object.require.extensions.<computed> [as .ts] (/c/progs/aws/greengrass-starter/node_modules/ts-node/src/index.ts:840:12)
        \_ Module.load (internal/modules/cjs/loader.js:988:32)
        \_ Function.Module._load (internal/modules/cjs/loader.js:896:14)
        \_ Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
        \_ main (/c/progs/aws/greengrass-starter/node_modules/ts-node/src/bin.ts:226:14)
        \_ Object.<anonymous> (/c/progs/aws/greengrass-starter/node_modules/ts-node/src/bin.ts:485:3)
        \_ Module._compile (internal/modules/cjs/loader.js:1139:30)
        \_ Object.Module._extensions..js (internal/modules/cjs/loader.js:1159:10)
        \_ Module.load (internal/modules/cjs/loader.js:988:32)
        \_ Function.Module._load (internal/modules/cjs/loader.js:896:14)
        \_ Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
        \_ /usr/local/lib/node_modules/npm/node_modules/libnpx/index.js:268:14

AwsSolutions-L1: The non-container Lambda function is not configured to use the latest runtime version.

Hi @udondan ,

When I ran CDK NAG on the stack, I get the following error.

It would be nice adding the suppression for the lambda itself.

const fn = new aws_lambda.Function(stack, constructName, {
functionName: `${this.prefix}-${cleanID}`,
role: role,
description: 'Custom CFN resource: Manage EC2 Key Pairs',
runtime: aws_lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: aws_lambda.Code.fromAsset(
path.join(__dirname, '../lambda/code.zip')
),
timeout: Duration.minutes(lambdaTimeout),
});

import { NagSuppressions } from "cdk-nag";


NagSuppressions.addResourceSuppressions(fn,
    [
        {
            id: "AwsSolutions-L1",
            reason: "The lambda function runs appropriate runtime and does not require the latest version."
        }
    ]
)

Update from 1.x fails

Hi,

what is the correct way to update existing stacks to the 2.2.0 from 1.x version - as stated in the documentation the update fails with the message "Received response status [FAILED] from custom resource. Message returned: Once created, a key cannot be modified or accessed. Therefore the public key can only be stored, when the key is created. | Full error in CloudWatch ..." and yes, the rollback finishes successfully. However, I didn't get it how to upgrade - we have to run this fully automated, because we have huge number of resources - is this possible without dropping the stack?

thanks again!

Lambda Code is not bundled with package

Trying to upgrade to the newest version, I get the following error

Error: Cannot find asset at /Users/someone/code/node_modules/cdk-ec2-key-pair/lambda/code.zip
    at new AssetStaging (/Users/someone/code/node_modules/aws-cdk-lib/core/lib/asset-staging.js:1:2119)
    at new Asset (/Users/someone/code/node_modules/aws-cdk-lib/aws-s3-assets/lib/asset.js:1:1080)
    at AssetCode.bind (/Users/someone/code/node_modules/aws-cdk-lib/aws-lambda/lib/code.js:1:4881)
    at new Function (/Users/someone/code/node_modules/aws-cdk-lib/aws-lambda/lib/function.js:1:9422)
    at KeyPair.ensureLambda (/Users/someone/code/node_modules/cdk-ec2-key-pair/lib/index.ts:419:16)
    at new KeyPair (/Users/someone/code/node_modules/cdk-ec2-key-pair/lib/index.ts:271:32)
    at new CommonStack (/Users/someone/code/lib/stacks/common/index.ts:43:27)
    at App.buildBase (/Users/someone/code/lib/app.ts:41:20)
    at new App (/Users/someone/code/lib/app.ts:25:23)
    at Object.<anonymous> (/Users/someone/code/bin/cdk.ts:20:1)

I don't see the code.zip bundled in the npm package

Screenshot 2024-03-25 at 9 35 30 AM

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.