Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(core): refactor API of Tokens #2757

Merged
merged 15 commits into from
Jun 11, 2019
2 changes: 1 addition & 1 deletion packages/@aws-cdk/assets-docker/lib/image-asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export class DockerImageAsset extends cdk.Construct implements assets.IAsset {

// Parse repository name and tag from the parameter (<REPO_NAME>@sha256:<TAG>)
// Example: cdk/cdkexampleimageb2d7f504@sha256:72c4f956379a43b5623d529ddd969f6826dde944d6221f445ff3e7add9875500
const components = cdk.Fn.split('@sha256:', imageNameParameter.stringValue);
const components = cdk.Fn.split('@sha256:', imageNameParameter.valueAsString);
const repositoryName = cdk.Fn.select(0, components).toString();
const imageSha = cdk.Fn.select(1, components).toString();

Expand Down
8 changes: 4 additions & 4 deletions packages/@aws-cdk/assets/lib/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,11 +148,11 @@ export class Asset extends cdk.Construct implements IAsset {
type: 'String',
});

this.s3BucketName = bucketParam.stringValue;
this.s3Prefix = cdk.Fn.select(0, cdk.Fn.split(cxapi.ASSET_PREFIX_SEPARATOR, keyParam.stringValue)).toString();
const s3Filename = cdk.Fn.select(1, cdk.Fn.split(cxapi.ASSET_PREFIX_SEPARATOR, keyParam.stringValue)).toString();
this.s3BucketName = bucketParam.valueAsString;
this.s3Prefix = cdk.Fn.select(0, cdk.Fn.split(cxapi.ASSET_PREFIX_SEPARATOR, keyParam.valueAsString)).toString();
const s3Filename = cdk.Fn.select(1, cdk.Fn.split(cxapi.ASSET_PREFIX_SEPARATOR, keyParam.valueAsString)).toString();
this.s3ObjectKey = `${this.s3Prefix}${s3Filename}`;
this.artifactHash = hashParam.stringValue;
this.artifactHash = hashParam.valueAsString;

this.bucket = s3.Bucket.fromBucketName(this, 'AssetBucket', this.s3BucketName);

Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-apigateway/lib/api-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export class ApiKey extends Resource implements IApiKey {
stageKeys: this.renderStageKeys(props.resources)
});

this.keyId = resource.ref;
this.keyId = resource.refAsString;
}

private renderStageKeys(resources: RestApi[] | undefined): CfnApiKey.StageKeyProperty[] | undefined {
Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/aws-apigateway/lib/deployment.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Construct, DeletionPolicy, Resource, Token } from '@aws-cdk/cdk';
import { Construct, DeletionPolicy, Lazy, Resource } from '@aws-cdk/cdk';
import crypto = require('crypto');
import { CfnDeployment, CfnDeploymentProps } from './apigateway.generated';
import { IRestApi } from './restapi';
Expand Down Expand Up @@ -76,7 +76,7 @@ export class Deployment extends Resource {
}

this.api = props.api;
this.deploymentId = new Token(() => this.resource.deploymentId).toString();
this.deploymentId = Lazy.stringValue({ produce: () => this.resource.deploymentId });
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we shorten? Lazy.string conveys the exact same meaning with less words...

Copy link
Contributor Author

@rix0rrr rix0rrr Jun 6, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, but string will be a keyword in nearly all languages.

}

/**
Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/aws-apigateway/lib/integrations/aws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export class AwsIntegration extends Integration {
super({
type,
integrationHttpMethod: props.integrationHttpMethod || 'POST',
uri: new cdk.Token(() => {
uri: cdk.Lazy.stringValue({ produce: () => {
if (!this.scope) { throw new Error('AwsIntegration must be used in API'); }
return this.scope.node.stack.formatArn({
service: 'apigateway',
Expand All @@ -87,7 +87,7 @@ export class AwsIntegration extends Integration {
sep: '/',
resourceName: apiValue,
});
}),
}}),
options: props.options,
});
}
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-apigateway/lib/method.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export class Method extends Resource {

const resource = new CfnMethod(this, 'Resource', methodProps);

this.methodId = resource.ref;
this.methodId = resource.refAsString;

props.resource.restApi._attachMethod(this);

Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-apigateway/lib/restapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ export class RestApi extends Resource implements IRestApi {
parameters: props.parameters,
});

this.restApiId = resource.ref;
this.restApiId = resource.refAsString;

this.configureDeployment(props);

Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-apigateway/lib/stage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ export class Stage extends Resource {
methodSettings,
});

this.stageName = resource.ref;
this.stageName = resource.refAsString;
this.restApi = props.deployment.api;
}

Expand Down
6 changes: 3 additions & 3 deletions packages/@aws-cdk/aws-apigateway/lib/usage-plan.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Token } from '@aws-cdk/cdk';
import { Lazy, Token } from '@aws-cdk/cdk';
import { Construct, Resource } from '@aws-cdk/cdk';
import { IApiKey } from './api-key';
import { CfnUsagePlan, CfnUsagePlanKey } from './apigateway.generated';
Expand Down Expand Up @@ -156,7 +156,7 @@ export class UsagePlan extends Resource {
let resource: CfnUsagePlan;

resource = new CfnUsagePlan(this, 'Resource', {
apiStages: new Token(() => this.renderApiStages(this.apiStages)),
apiStages: Lazy.anyValue({ produce: () => this.renderApiStages(this.apiStages) }),
description: props.description,
quota: this.renderQuota(props),
throttle: this.renderThrottle(props.throttle),
Expand All @@ -165,7 +165,7 @@ export class UsagePlan extends Resource {

this.apiStages.push(...(props.apiStages || []));

this.usagePlanId = resource.ref;
this.usagePlanId = resource.refAsString;

// Add ApiKey when
if (props.apiKey) {
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-apigateway/test/test.deployment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export = {

// tokens supported, and are resolved upon synthesis
const value = 'hello hello';
deployment.addToLogicalId({ foo: new cdk.Token(() => value) });
deployment.addToLogicalId({ foo: cdk.Lazy.stringValue({ produce: () => value }) });

const template2 = synthesize();
test.ok(template2.Resources.deployment33381975a12dfe81474913364dc31c06e37f9449);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export class StepScalingAction extends cdk.Construct {
cooldown: props.cooldownSec,
minAdjustmentMagnitude: props.minAdjustmentMagnitude,
metricAggregationType: props.metricAggregationType,
stepAdjustments: new cdk.Token(() => this.adjustments),
stepAdjustments: cdk.Lazy.anyValue({ produce: () => this.adjustments }),
} as CfnScalingPolicy.StepScalingPolicyConfigurationProperty
});

Expand Down
16 changes: 8 additions & 8 deletions packages/@aws-cdk/aws-autoscaling/lib/auto-scaling-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import elbv2 = require('@aws-cdk/aws-elasticloadbalancingv2');
import iam = require('@aws-cdk/aws-iam');
import sns = require('@aws-cdk/aws-sns');

import { AutoScalingRollingUpdate, Construct, Fn, IResource, Resource, Tag, Token } from '@aws-cdk/cdk';
import { AutoScalingRollingUpdate, Construct, Fn, IResource, Lazy, Resource, Tag } from '@aws-cdk/cdk';
import { CfnAutoScalingGroup, CfnAutoScalingGroupProps, CfnLaunchConfiguration } from './autoscaling.generated';
import { BasicLifecycleHookProps, LifecycleHook } from './lifecycle-hook';
import { BasicScheduledActionProps, ScheduledAction } from './scheduled-action';
Expand Down Expand Up @@ -375,15 +375,15 @@ export class AutoScalingGroup extends AutoScalingGroupBase implements

// use delayed evaluation
const machineImage = props.machineImage.getImage(this);
const userDataToken = new Token(() => Fn.base64((machineImage.os.createUserData(this.userDataLines)))).toString();
const securityGroupsToken = new Token(() => this.securityGroups.map(sg => sg.securityGroupId));
const userDataToken = Lazy.stringValue({ produce: () => Fn.base64((machineImage.os.createUserData(this.userDataLines))) });
const securityGroupsToken = Lazy.listValue({ produce: () => this.securityGroups.map(sg => sg.securityGroupId) });

const launchConfig = new CfnLaunchConfiguration(this, 'LaunchConfig', {
imageId: machineImage.imageId,
keyName: props.keyName,
instanceType: props.instanceType.toString(),
securityGroups: securityGroupsToken.toList(),
iamInstanceProfile: iamProfile.ref,
securityGroups: securityGroupsToken,
iamInstanceProfile: iamProfile.refAsString,
userData: userDataToken,
associatePublicIpAddress: props.associatePublicIpAddress,
spotPrice: props.spotPrice,
Expand All @@ -408,9 +408,9 @@ export class AutoScalingGroup extends AutoScalingGroupBase implements
minSize: minCapacity.toString(),
maxSize: maxCapacity.toString(),
desiredCapacity: desiredCapacity.toString(),
launchConfigurationName: launchConfig.ref,
loadBalancerNames: new Token(() => this.loadBalancerNames.length > 0 ? this.loadBalancerNames : undefined).toList(),
targetGroupArns: new Token(() => this.targetGroupArns.length > 0 ? this.targetGroupArns : undefined).toList(),
launchConfigurationName: launchConfig.refAsString,
loadBalancerNames: Lazy.listValue({ produce: () => this.loadBalancerNames }, { omitEmpty: true }),
targetGroupArns: Lazy.listValue({ produce: () => this.targetGroupArns }, { omitEmpty: true }),
notificationConfigurations: !props.notificationsTopic ? undefined : [
{
topicArn: props.notificationsTopic.topicArn,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export class StepScalingAction extends cdk.Construct {
adjustmentType: props.adjustmentType,
minAdjustmentMagnitude: props.minAdjustmentMagnitude,
metricAggregationType: props.metricAggregationType,
stepAdjustments: new cdk.Token(() => this.adjustments),
stepAdjustments: cdk.Lazy.anyValue({ produce: () => this.adjustments }),
});

this.scalingPolicyArn = resource.scalingPolicyArn;
Expand Down
8 changes: 4 additions & 4 deletions packages/@aws-cdk/aws-cloudwatch/lib/alarm.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Construct, IResource, Resource, Token } from '@aws-cdk/cdk';
import { Construct, IResource, Lazy, Resource } from '@aws-cdk/cdk';
import { IAlarmAction } from './alarm-action';
import { CfnAlarm } from './cloudwatch.generated';
import { HorizontalAnnotation } from './graph';
Expand Down Expand Up @@ -133,9 +133,9 @@ export class Alarm extends Resource implements IAlarm {

// Actions
actionsEnabled: props.actionsEnabled,
alarmActions: new Token(() => this.alarmActionArns).toList(),
insufficientDataActions: new Token(() => this.insufficientDataActionArns).toList(),
okActions: new Token(() => this.okActionArns).toList(),
alarmActions: Lazy.listValue({ produce: () => this.alarmActionArns }),
insufficientDataActions: Lazy.listValue({ produce: (() => this.insufficientDataActionArns) }),
okActions: Lazy.listValue({ produce: () => this.okActionArns }),

// Metric
...metricJson(props.metric)
Expand Down
6 changes: 3 additions & 3 deletions packages/@aws-cdk/aws-cloudwatch/lib/dashboard.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Construct, Resource, Token } from "@aws-cdk/cdk";
import { Construct, Lazy, Resource } from "@aws-cdk/cdk";
import { CfnDashboard } from './cloudwatch.generated';
import { Column, Row } from "./layout";
import { IWidget } from "./widget";
Expand Down Expand Up @@ -58,7 +58,7 @@ export class Dashboard extends Resource {

new CfnDashboard(this, 'Resource', {
dashboardName: (props && props.dashboardName) || undefined,
dashboardBody: new Token(() => {
dashboardBody: Lazy.stringValue({ produce: () => {
const column = new Column(...this.rows);
column.position(0, 0);
return this.node.stringifyJson({
Expand All @@ -67,7 +67,7 @@ export class Dashboard extends Resource {
periodOverride: props ? props.periodOverride : undefined,
widgets: column.toJson(),
});
}).toString()
}})
});
}

Expand Down
6 changes: 3 additions & 3 deletions packages/@aws-cdk/aws-codebuild/lib/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import ecr = require('@aws-cdk/aws-ecr');
import events = require('@aws-cdk/aws-events');
import iam = require('@aws-cdk/aws-iam');
import kms = require('@aws-cdk/aws-kms');
import { Aws, Construct, IResource, Resource, Token } from '@aws-cdk/cdk';
import { Aws, Construct, IResource, Lazy, Resource } from '@aws-cdk/cdk';
import { BuildArtifacts, CodePipelineBuildArtifacts, NoBuildArtifacts } from './artifacts';
import { Cache } from './cache';
import { CfnProject } from './codebuild.generated';
Expand Down Expand Up @@ -702,8 +702,8 @@ export class Project extends ProjectBase {
cache: cache._toCloudFormation(),
name: props.projectName,
timeoutInMinutes: props.timeout,
secondarySources: new Token(() => this.renderSecondarySources()),
secondaryArtifacts: new Token(() => this.renderSecondaryArtifacts()),
secondarySources: Lazy.anyValue({ produce: () => this.renderSecondarySources() }),
secondaryArtifacts: Lazy.anyValue({ produce: () => this.renderSecondaryArtifacts() }),
triggers: this.source._buildTriggers(),
vpcConfig: this.configureVpc(props),
});
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-codebuild/test/test.codebuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1135,7 +1135,7 @@ export = {
environment: {
environmentVariables: {
FOO: { value: '1234' },
BAR: { value: `111${new cdk.Token({ twotwotwo: '222' })}`, type: codebuild.BuildEnvironmentVariableType.ParameterStore }
BAR: { value: `111${new cdk.Intrinsic({ twotwotwo: '222' })}`, type: codebuild.BuildEnvironmentVariableType.ParameterStore }
}
},
environmentVariables: {
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-codedeploy/lib/lambda/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export class LambdaApplication extends Resource implements ILambdaApplication {
computePlatform: 'Lambda'
});

this.applicationName = resource.ref;
this.applicationName = resource.refAsString;
this.applicationArn = arnForApplication(this.applicationName);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,8 @@ export class LambdaDeploymentGroup extends cdk.Resource implements ILambdaDeploy
deploymentType: 'BLUE_GREEN',
deploymentOption: 'WITH_TRAFFIC_CONTROL'
},
alarmConfiguration: new cdk.Token(() => renderAlarmConfiguration(this.alarms, props.ignorePollAlarmsFailure)),
autoRollbackConfiguration: new cdk.Token(() => renderAutoRollbackConfiguration(this.alarms, props.autoRollback)),
alarmConfiguration: cdk.Lazy.anyValue({ produce: () => renderAlarmConfiguration(this.alarms, props.ignorePollAlarmsFailure) }),
autoRollbackConfiguration: cdk.Lazy.anyValue({ produce: () => renderAutoRollbackConfiguration(this.alarms, props.autoRollback) }),
});

this.deploymentGroupName = resource.deploymentGroupName;
Expand All @@ -180,8 +180,8 @@ export class LambdaDeploymentGroup extends cdk.Resource implements ILambdaDeploy
codeDeployLambdaAliasUpdate: {
applicationName: this.application.applicationName,
deploymentGroupName: resource.deploymentGroupName,
beforeAllowTrafficHook: new cdk.Token(() => this.preHook === undefined ? undefined : this.preHook.functionName).toString(),
afterAllowTrafficHook: new cdk.Token(() => this.postHook === undefined ? undefined : this.postHook.functionName).toString()
beforeAllowTrafficHook: cdk.Lazy.stringValue({ produce: () => this.preHook && this.preHook.functionName }),
afterAllowTrafficHook: cdk.Lazy.stringValue({ produce: () => this.postHook && this.postHook.functionName }),
}
};
}
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-codedeploy/lib/server/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export class ServerApplication extends Resource implements IServerApplication {
computePlatform: 'Server',
});

this.applicationName = resource.ref;
this.applicationName = resource.refAsString;
this.applicationArn = arnForApplication(this.applicationName);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export class ServerDeploymentConfig extends cdk.Resource implements IServerDeplo
minimumHealthyHosts: props.minimumHealthyHosts._json,
});

this.deploymentConfigName = resource.ref.toString();
this.deploymentConfigName = resource.refAsString;
this.deploymentConfigArn = arnForDeploymentConfig(this.deploymentConfigName);
}
}
Expand All @@ -125,4 +125,4 @@ function deploymentConfig(name: string): IServerDeploymentConfig {
};
}

function ignore(_x: any) { return; }
function ignore(_x: any) { return; }
Original file line number Diff line number Diff line change
Expand Up @@ -289,10 +289,7 @@ export class ServerDeploymentGroup extends ServerDeploymentGroupBase {
serviceRoleArn: this.role.roleArn,
deploymentConfigName: props.deploymentConfig &&
props.deploymentConfig.deploymentConfigName,
autoScalingGroups: new cdk.Token(() =>
this._autoScalingGroups.length === 0
? undefined
: this._autoScalingGroups.map(asg => asg.autoScalingGroupName)).toList(),
autoScalingGroups: cdk.Lazy.listValue({ produce: () => this._autoScalingGroups.map(asg => asg.autoScalingGroupName) }, { omitEmpty: true }),
loadBalancerInfo: this.loadBalancerInfo(props.loadBalancer),
deploymentStyle: props.loadBalancer === undefined
? undefined
Expand All @@ -301,8 +298,8 @@ export class ServerDeploymentGroup extends ServerDeploymentGroupBase {
},
ec2TagSet: this.ec2TagSet(props.ec2InstanceTags),
onPremisesTagSet: this.onPremiseTagSet(props.onPremiseInstanceTags),
alarmConfiguration: new cdk.Token(() => renderAlarmConfiguration(this.alarms, props.ignorePollAlarmsFailure)),
autoRollbackConfiguration: new cdk.Token(() => renderAutoRollbackConfiguration(this.alarms, props.autoRollback)),
alarmConfiguration: cdk.Lazy.anyValue({ produce: () => renderAlarmConfiguration(this.alarms, props.ignorePollAlarmsFailure) }),
autoRollbackConfiguration: cdk.Lazy.anyValue({ produce: () => renderAutoRollbackConfiguration(this.alarms, props.autoRollback) }),
});

this.deploymentGroupName = resource.deploymentGroupName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,8 @@ export abstract class CloudFormationDeployAction extends CloudFormationAction {
...configuration,
// None evaluates to empty string which is falsey and results in undefined
Capabilities: (capabilities && capabilities.toString()) || undefined,
RoleArn: new cdk.Token(() => this.deploymentRole.roleArn),
ParameterOverrides: new cdk.Token(() => this.scope.node.stringifyJson(props.parameterOverrides)),
RoleArn: cdk.Lazy.stringValue({ produce: () => this.deploymentRole.roleArn }),
ParameterOverrides: cdk.Lazy.stringValue({ produce: () => this.scope.node.stringifyJson(props.parameterOverrides) }),
TemplateConfiguration: props.templateConfiguration ? props.templateConfiguration.location : undefined,
StackName: props.stackName,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export class CodeBuildAction extends codepipeline.Action {
this.props = props;

if (this.inputs.length > 1) {
this.configuration.PrimarySource = new cdk.Token(() => this.inputs[0].artifactName);
this.configuration.PrimarySource = cdk.Lazy.stringValue({ produce: () => this.inputs[0].artifactName });
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class ManualApprovalAction extends codepipeline.Action {
category: codepipeline.ActionCategory.Approval,
provider: 'Manual',
artifactBounds: { minInputs: 0, maxInputs: 0, minOutputs: 0, maxOutputs: 0 },
configuration: new cdk.Token(() => this.actionConfiguration()),
configuration: cdk.Lazy.anyValue({ produce: () => this.actionConfiguration() }),
});

this.props = props;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect, haveResourceLike } from "@aws-cdk/assert";
import codepipeline = require('@aws-cdk/aws-codepipeline');
import lambda = require('@aws-cdk/aws-lambda');
import { Aws, SecretValue, Stack, Token } from "@aws-cdk/cdk";
import { Aws, Intrinsic, Lazy, SecretValue, Stack } from "@aws-cdk/cdk";
import { Test } from 'nodeunit';
import cpactions = require('../../lib');

Expand Down Expand Up @@ -34,7 +34,7 @@ export = {

'properly resolves any Tokens passed in userParameters'(test: Test) {
const stack = stackIncludingLambdaInvokeCodePipeline({
key: new Token(() => Aws.region),
key: Lazy.stringValue({ produce: () => Aws.region }),
});

expect(stack).to(haveResourceLike('AWS::CodePipeline::Pipeline', {
Expand Down Expand Up @@ -68,7 +68,7 @@ export = {

'properly resolves any stringified Tokens passed in userParameters'(test: Test) {
const stack = stackIncludingLambdaInvokeCodePipeline({
key: new Token(() => null).toString(),
key: new Intrinsic(null).toString(),
});

expect(stack).to(haveResourceLike('AWS::CodePipeline::Pipeline', {
Expand Down
Loading