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

feat: idiomize cloudformation intrinsics and pseudo parameters #1428

Merged
merged 10 commits into from
Dec 27, 2018
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -1700,7 +1700,7 @@ Fn.if_(Fn.equals(param.ref, 'True'), 'Encrypted', Pseudo.NO_VALUE)
After:

```javascript
new FnIf(new FnEquals(param.ref, 'True'), 'Encrypted', new AwsNoValue())
new FnIf(Fn.equals(param.ref, 'True'), 'Encrypted', new AwsNoValue())
```

- CloudFormation template options (`templateFormatVersion`, `description` and `transform`) are now grouped under `Stack.templateOptions` instead of directly under `Stack`.
Expand Down
8 changes: 4 additions & 4 deletions docs/src/cloudformation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,8 @@ Intrinsic Functions

.. code-block:: js

import cdk = require('@aws-cdk/cdk');
new cdk.FnJoin(",", [...])
import { Fn } from'@aws-cdk/cdk';
Fn.join(",", [...])

.. _pseudo_parameters:

Expand All @@ -183,8 +183,8 @@ Pseudo Parameters

.. code-block:: js

import cdk = require('@aws-cdk/cdk');
new cdk.AwsRegion()
import { Aws } from '@aws-cdk/cdk';
Aws.region

.. Add a new topic in "Advanced Topics" about integrating
cdk synch > mytemplate
Expand Down
2 changes: 1 addition & 1 deletion docs/src/constructs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ Construct IDs may be any string with the following caveats:
* Path separators (``/``s) will be replaced by double-dashes ``--``. This means
that if you are trying to look up a child construct that may have a path separator,
you will need to manually replace it with ``--``.
* Construct IDs may not include unresolved tokens (such as `new AwsRegion()`). This is
* Construct IDs may not include unresolved tokens (such as `Aws.region`). This is
because those tokens are only resolved during deployment, and therefore cannot be used
to render a stable logical ID for any resources in this tree.

Expand Down
30 changes: 15 additions & 15 deletions examples/cdk-examples-typescript/advanced-usage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ class CloudFormationExample extends cdk.Stack {
// outputs are constructs the synthesize into the template's "Outputs" section
new cdk.Output(this, 'Output', {
description: 'This is an output of the template',
value: new cdk.FnConcat(new cdk.AwsAccountId(), '/', param.ref)
value: `${cdk.Aws.accountId}/${param.ref}`
});

// stack.templateOptions can be used to specify template-level options
Expand All @@ -166,23 +166,23 @@ class CloudFormationExample extends cdk.Stack {

// all CloudFormation's pseudo-parameters are supported via the `cdk.AwsXxx` classes
PseudoParameters: [
new cdk.AwsAccountId(),
new cdk.AwsDomainSuffix(),
new cdk.AwsNotificationARNs(),
new cdk.AwsNoValue(),
new cdk.AwsPartition(),
new cdk.AwsRegion(),
new cdk.AwsStackId(),
new cdk.AwsStackName(),
cdk.Aws.accountId,
cdk.Aws.domainSuffix,
cdk.Aws.notificationARNs,
cdk.Aws.noValue,
cdk.Aws.partition,
cdk.Aws.region,
cdk.Aws.stackId,
cdk.Aws.stackName,
],

// all CloudFormation's intrinsic functions are supported via the `cdk.FnXxx` classes
// all CloudFormation's intrinsic functions are supported via the `cdk.Fn.xxx` static methods.
IntrinsicFunctions: [
new cdk.FnAnd(
new cdk.FnFindInMap('MyMap', 'K1', 'K2'),
new cdk.FnSub('hello ${world}', {
world: new cdk.FnBase64(param.ref) // resolves to { Ref: <param-id> }
}))
cdk.Fn.join('', [
cdk.Fn.findInMap('MyMap', 'K1', 'K2'),
cdk.Fn.sub('hello ${world}', {
world: cdk.Fn.base64(param.ref) // resolves to { Ref: <param-id> }
}) ])
],
};
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"pkglint": "tools/pkglint/bin/pkglint -f ."
},
"devDependencies": {
"@types/node": "^8.10.38",
"@types/node": "8.10.38",
Copy link
Contributor

Choose a reason for hiding this comment

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

Why the pinning?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

For some reason it seems like npm keeps moving us to 10.x when we build in CI and then we get these unsolicited breakage of master. Other ideas?

"@types/nodeunit": "^0.0.30",
"conventional-changelog-cli": "^2.0.5",
"lerna": "^3.3.0",
Expand Down
6 changes: 3 additions & 3 deletions packages/@aws-cdk/assets-docker/lib/image-asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ export class DockerImageAsset extends cdk.Construct {
this.addMetadata(cxapi.ASSET_METADATA, asset);

// parse repository name and tag from the parameter (<REPO_NAME>:<TAG>)
const components = new cdk.FnSplit(':', imageNameParameter.value);
const repositoryName = new cdk.FnSelect(0, components).toString();
const imageTag = new cdk.FnSelect(1, components).toString();
const components = cdk.Fn.split(':', imageNameParameter.valueAsString);
const repositoryName = cdk.Fn.select(0, components).toString();
const imageTag = cdk.Fn.select(1, components).toString();

// Require that repository adoption happens first, so we route the
// input ARN into the Custom Resource and then get the URI which we use to
Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/assets/lib/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ export class Asset extends cdk.Construct {
});

this.s3BucketName = bucketParam.value.toString();
this.s3Prefix = new cdk.FnSelect(0, new cdk.FnSplit(cxapi.ASSET_PREFIX_SEPARATOR, keyParam.value)).toString();
const s3Filename = new cdk.FnSelect(1, new cdk.FnSplit(cxapi.ASSET_PREFIX_SEPARATOR, keyParam.value)).toString();
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.bucket = s3.BucketRef.import(this, 'AssetBucket', {
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 @@ -173,7 +173,7 @@ export class Stage extends cdk.Construct implements cdk.IDependable {
if (!path.startsWith('/')) {
throw new Error(`Path must begin with "/": ${path}`);
}
return `https://${this.restApi.restApiId}.execute-api.${new cdk.AwsRegion()}.amazonaws.com/${this.stageName}${path}`;
return `https://${this.restApi.restApiId}.execute-api.${cdk.Aws.region}.amazonaws.com/${this.stageName}${path}`;
}

private renderMethodSettings(props: StageProps): CfnStage.MethodSettingProperty[] | undefined {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ export class AutoScalingGroup extends cdk.Construct implements IAutoScalingGroup

// use delayed evaluation
const machineImage = props.machineImage.getImage(this);
const userDataToken = new cdk.Token(() => new cdk.FnBase64((machineImage.os.createUserData(this.userDataLines))));
const userDataToken = new cdk.Token(() => cdk.Fn.base64((machineImage.os.createUserData(this.userDataLines))));
const securityGroupsToken = new cdk.Token(() => this.securityGroups.map(sg => sg.securityGroupId));

const launchConfig = new CfnLaunchConfiguration(this, 'LaunchConfig', {
Expand Down
4 changes: 1 addition & 3 deletions packages/@aws-cdk/aws-cloudfront/lib/web_distribution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -574,9 +574,7 @@ export class CloudFrontWebDistribution extends cdk.Construct implements route53.

if (originConfig.s3OriginSource && originConfig.s3OriginSource.originAccessIdentity) {
originProperty.s3OriginConfig = {
originAccessIdentity: new cdk.FnConcat(
"origin-access-identity/cloudfront/", originConfig.s3OriginSource.originAccessIdentity.ref
),
originAccessIdentity: `origin-access-identity/cloudfront/${originConfig.s3OriginSource.originAccessIdentity.ref}`
eladb marked this conversation as resolved.
Show resolved Hide resolved
};
} else if (originConfig.s3OriginSource) {
originProperty.s3OriginConfig = {};
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-cloudtrail/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export class CloudTrail extends cdk.Construct {
.addServicePrincipal(cloudTrailPrincipal));

s3bucket.addToResourcePolicy(new iam.PolicyStatement()
.addResource(s3bucket.arnForObjects(new cdk.FnConcat('AWSLogs/', new cdk.AwsAccountId(), "/*")))
.addResource(s3bucket.arnForObjects(`AWSLogs/${cdk.Aws.accountId}/*`))
.addActions("s3:PutObject")
.addServicePrincipal(cloudTrailPrincipal)
.setCondition("StringEquals", {'s3:x-amz-acl': "bucket-owner-full-control"}));
Expand Down
8 changes: 4 additions & 4 deletions packages/@aws-cdk/aws-cloudwatch/lib/graph.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AwsRegion } from "@aws-cdk/cdk";
import { Aws } from "@aws-cdk/cdk";
import { Alarm } from "./alarm";
import { Metric } from "./metric";
import { parseStatistic } from './util.statistic';
Expand Down Expand Up @@ -73,7 +73,7 @@ export class AlarmWidget extends ConcreteWidget {
properties: {
view: 'timeSeries',
title: this.props.title,
region: this.props.region || new AwsRegion(),
region: this.props.region || Aws.region,
annotations: {
alarms: [this.props.alarm.alarmArn]
},
Expand Down Expand Up @@ -150,7 +150,7 @@ export class GraphWidget extends ConcreteWidget {
properties: {
view: 'timeSeries',
title: this.props.title,
region: this.props.region || new AwsRegion(),
region: this.props.region || Aws.region,
metrics: (this.props.left || []).map(m => metricJson(m, 'left')).concat(
(this.props.right || []).map(m => metricJson(m, 'right'))),
annotations: {
Expand Down Expand Up @@ -197,7 +197,7 @@ export class SingleValueWidget extends ConcreteWidget {
properties: {
view: 'singleValue',
title: this.props.title,
region: this.props.region || new AwsRegion(),
region: this.props.region || Aws.region,
metrics: this.props.metrics.map(m => metricJson(m, 'left'))
}
}];
Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/aws-codebuild/lib/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,10 +495,10 @@ export class Project extends ProjectRef {

let cache: CfnProject.ProjectCacheProperty | undefined;
if (props.cacheBucket) {
const cacheDir = props.cacheDir != null ? props.cacheDir : new cdk.AwsNoValue();
const cacheDir = props.cacheDir != null ? props.cacheDir : cdk.Aws.noValue;
cache = {
type: 'S3',
location: new cdk.FnJoin('/', [props.cacheBucket.bucketName, cacheDir]),
location: cdk.Fn.join('/', [props.cacheBucket.bucketName, cacheDir]),
};

props.cacheBucket.grantReadWrite(this.role);
Expand Down
12 changes: 6 additions & 6 deletions packages/@aws-cdk/aws-codebuild/test/test.codebuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -855,14 +855,14 @@ export = {
new codebuild.Project(stack, 'Project', {
source: new codebuild.CodePipelineSource(),
environment: {
environmentVariables: {
FOO: { value: '1234' },
BAR: { value: new cdk.FnConcat('111', { twotwotwo: '222' }), type: codebuild.BuildEnvironmentVariableType.ParameterStore }
}
environmentVariables: {
FOO: { value: '1234' },
BAR: { value: `111${new cdk.CloudFormationToken({ twotwotwo: '222' })}`, type: codebuild.BuildEnvironmentVariableType.ParameterStore }
}
},
environmentVariables: {
eladb marked this conversation as resolved.
Show resolved Hide resolved
GOO: { value: 'ABC' },
FOO: { value: 'OVERRIDE!' }
GOO: { value: 'ABC' },
FOO: { value: 'OVERRIDE!' }
}
});

Expand Down
7 changes: 1 addition & 6 deletions packages/@aws-cdk/aws-codecommit/lib/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,7 @@ class ImportedRepositoryRef extends RepositoryRef {
}

private repositoryCloneUrl(protocol: 'https' | 'ssh'): string {
return new cdk.FnConcat(`${protocol}://git-codecommit.`,
new cdk.AwsRegion(),
'.',
new cdk.AwsURLSuffix(),
'/v1/repos/',
this.repositoryName).toString();
return `${protocol}://git-codecommit.${cdk.Aws.region}.${cdk.Aws.urlSuffix}/v1/repos/${this.repositoryName}`;
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/aws-codedeploy/lib/deployment-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ export class ServerDeploymentGroup extends ServerDeploymentGroupRef {

this._autoScalingGroups = props.autoScalingGroups || [];
this.installAgent = props.installAgent === undefined ? true : props.installAgent;
const region = (new cdk.AwsRegion()).toString();
const region = (cdk.Aws.region).toString();
this.codeDeployBucket = s3.BucketRef.import(this, 'CodeDeployBucket', {
bucketName: `aws-codedeploy-${region}`,
});
Expand Down Expand Up @@ -371,7 +371,7 @@ export class ServerDeploymentGroup extends ServerDeploymentGroupRef {

this.codeDeployBucket.grantRead(asg.role, 'latest/*');

const region = (new cdk.AwsRegion()).toString();
const region = (cdk.Aws.region).toString();
switch (asg.osType) {
case ec2.OperatingSystemType.Linux:
asg.addUserData(
Expand Down
8 changes: 4 additions & 4 deletions packages/@aws-cdk/aws-ecr/test/test.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ export = {

// WHEN/THEN
test.throws(() => ecr.Repository.import(stack, 'Repo', {
repositoryArn: new cdk.FnGetAtt('Boom', 'Boom').toString()
repositoryArn: cdk.Fn.getAtt('Boom', 'Boom').toString()
}), /repositoryArn is a late-bound value, and therefore repositoryName is required/);

test.done();
Expand All @@ -204,8 +204,8 @@ export = {

// WHEN
const repo = ecr.Repository.import(stack, 'Repo', {
repositoryArn: new cdk.FnGetAtt('Boom', 'Arn').toString(),
repositoryName: new cdk.FnGetAtt('Boom', 'Name').toString()
repositoryArn: cdk.Fn.getAtt('Boom', 'Arn').toString(),
repositoryName: cdk.Fn.getAtt('Boom', 'Name').toString()
});

// THEN
Expand Down Expand Up @@ -242,7 +242,7 @@ export = {
'arnForLocalRepository can be used to render an ARN for a local repository'(test: Test) {
// GIVEN
const stack = new cdk.Stack();
const repoName = new cdk.FnGetAtt('Boom', 'Name').toString();
const repoName = cdk.Fn.getAtt('Boom', 'Name').toString();

// WHEN
const repo = ecr.Repository.import(stack, 'Repo', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export class AwsLogDriver extends LogDriver {
options: removeEmpty({
'awslogs-group': this.logGroup.logGroupName,
'awslogs-stream-prefix': this.props.streamPrefix,
'awslogs-region': `${new cdk.AwsRegion()}`,
'awslogs-region': cdk.Aws.region,
'awslogs-datetime-format': this.props.datetimeFormat,
'awslogs-multiline-pattern': this.props.multilinePattern,
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,6 @@ export interface LoadBalancerTargetProps {
* app/my-load-balancer/50dc6c495c0c9188
*/
export function loadBalancerNameFromListenerArn(listenerArn: string) {
const arnParts = new cdk.FnSplit('/', listenerArn);
return `${new cdk.FnSelect(1, arnParts)}/${new cdk.FnSelect(2, arnParts)}/${new cdk.FnSelect(3, arnParts)}`;
const arnParts = cdk.Fn.split('/', listenerArn);
eladb marked this conversation as resolved.
Show resolved Hide resolved
return `${cdk.Fn.select(1, arnParts)}/${cdk.Fn.select(2, arnParts)}/${cdk.Fn.select(3, arnParts)}`;
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ export class BaseImportedTargetGroup extends cdk.Construct {
super(parent, id);

this.targetGroupArn = props.targetGroupArn;
this.loadBalancerArns = props.loadBalancerArns || new cdk.AwsNoValue().toString();
this.loadBalancerArns = props.loadBalancerArns || cdk.Aws.noValue;
}
}
10 changes: 5 additions & 5 deletions packages/@aws-cdk/aws-events/lib/input-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ export interface TargetInputTemplate {
* @example
*
* {
* textTemplate: 'Build <buildid> started',
* pathsMap: {
* buildid: '$.detail.id'
* }
* textTemplate: 'Build <buildid> started',
* pathsMap: {
* buildid: '$.detail.id'
* }
* }
*/
textTemplate?: any;
textTemplate?: string;

/**
* Input template where you can use the values of the keys from
Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/aws-events/lib/rule.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Construct, FnConcat, Token } from '@aws-cdk/cdk';
import { Construct, Token } from '@aws-cdk/cdk';
import { EventPattern } from './event-pattern';
import { CfnRule } from './events.generated';
import { TargetInputTemplate } from './input-options';
Expand Down Expand Up @@ -133,7 +133,7 @@ export class EventRule extends EventRuleRef {
} else if (typeof(inputOptions.textTemplate) === 'string') {
inputTemplate = JSON.stringify(inputOptions.textTemplate);
} else {
inputTemplate = new FnConcat('"', inputOptions.textTemplate, '"');
inputTemplate = `"${inputOptions.textTemplate}"`;
}

return {
Expand Down
4 changes: 2 additions & 2 deletions packages/@aws-cdk/aws-events/test/test.rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ export = {
// tokens are used here (FnConcat), but this is a text template so we
// expect it to be wrapped in double quotes automatically for us.
rule.addTarget(t1, {
textTemplate: new cdk.FnConcat('a', 'b')
textTemplate: cdk.Fn.join('', [ 'a', 'b' ]).toString()
});

// jsonTemplate can be used to format JSON documents with replacements
Expand All @@ -252,7 +252,7 @@ export = {
// tokens can also used for JSON templates, but that means escaping is
// the responsibility of the user.
rule.addTarget(t4, {
jsonTemplate: new cdk.FnJoin(' ', ['"', 'hello', '\"world\"', '"']),
jsonTemplate: cdk.Fn.join(' ', ['"', 'hello', '\"world\"', '"']),
});

expect(stack).toMatch({
Expand Down
6 changes: 3 additions & 3 deletions packages/@aws-cdk/aws-iam/lib/policy-document.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AwsAccountId, AwsPartition, Token } from '@aws-cdk/cdk';
import { Aws, Token } from '@aws-cdk/cdk';

export class PolicyDocument extends Token {
private statements = new Array<PolicyStatement>();
Expand Down Expand Up @@ -82,7 +82,7 @@ export class ArnPrincipal extends PolicyPrincipal {

export class AccountPrincipal extends ArnPrincipal {
constructor(public readonly accountId: any) {
super(`arn:${new AwsPartition()}:iam::${accountId}:root`);
super(`arn:${Aws.partition}:iam::${accountId}:root`);
}
}

Expand Down Expand Up @@ -137,7 +137,7 @@ export class FederatedPrincipal extends PolicyPrincipal {

export class AccountRootPrincipal extends AccountPrincipal {
constructor() {
super(new AwsAccountId());
super(Aws.accountId);
}
}

Expand Down
Loading