Skip to content

Commit

Permalink
Merge branch 'master' into feat/lambda-python/improve-bundling
Browse files Browse the repository at this point in the history
  • Loading branch information
mergify[bot] committed Dec 30, 2021
2 parents 5e48214 + 7d0680a commit b94dbac
Show file tree
Hide file tree
Showing 44 changed files with 2,006 additions and 599 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
},
"devDependencies": {
"@yarnpkg/lockfile": "^1.1.0",
"cdk-generate-synthetic-examples": "^0.1.1",
"conventional-changelog-cli": "^2.2.2",
"fs-extra": "^9.1.0",
"graceful-fs": "^4.2.8",
Expand All @@ -27,8 +28,7 @@
"lerna": "^4.0.0",
"patch-package": "^6.4.7",
"standard-version": "^9.3.2",
"typescript": "~3.9.10",
"cdk-generate-synthetic-examples": "^0.1.1"
"typescript": "~3.9.10"
},
"resolutions": {
"string-width": "^4.2.3"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
"@aws-cdk/cdk-build-tools": "0.0.0",
"@aws-cdk/cdk-integ-tools": "0.0.0",
"@aws-cdk/pkglint": "0.0.0",
"@types/aws-lambda": "^8.10.88",
"@types/aws-lambda": "^8.10.89",
"@types/jest": "^27.0.3"
},
"dependencies": {
Expand Down
26 changes: 26 additions & 0 deletions packages/@aws-cdk/aws-autoscaling/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,32 @@ new autoscaling.AutoScalingGroup(this, 'ASG', {
});
```

## Termination policies

Auto Scaling uses [termination policies](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html)
to determine which instances it terminates first during scale-in events. You
can specify one or more termination policies with the `terminationPolicies`
property:

```ts
declare const vpc: ec2.Vpc;
declare const instanceType: ec2.InstanceType;
declare const machineImage: ec2.IMachineImage;

new autoscaling.AutoScalingGroup(this, 'ASG', {
vpc,
instanceType,
machineImage,

// ...

terminationPolicies: [
autoscaling.TerminationPolicy.OLDEST_INSTANCE,
autoscaling.TerminationPolicy.DEFAULT,
],
});
```

## Protecting new instances from being terminated on scale-in

By default, Auto Scaling can terminate an instance at any time after launch when
Expand Down
12 changes: 12 additions & 0 deletions packages/@aws-cdk/aws-autoscaling/lib/auto-scaling-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { BasicLifecycleHookProps, LifecycleHook } from './lifecycle-hook';
import { BasicScheduledActionProps, ScheduledAction } from './scheduled-action';
import { BasicStepScalingPolicyProps, StepScalingPolicy } from './step-scaling-policy';
import { BaseTargetTrackingProps, PredefinedMetric, TargetTrackingScalingPolicy } from './target-tracking-scaling-policy';
import { TerminationPolicy } from './termination-policy';
import { BlockDevice, BlockDeviceVolume, EbsDeviceVolumeType } from './volume';

/**
Expand Down Expand Up @@ -314,6 +315,16 @@ export interface CommonAutoScalingGroupProps {
* @default - Auto generated by CloudFormation
*/
readonly autoScalingGroupName?: string;

/**
* A policy or a list of policies that are used to select the instances to
* terminate. The policies are executed in the order that you list them.
*
* @see https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html
*
* @default - `TerminationPolicy.DEFAULT`
*/
readonly terminationPolicies?: TerminationPolicy[];
}

/**
Expand Down Expand Up @@ -1052,6 +1063,7 @@ export class AutoScalingGroup extends AutoScalingGroupBase implements
healthCheckGracePeriod: props.healthCheck && props.healthCheck.gracePeriod && props.healthCheck.gracePeriod.toSeconds(),
maxInstanceLifetime: this.maxInstanceLifetime ? this.maxInstanceLifetime.toSeconds() : undefined,
newInstancesProtectedFromScaleIn: Lazy.any({ produce: () => this.newInstancesProtectedFromScaleIn }),
terminationPolicies: props.terminationPolicies,
};

if (!hasPublic && props.associatePublicIpAddress) {
Expand Down
3 changes: 2 additions & 1 deletion packages/@aws-cdk/aws-autoscaling/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ export * from './scheduled-action';
export * from './step-scaling-action';
export * from './step-scaling-policy';
export * from './target-tracking-scaling-policy';
export * from './termination-policy';
export * from './volume';

// AWS::AutoScaling CloudFormation Resources:
export * from './autoscaling.generated';
export * from './autoscaling.generated';
42 changes: 42 additions & 0 deletions packages/@aws-cdk/aws-autoscaling/lib/termination-policy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* Specifies the termination criteria to apply before Amazon EC2 Auto Scaling
* chooses an instance for termination.
*/
export enum TerminationPolicy {
/**
* Terminate instances in the Auto Scaling group to align the remaining
* instances to the allocation strategy for the type of instance that is
* terminating (either a Spot Instance or an On-Demand Instance).
*/
ALLOCATION_STRATEGY = 'AllocationStrategy',

/**
* Terminate instances that are closest to the next billing hour.
*/
CLOSEST_TO_NEXT_INSTANCE_HOUR = 'ClosestToNextInstanceHour',

/**
* Terminate instances according to the default termination policy.
*/
DEFAULT = 'Default',

/**
* Terminate the newest instance in the group.
*/
NEWEST_INSTANCE = 'NewestInstance',

/**
* Terminate the oldest instance in the group.
*/
OLDEST_INSTANCE = 'OldestInstance',

/**
* Terminate instances that have the oldest launch configuration.
*/
OLDEST_LAUNCH_CONFIGURATION = 'OldestLaunchConfiguration',

/**
* Terminate instances that have the oldest launch template.
*/
OLDEST_LAUNCH_TEMPLATE = 'OldestLaunchTemplate',
}
25 changes: 25 additions & 0 deletions packages/@aws-cdk/aws-autoscaling/test/auto-scaling-group.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1382,6 +1382,31 @@ describe('auto scaling group', () => {
},
});
});

test('supports termination policies', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = mockVpc(stack);

// WHEN
new autoscaling.AutoScalingGroup(stack, 'MyASG', {
vpc,
instanceType: new ec2.InstanceType('t2.micro'),
machineImage: ec2.MachineImage.latestAmazonLinux(),
terminationPolicies: [
autoscaling.TerminationPolicy.OLDEST_INSTANCE,
autoscaling.TerminationPolicy.DEFAULT,
],
});

// THEN
expect(stack).toHaveResource('AWS::AutoScaling::AutoScalingGroup', {
TerminationPolicies: [
'OldestInstance',
'Default',
],
});
});
});

function mockVpc(stack: cdk.Stack) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
},
"license": "Apache-2.0",
"devDependencies": {
"@types/aws-lambda": "^8.10.88",
"@types/aws-lambda": "^8.10.89",
"@types/sinon": "^9.0.11",
"@aws-cdk/cdk-build-tools": "0.0.0",
"aws-sdk": "^2.596.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-cloudformation/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
"@aws-cdk/cdk-integ-tools": "0.0.0",
"@aws-cdk/cfn2ts": "0.0.0",
"@aws-cdk/pkglint": "0.0.0",
"@types/aws-lambda": "^8.10.88",
"@types/aws-lambda": "^8.10.89",
"@types/jest": "^27.0.3",
"jest": "^27.4.5"
},
Expand Down
19 changes: 9 additions & 10 deletions packages/@aws-cdk/aws-cloudfront-origins/lib/s3-origin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,17 +73,16 @@ class S3BucketOrigin extends cloudfront.OriginBase {
this.originAccessIdentity = new cloudfront.OriginAccessIdentity(oaiScope, oaiId, {
comment: `Identity for ${options.originId}`,
});

// Used rather than `grantRead` because `grantRead` will grant overly-permissive policies.
// Only GetObject is needed to retrieve objects for the distribution.
// This also excludes KMS permissions; currently, OAI only supports SSE-S3 for buckets.
// Source: https://aws.amazon.com/blogs/networking-and-content-delivery/serving-sse-kms-encrypted-content-from-s3-using-cloudfront/
this.bucket.addToResourcePolicy(new iam.PolicyStatement({
resources: [this.bucket.arnForObjects('*')],
actions: ['s3:GetObject'],
principals: [this.originAccessIdentity.grantPrincipal],
}));
}
// Used rather than `grantRead` because `grantRead` will grant overly-permissive policies.
// Only GetObject is needed to retrieve objects for the distribution.
// This also excludes KMS permissions; currently, OAI only supports SSE-S3 for buckets.
// Source: https://aws.amazon.com/blogs/networking-and-content-delivery/serving-sse-kms-encrypted-content-from-s3-using-cloudfront/
this.bucket.addToResourcePolicy(new iam.PolicyStatement({
resources: [this.bucket.arnForObjects('*')],
actions: ['s3:GetObject'],
principals: [this.originAccessIdentity.grantPrincipal],
}));
return super.bind(scope, options);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,45 @@
"UpdateReplacePolicy": "Retain",
"DeletionPolicy": "Retain"
},
"BucketPolicyE9A3008A": {
"Type": "AWS::S3::BucketPolicy",
"Properties": {
"Bucket": {
"Ref": "Bucket83908E77"
},
"PolicyDocument": {
"Statement": [
{
"Action": "s3:GetObject",
"Effect": "Allow",
"Principal": {
"CanonicalUser": {
"Fn::GetAtt": [
"OriginAccessIdentityDF1E3CAC",
"S3CanonicalUserId"
]
}
},
"Resource": {
"Fn::Join": [
"",
[
{
"Fn::GetAtt": [
"Bucket83908E77",
"Arn"
]
},
"/*"
]
]
}
}
],
"Version": "2012-10-17"
}
}
},
"OriginAccessIdentityDF1E3CAC": {
"Type": "AWS::CloudFront::CloudFrontOriginAccessIdentity",
"Properties": {
Expand Down
14 changes: 14 additions & 0 deletions packages/@aws-cdk/aws-cloudfront-origins/test/s3-origin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,20 @@ describe('With bucket', () => {
Comment: 'Identity for bucket provided by test',
},
});

expect(stack).toHaveResourceLike('AWS::S3::BucketPolicy', {
PolicyDocument: {
Statement: [{
Action: 's3:GetObject',
Principal: {
CanonicalUser: { 'Fn::GetAtt': ['OriginAccessIdentityDF1E3CAC', 'S3CanonicalUserId'] },
},
Resource: {
'Fn::Join': ['', [{ 'Fn::GetAtt': ['Bucket83908E77', 'Arn'] }, '/*']],
},
}],
},
});
});

test('creates an OriginAccessIdentity and grants read permissions on the bucket', () => {
Expand Down
29 changes: 29 additions & 0 deletions packages/@aws-cdk/aws-codepipeline-actions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,35 @@ const sourceAction = new codepipeline_actions.CodeStarConnectionsSourceAction({
You can also use the `CodeStarConnectionsSourceAction` to connect to GitHub, in the same way
(you just have to select GitHub as the source when creating the connection in the console).

Similarly to `GitHubSourceAction`, `CodeStarConnectionsSourceAction` also emits the variables:

```ts
declare const project: codebuild.Project;

const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeStarConnectionsSourceAction({
actionName: 'BitBucket_Source',
owner: 'aws',
repo: 'aws-cdk',
output: sourceOutput,
connectionArn: 'arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh',
variablesNamespace: 'SomeSpace', // optional - by default, a name will be generated for you
});

// later:

new codepipeline_actions.CodeBuildAction({
actionName: 'CodeBuild',
project,
input: sourceOutput,
environmentVariables: {
COMMIT_ID: {
value: sourceAction.variables.commitId,
},
},
});
```

### AWS S3 Source

To use an S3 Bucket as a source in CodePipeline:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,24 @@ import { sourceArtifactBounds } from '../common';
// eslint-disable-next-line no-duplicate-imports, import/order
import { Construct } from '@aws-cdk/core';

/**
* The CodePipeline variables emitted by CodeStar source Action.
*/
export interface CodeStarSourceVariables {
/** The name of the repository this action points to. */
readonly fullRepositoryName: string;
/** The name of the branch this action tracks. */
readonly branchName: string;
/** The date the currently last commit on the tracked branch was authored, in ISO-8601 format. */
readonly authorDate: string;
/** The SHA1 hash of the currently last commit on the tracked branch. */
readonly commitId: string;
/** The message of the currently last commit on the tracked branch. */
readonly commitMessage: string;
/** The connection ARN this source uses. */
readonly connectionArn: string;
}

/**
* Construction properties for {@link CodeStarConnectionsSourceAction}.
*/
Expand Down Expand Up @@ -101,6 +119,18 @@ export class CodeStarConnectionsSourceAction extends Action {
this.props = props;
}

/** The variables emitted by this action. */
public get variables(): CodeStarSourceVariables {
return {
fullRepositoryName: this.variableExpression('FullRepositoryName'),
branchName: this.variableExpression('BranchName'),
authorDate: this.variableExpression('AuthorDate'),
commitId: this.variableExpression('CommitId'),
commitMessage: this.variableExpression('CommitMessage'),
connectionArn: this.variableExpression('ConnectionArn'),
};
}

protected bound(_scope: Construct, _stage: codepipeline.IStage, options: codepipeline.ActionBindOptions): codepipeline.ActionConfig {
// https://docs.aws.amazon.com/codepipeline/latest/userguide/security-iam.html#how-to-update-role-new-services
options.role.addToPolicy(new iam.PolicyStatement({
Expand Down
Loading

0 comments on commit b94dbac

Please sign in to comment.