Skip to content

Commit 464cb6f

Browse files
author
Elad Ben-Israel
authored
fix(core): allow CfnMapping.findInMap to use pseudo functions/params (#2220)
* fix(core): allow CfnMapping.findInMap to use pseudo functions/params gate the key existence check by !Token.unresolved so if tokens are used, the key check will not occur. fixes #1363
1 parent 9e87661 commit 464cb6f

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

packages/@aws-cdk/cdk/lib/cfn-mapping.ts

+5-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { CfnRefElement } from './cfn-element';
22
import { Construct } from './construct';
33
import { Fn } from './fn';
4+
import { Token } from './token';
45

56
export interface CfnMappingProps {
67
readonly mapping?: { [k1: string]: { [k2: string]: any } };
@@ -32,11 +33,13 @@ export class CfnMapping extends CfnRefElement {
3233
* @returns A reference to a value in the map based on the two keys.
3334
*/
3435
public findInMap(key1: string, key2: string): string {
35-
if (!(key1 in this.mapping)) {
36+
// opportunistically check that the key exists (if the key does not contain tokens)
37+
if (!Token.unresolved(key1) && !(key1 in this.mapping)) {
3638
throw new Error(`Mapping doesn't contain top-level key '${key1}'`);
3739
}
3840

39-
if (!(key2 in this.mapping[key1])) {
41+
// opportunistically check that the key exists (if the key does not contain tokens)
42+
if (!Token.unresolved(key2) && !(key2 in this.mapping[key1])) {
4043
throw new Error(`Mapping doesn't contain second-level key '${key2}'`);
4144
}
4245

packages/@aws-cdk/cdk/test/test.mappings.ts

+21-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Test } from 'nodeunit';
2-
import { CfnMapping, CfnResource, Stack } from '../lib';
2+
import { Aws, CfnMapping, CfnResource, Fn, Stack } from '../lib';
33

44
export = {
55
'mappings can be added as another type of entity, and mapping.findInMap can be used to get a token'(test: Test) {
@@ -43,4 +43,24 @@ export = {
4343

4444
test.done();
4545
},
46+
47+
'allow using unresolved tokens in find-in-map'(test: Test) {
48+
const stack = new Stack();
49+
50+
const mapping = new CfnMapping(stack, 'mapping', {
51+
mapping: {
52+
instanceCount: {
53+
'us-east-1': 12
54+
}
55+
}
56+
});
57+
58+
const v1 = mapping.findInMap('instanceCount', Aws.region);
59+
const v2 = Fn.findInMap(mapping.logicalId, 'instanceCount', Aws.region);
60+
61+
const expected = { 'Fn::FindInMap': [ 'mapping', 'instanceCount', { Ref: 'AWS::Region' } ] };
62+
test.deepEqual(stack.node.resolve(v1), expected);
63+
test.deepEqual(stack.node.resolve(v2), expected);
64+
test.done();
65+
}
4666
};

0 commit comments

Comments
 (0)