aws / aws-cdk

The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code
https://aws.amazon.com/cdk
Apache License 2.0
11.38k stars 3.79k forks source link

feat(custom-resource): universal loggingConfig for all custom resource providers #30777

Open pahud opened 1 week ago

pahud commented 1 week ago

Describe the feature

CDK has some built-in custom resources that come with providers with LoggingConfig undefined. This may violate some cooperation compliance requirements.

We need an approach to allow users to specify an universal or custom LoggingConfig for all those lambda providers.

Use Case

To make sure all lambda functions CDK auto generates have LoggingConfig configured with custom retention period.

Proposed Solution

Not sure what would be the best solution but at this moment, users would have to write a custom function or Aspects.

Let's say if we need to ensure all custom resources behind the eks.Cluster has LoggingConfig defined:

export class DummyStack extends Stack {
  readonly globalClusterIdentifier: string;
  private readonly processed: CfnResource[] = [];
  private lambdaSharedLogGroup: logs.ILogGroup;
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    new eks.Cluster(this, 'Cluster', {
      version: eks.KubernetesVersion.V1_30,
    });

    // create a shared log group
    this.lambdaSharedLogGroup = new logs.LogGroup(this, id, {
      retention: logs.RetentionDays.NINE_YEARS,
    });

    this.ensureLambdaLogs();

  }

  private ensureLambdaLogs(construct?: IConstruct[]) {
    // this method ensure log group for each lambda function with custom retention period
    (construct ?? this.node.findAll()).forEach(c => {
      if (CfnResource.isCfnResource(c)) {
        if (c.cfnResourceType === 'AWS::Lambda::Function' && (c as lambda.CfnFunction).loggingConfig === undefined) {
          console.log('got lambda resource with undefined loggingConfig: ' + c.cfnResourceType )
          this.addLoggingConfigOverride(c as lambda.CfnFunction)
        } else {
          console.log('got resource type ' + c.cfnResourceType)
        }
      } else {
         this.ensureLambdaLogs(c.node.children);
      }
    })
  }
  private addLoggingConfigOverride(f: lambda.CfnFunction) {
    f.addPropertyOverride('LoggingConfig', {
      'LogGroup': this.lambdaSharedLogGroup.logGroupName,
    })
  }
} // end stack

Other Information

No response

Acknowledgements

CDK version used

2.147.0

Environment details (OS name and version, etc.)

all

pahud commented 1 week ago

internal tracking: D142944846