Skip to content

Commit 02cd84b

Browse files
author
Alexander Schueren
authored
docs(parameters): add parameters examples cdk and sam (#1622)
* add ssm to example * add parameters to cdk example * update cleanup * add sam tempalte with dedicated uuid api gw * added deps for examples * clean up corructed deps * fix test and revert back to cdk 2.73.0 * revert to previous package lock * swtich to randomUUID * removed unused param, bumped powertools version * add PT_VERSION from commons instead of string variable * add nosonar for temp resources in example
1 parent c4e6b19 commit 02cd84b

18 files changed

+660
-92
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { logger } from './powertools';
2+
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';
3+
import { randomUUID } from 'node:crypto';
4+
import { default as request } from 'phin';
5+
6+
export const getUuid = async (): Promise<string> => {
7+
const uuidApiUrl = await getParameter('/app/uuid-api-url');
8+
if (!uuidApiUrl) {
9+
// create uuid locally
10+
logger.warn('No uuid-api-url parameter found, creating uuid locally');
11+
12+
return randomUUID();
13+
} else {
14+
// Request a sample random uuid from a webservice
15+
const res = await request<{ uuid: string }>({
16+
url: uuidApiUrl,
17+
parse: 'json',
18+
});
19+
20+
return res.body.uuid;
21+
}
22+
};

examples/cdk/functions/common/powertools.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import { Logger } from '@aws-lambda-powertools/logger';
22
import { Metrics } from '@aws-lambda-powertools/metrics';
33
import { Tracer } from '@aws-lambda-powertools/tracer';
4-
5-
const awsLambdaPowertoolsVersion = '1.5.0';
4+
import { PT_VERSION } from '@aws-lambda-powertools/commons/lib/version';
65

76
const defaultValues = {
87
region: process.env.AWS_REGION || 'N/A',
@@ -14,7 +13,7 @@ const logger = new Logger({
1413
...defaultValues,
1514
logger: {
1615
name: '@aws-lambda-powertools/logger',
17-
version: awsLambdaPowertoolsVersion,
16+
version: PT_VERSION,
1817
},
1918
},
2019
});

examples/cdk/functions/get-all-items.ts

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
1+
import { injectLambdaContext } from '@aws-lambda-powertools/logger';
2+
import { logMetrics } from '@aws-lambda-powertools/metrics';
3+
import { captureLambdaHandler } from '@aws-lambda-powertools/tracer';
4+
import { ScanCommand } from '@aws-sdk/lib-dynamodb';
5+
import middy from '@middy/core';
16
import {
27
APIGatewayProxyEvent,
38
APIGatewayProxyResult,
49
Context,
510
} from 'aws-lambda';
6-
import middy from '@middy/core';
711
import { tableName } from './common/constants';
8-
import { logger, tracer, metrics } from './common/powertools';
9-
import { logMetrics } from '@aws-lambda-powertools/metrics';
10-
import { injectLambdaContext } from '@aws-lambda-powertools/logger';
11-
import { captureLambdaHandler } from '@aws-lambda-powertools/tracer';
1212
import { docClient } from './common/dynamodb-client';
13-
import { ScanCommand } from '@aws-sdk/lib-dynamodb';
14-
import { default as request } from 'phin';
13+
import { getUuid } from './common/getUuid';
14+
import { logger, metrics, tracer } from './common/powertools';
1515

1616
/*
1717
*
@@ -45,12 +45,7 @@ const getAllItemsHandler = async (
4545
awsRequestId: context.awsRequestId,
4646
});
4747

48-
// Request a sample random uuid from a webservice
49-
const res = await request<{ uuid: string }>({
50-
url: 'https://httpbin.org/uuid',
51-
parse: 'json',
52-
});
53-
const { uuid } = res.body;
48+
const uuid = await getUuid();
5449

5550
// Logger: Append uuid to each log statement
5651
logger.appendKeys({ uuid });

examples/cdk/functions/get-by-id.ts

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1+
import { LambdaInterface } from '@aws-lambda-powertools/commons';
2+
import { GetCommand } from '@aws-sdk/lib-dynamodb';
13
import {
24
APIGatewayProxyEvent,
35
APIGatewayProxyResult,
46
Context,
57
} from 'aws-lambda';
68
import { tableName } from './common/constants';
7-
import { logger, tracer, metrics } from './common/powertools';
8-
import { LambdaInterface } from '@aws-lambda-powertools/commons';
99
import { docClient } from './common/dynamodb-client';
10-
import { GetCommand } from '@aws-sdk/lib-dynamodb';
11-
import { default as request } from 'phin';
10+
import { getUuid } from './common/getUuid';
11+
import { logger, metrics, tracer } from './common/powertools';
1212

1313
/*
1414
*
@@ -28,14 +28,7 @@ import { default as request } from 'phin';
2828
class Lambda implements LambdaInterface {
2929
@tracer.captureMethod()
3030
public async getUuid(): Promise<string> {
31-
// Request a sample random uuid from a webservice
32-
const res = await request<{ uuid: string }>({
33-
url: 'https://httpbin.org/uuid',
34-
parse: 'json',
35-
});
36-
const { uuid } = res.body;
37-
38-
return uuid;
31+
return getUuid();
3932
}
4033

4134
@tracer.captureLambdaHandler({ captureResponse: false }) // by default the tracer would add the response as metadata on the segment, but there is a chance to hit the 64kb segment size limit. Therefore set captureResponse: false

examples/cdk/functions/put-item.ts

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1+
import { PutCommand } from '@aws-sdk/lib-dynamodb';
12
import {
23
APIGatewayProxyEvent,
34
APIGatewayProxyResult,
45
Context,
56
} from 'aws-lambda';
7+
import type { Subsegment } from 'aws-xray-sdk-core';
68
import { tableName } from './common/constants';
7-
import { logger, tracer, metrics } from './common/powertools';
89
import { docClient } from './common/dynamodb-client';
9-
import { PutCommand } from '@aws-sdk/lib-dynamodb';
10-
import { default as request } from 'phin';
11-
import type { Subsegment } from 'aws-xray-sdk-core';
10+
import { getUuid } from './common/getUuid';
11+
import { logger, metrics, tracer } from './common/powertools';
1212

1313
/**
1414
*
@@ -59,12 +59,7 @@ export const handler = async (
5959
awsRequestId: context.awsRequestId,
6060
});
6161

62-
// Request a sample random uuid from a webservice
63-
const res = await request<{ uuid: string }>({
64-
url: 'https://httpbin.org/uuid',
65-
parse: 'json',
66-
});
67-
const { uuid } = res.body;
62+
const uuid = await getUuid();
6863

6964
// Logger: Append uuid to each log statement
7065
logger.appendKeys({ uuid });

examples/cdk/functions/uuid.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { randomUUID } from 'node:crypto';
2+
3+
exports.handler = async (_event) => {
4+
return {
5+
statusCode: 200,
6+
body: JSON.stringify(randomUUID()),
7+
};
8+
};

examples/cdk/package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,12 @@
2525
"*.js": "npm run lint-fix"
2626
},
2727
"devDependencies": {
28+
"@aws-lambda-powertools/commons": "^1.11.1",
2829
"@aws-lambda-powertools/logger": "^1.11.1",
2930
"@aws-lambda-powertools/metrics": "^1.11.1",
31+
"@aws-lambda-powertools/parameters": "^1.11.1",
3032
"@aws-lambda-powertools/tracer": "^1.11.1",
33+
"@aws-sdk/client-ssm": "^3.360.0",
3134
"@aws-sdk/lib-dynamodb": "^3.360.0",
3235
"@types/aws-lambda": "^8.10.109",
3336
"@types/jest": "^29.2.4",

examples/cdk/src/example-stack.ts

Lines changed: 46 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
1-
import { Stack, StackProps, Duration } from 'aws-cdk-lib';
2-
import { Construct } from 'constructs';
3-
import { Table, BillingMode, AttributeType } from 'aws-cdk-lib/aws-dynamodb';
1+
import { Duration, Stack, StackProps } from 'aws-cdk-lib';
2+
import { LambdaIntegration, RestApi } from 'aws-cdk-lib/aws-apigateway';
3+
import { AttributeType, BillingMode, Table } from 'aws-cdk-lib/aws-dynamodb';
4+
import { LayerVersion, Runtime, Tracing } from 'aws-cdk-lib/aws-lambda';
45
import {
56
NodejsFunction,
67
NodejsFunctionProps,
78
} from 'aws-cdk-lib/aws-lambda-nodejs';
8-
import { Runtime, Tracing, LayerVersion } from 'aws-cdk-lib/aws-lambda';
99
import { RetentionDays } from 'aws-cdk-lib/aws-logs';
10-
import { RestApi, LambdaIntegration } from 'aws-cdk-lib/aws-apigateway';
10+
import { StringParameter } from 'aws-cdk-lib/aws-ssm';
11+
import { Construct } from 'constructs';
1112

1213
const commonProps: Partial<NodejsFunctionProps> = {
1314
runtime: Runtime.NODEJS_18_X,
@@ -37,6 +38,8 @@ export class CdkAppStack extends Stack {
3738
public constructor(scope: Construct, id: string, props?: StackProps) {
3839
super(scope, id, props);
3940

41+
const uuidApi = new UuidApi(this, 'uuid-api');
42+
4043
const table = new Table(this, 'Table', {
4144
billingMode: BillingMode.PAY_PER_REQUEST,
4245
partitionKey: {
@@ -51,7 +54,7 @@ export class CdkAppStack extends Stack {
5154
'powertools-layer',
5255
`arn:aws:lambda:${
5356
Stack.of(this).region
54-
}:094274105915:layer:AWSLambdaPowertoolsTypeScript:6`
57+
}:094274105915:layer:AWSLambdaPowertoolsTypeScript:16`
5558
)
5659
);
5760

@@ -76,12 +79,20 @@ export class CdkAppStack extends Stack {
7679
entry: './functions/get-by-id.ts',
7780
handler: 'handler',
7881
});
82+
83+
uuidApi.apiUrlParam.grantRead(getByIdFn);
84+
uuidApi.apiUrlParam.grantRead(putItemFn);
85+
uuidApi.apiUrlParam.grantRead(getAllItemsFn);
86+
7987
getByIdFn.addEnvironment('SAMPLE_TABLE', table.tableName);
8088
table.grantReadData(getByIdFn);
8189

8290
const api = new RestApi(this, 'items-api', {
8391
restApiName: 'Items Service',
8492
description: 'This service serves items.',
93+
deployOptions: {
94+
tracingEnabled: true,
95+
},
8596
});
8697

8798
const itemPutIntegration = new LambdaIntegration(putItemFn);
@@ -95,3 +106,32 @@ export class CdkAppStack extends Stack {
95106
item.addMethod('GET', itemIntegration);
96107
}
97108
}
109+
110+
class UuidApi extends Construct {
111+
public readonly apiUrlParam: StringParameter;
112+
public constructor(scope: Construct, id: string) {
113+
super(scope, id);
114+
115+
const uuidFn = new NodejsFunction(this, 'UuidFn', {
116+
runtime: Runtime.NODEJS_18_X,
117+
entry: './functions/uuid.ts',
118+
});
119+
120+
const api = new RestApi(this, 'uuid-api', {
121+
restApiName: 'UUID Service',
122+
description: 'This service serves UUIDs.',
123+
deployOptions: {
124+
tracingEnabled: true,
125+
},
126+
});
127+
128+
const uuidIntegration = new LambdaIntegration(uuidFn);
129+
const uuid = api.root.addResource('uuid');
130+
uuid.addMethod('GET', uuidIntegration);
131+
132+
this.apiUrlParam = new StringParameter(this, 'uuid-api-url', {
133+
parameterName: '/app/uuid-api-url',
134+
stringValue: `${api.url}/uuid`,
135+
});
136+
}
137+
}

examples/cdk/tests/cdk-app.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,5 @@ import * as CdkApp from '../src/example-stack';
55
test('CDK code synthesize', () => {
66
const app = new cdk.App();
77
const stack = new CdkApp.CdkAppStack(app, 'MyTestStack');
8-
Template.fromStack(stack).resourceCountIs('AWS::Lambda::Function', 4); // The stack has 4 functions: 3 for the example, and 1 for the log retention that is deployed by CDK
8+
Template.fromStack(stack).resourceCountIs('AWS::Lambda::Function', 5); // The stack has 4 functions: 3 for the example, and 1 for the log retention that is deployed by CDK
99
});

examples/sam/package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
"@types/node": "18.11.17",
2727
"@typescript-eslint/eslint-plugin": "^5.46.1",
2828
"@typescript-eslint/parser": "^5.46.1",
29-
"esbuild": "^0.16.9",
3029
"eslint": "^8.30.0",
3130
"eslint-import-resolver-node": "^0.3.6",
3231
"eslint-import-resolver-typescript": "^3.5.2",
@@ -40,9 +39,12 @@
4039
"@aws-lambda-powertools/logger": "^1.11.1",
4140
"@aws-lambda-powertools/metrics": "^1.11.1",
4241
"@aws-lambda-powertools/tracer": "^1.11.1",
42+
"@aws-lambda-powertools/parameters": "^1.11.1",
4343
"@aws-sdk/client-dynamodb": "^3.360.0",
44+
"@aws-sdk/client-ssm": "^3.360.0",
4445
"@aws-sdk/lib-dynamodb": "^3.360.0",
4546
"@middy/core": "^3.6.2",
47+
"esbuild": "^0.18.14",
4648
"phin": "^3.7.0"
4749
}
4850
}

examples/sam/src/common/getUuid.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { logger } from './powertools';
2+
import { getParameter } from '@aws-lambda-powertools/parameters/ssm';
3+
import { randomUUID } from 'node:crypto';
4+
import { default as request } from 'phin';
5+
6+
export const getUuid = async (): Promise<string> => {
7+
const uuidApiUrl = await getParameter('/app/uuid-api-url');
8+
if (!uuidApiUrl) {
9+
// create uuid locally
10+
logger.warn('No uuid-api-url parameter found, creating uuid locally');
11+
12+
return randomUUID();
13+
} else {
14+
// Request a sample random uuid from a webservice
15+
const res = await request<{ uuid: string }>({
16+
url: uuidApiUrl,
17+
parse: 'json',
18+
});
19+
20+
return res.body.uuid;
21+
}
22+
};

examples/sam/src/common/powertools.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import { Logger } from '@aws-lambda-powertools/logger';
22
import { Metrics } from '@aws-lambda-powertools/metrics';
33
import { Tracer } from '@aws-lambda-powertools/tracer';
4-
5-
const awsLambdaPowertoolsVersion = '1.5.0';
4+
import { PT_VERSION } from '@aws-lambda-powertools/commons/lib/version';
65

76
const defaultValues = {
87
region: process.env.AWS_REGION || 'N/A',
@@ -14,7 +13,7 @@ const logger = new Logger({
1413
...defaultValues,
1514
logger: {
1615
name: '@aws-lambda-powertools/logger',
17-
version: awsLambdaPowertoolsVersion,
16+
version: PT_VERSION,
1817
},
1918
},
2019
});

examples/sam/src/get-all-items.ts

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { injectLambdaContext } from '@aws-lambda-powertools/logger';
1111
import { captureLambdaHandler } from '@aws-lambda-powertools/tracer';
1212
import { docClient } from './common/dynamodb-client';
1313
import { ScanCommand } from '@aws-sdk/lib-dynamodb';
14-
import { default as request } from 'phin';
14+
import { getUuid } from './common/getUuid';
1515

1616
/*
1717
*
@@ -45,12 +45,7 @@ const getAllItemsHandler = async (
4545
awsRequestId: context.awsRequestId,
4646
});
4747

48-
// Request a sample random uuid from a webservice
49-
const res = await request<{ uuid: string }>({
50-
url: 'https://httpbin.org/uuid',
51-
parse: 'json',
52-
});
53-
const { uuid } = res.body;
48+
const uuid = await getUuid();
5449

5550
// Logger: Append uuid to each log statement
5651
logger.appendKeys({ uuid });

examples/sam/src/get-by-id.ts

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1+
import { LambdaInterface } from '@aws-lambda-powertools/commons';
2+
import { GetCommand } from '@aws-sdk/lib-dynamodb';
13
import {
24
APIGatewayProxyEvent,
35
APIGatewayProxyResult,
46
Context,
57
} from 'aws-lambda';
68
import { tableName } from './common/constants';
7-
import { logger, tracer, metrics } from './common/powertools';
8-
import { LambdaInterface } from '@aws-lambda-powertools/commons';
99
import { docClient } from './common/dynamodb-client';
10-
import { GetCommand } from '@aws-sdk/lib-dynamodb';
11-
import { default as request } from 'phin';
10+
import { getUuid } from './common/getUuid';
11+
import { logger, metrics, tracer } from './common/powertools';
1212

1313
/*
1414
*
@@ -28,14 +28,7 @@ import { default as request } from 'phin';
2828
class Lambda implements LambdaInterface {
2929
@tracer.captureMethod()
3030
public async getUuid(): Promise<string> {
31-
// Request a sample random uuid from a webservice
32-
const res = await request<{ uuid: string }>({
33-
url: 'https://httpbin.org/uuid',
34-
parse: 'json',
35-
});
36-
const { uuid } = res.body;
37-
38-
return uuid;
31+
return getUuid();
3932
}
4033

4134
@tracer.captureLambdaHandler({ captureResponse: false }) // by default the tracer would add the response as metadata on the segment, but there is a chance to hit the 64kb segment size limit. Therefore set captureResponse: false

examples/sam/src/get-uuid.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { randomUUID } from 'node:crypto';
2+
3+
exports.handler = async (_event) => {
4+
return {
5+
statusCode: 200,
6+
body: JSON.stringify(randomUUID()),
7+
};
8+
};

0 commit comments

Comments
 (0)