Skip to content

Commit

Permalink
fix(core): allow CfnMapping.findInMap to use pseudo functions/params (a…
Browse files Browse the repository at this point in the history
…ws#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 aws#1363
  • Loading branch information
Elad Ben-Israel authored Apr 10, 2019
1 parent 9e87661 commit 464cb6f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
7 changes: 5 additions & 2 deletions packages/@aws-cdk/cdk/lib/cfn-mapping.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { CfnRefElement } from './cfn-element';
import { Construct } from './construct';
import { Fn } from './fn';
import { Token } from './token';

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

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

Expand Down
22 changes: 21 additions & 1 deletion packages/@aws-cdk/cdk/test/test.mappings.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Test } from 'nodeunit';
import { CfnMapping, CfnResource, Stack } from '../lib';
import { Aws, CfnMapping, CfnResource, Fn, Stack } from '../lib';

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

test.done();
},

'allow using unresolved tokens in find-in-map'(test: Test) {
const stack = new Stack();

const mapping = new CfnMapping(stack, 'mapping', {
mapping: {
instanceCount: {
'us-east-1': 12
}
}
});

const v1 = mapping.findInMap('instanceCount', Aws.region);
const v2 = Fn.findInMap(mapping.logicalId, 'instanceCount', Aws.region);

const expected = { 'Fn::FindInMap': [ 'mapping', 'instanceCount', { Ref: 'AWS::Region' } ] };
test.deepEqual(stack.node.resolve(v1), expected);
test.deepEqual(stack.node.resolve(v2), expected);
test.done();
}
};

0 comments on commit 464cb6f

Please sign in to comment.