Skip to content

(aws-ec2): Support scope-local cdk context caching of images #26982

@luxaritas

Description

@luxaritas

Describe the feature

Many of the MachineImage constructs support the cacheInContext parameter to cache the AMI ID in the cdk.context.json. A limitation of this is that then any usage of the image across the entire app will use the same AMI, even though it may be desirable to use the latest image at the time of resource creation.

I would like to be able to specify the CDK context key to be tied to the scope the MachineImage is used in.

Use Case

I have a number of EC2 instances that I treat as persistent/stateful, namely which host third-party software which expect to be run completely self-contained in a Docker container which maintains its own volumes for databases, file uploads, etc. in addition to maintaining its own update lifecycle through update scripts. Whenever I deploy one of these new stateful instances in my CDK app, I want it to deploy with the latest Amazon Linux API, without the instance being recreated on future deployments.

Proposed Solution

I currently use the following workaround:

class CustomImage implements IMachineImage {
  getImage(scope: Construct): MachineImageConfig {
    const parameterName = AmazonLinuxImage.ssmParameterName({
      generation: AmazonLinuxGeneration.AMAZON_LINUX_2,
      edition: AmazonLinuxEdition.STANDARD,
    });
    const imageId = ContextProvider.getValue(scope, {
      provider: ContextProviderOpt.SSM_PARAMETER_PROVIDER,
      props: { parameterName, scope: scope.node.path },
      dummyValue: `dummy-value-for-${scope.node.path}-${parameterName}`,
    }).value;
    return {
      imageId,
      osType: OperatingSystemType.LINUX,
      userData: UserData.forLinux(),
    }
  }
}

My anticipated solution would be to support an additional parameter to ssm.StringParameter.valueFromLookup called something like forScope which provides the scope as an extra prop to ContextProvider.getValue, and then MachineImage props would either allow cachedInContext to support multiple options (say "global" or "scope"), or a new property (eg cachedInContextForScope). This additional forScope option can be useful in general for other string parameters and other "cacheable lookup" routines as well.

Other Information

Relevant stale issue: #12355

Acknowledgements

  • I may be able to implement this feature request
  • This feature might incur a breaking change

CDK version used

2.93.0

Environment details (OS name and version, etc.)

N/A

Metadata

Metadata

Assignees

No one assigned

    Labels

    @aws-cdk/aws-ec2Related to Amazon Elastic Compute Cloudeffort/mediumMedium work item – several days of effortfeature-requestA feature should be added or improved.p2

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions