diff --git a/.projenrc.ts b/.projenrc.ts index d507f1d09..ed9424e07 100644 --- a/.projenrc.ts +++ b/.projenrc.ts @@ -808,6 +808,7 @@ const toolkitLib = configureProject( cdkAssetsLib.customizeReference({ versionType: 'any-minor' }), // stay within the same MV, otherwise any should work `${cxApi}@^2`, // stay within the same MV, otherwise any should work sdkDepForLib('@aws-sdk/client-appsync'), + sdkDepForLib('@aws-sdk/client-bedrock-agentcore-control'), sdkDepForLib('@aws-sdk/client-cloudformation'), sdkDepForLib('@aws-sdk/client-cloudwatch-logs'), sdkDepForLib('@aws-sdk/client-cloudcontrol'), @@ -1128,6 +1129,7 @@ const cli = configureProject( toolkitLib, 'archiver', '@aws-sdk/client-appsync', + '@aws-sdk/client-bedrock-agentcore-control', '@aws-sdk/client-cloudformation', '@aws-sdk/client-cloudwatch-logs', '@aws-sdk/client-cloudcontrol', diff --git a/packages/@aws-cdk-testing/cli-integ/resources/cdk-apps/app/app.js b/packages/@aws-cdk-testing/cli-integ/resources/cdk-apps/app/app.js index 2698d7983..74d052ca9 100755 --- a/packages/@aws-cdk-testing/cli-integ/resources/cdk-apps/app/app.js +++ b/packages/@aws-cdk-testing/cli-integ/resources/cdk-apps/app/app.js @@ -32,6 +32,7 @@ if (process.env.PACKAGE_LAYOUT_VERSION === '1') { aws_lambda_nodejs: node_lambda, aws_ecr_assets: docker, aws_appsync: appsync, + aws_bedrockagentcore: bedrockagentcore, Stack } = require('aws-cdk-lib'); } @@ -672,6 +673,43 @@ class EcsHotswapStack extends cdk.Stack { } } +class BedrockAgentCoreRuntimeHotswapStack extends cdk.Stack { + constructor(parent, id, props) { + super(parent, id, props); + + const role = new iam.Role(this, 'RuntimeRole', { + assumedBy: new iam.ServicePrincipal('bedrock-agentcore.amazonaws.com'), + managedPolicies: [ + iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonBedrockFullAccess'), + ], + }); + + const image = new docker.DockerImageAsset(this, 'Image', { + directory: path.join(__dirname, 'docker'), + }); + image.repository.grantPull(role); + + const runtime = new bedrockagentcore.CfnRuntime(this, 'Runtime', { + agentRuntimeName: 'test_runtime', + roleArn: role.roleArn, + networkConfiguration: { + networkMode: 'PUBLIC', + }, + agentRuntimeArtifact: { + containerConfiguration: { + containerUri: image.imageUri, + }, + }, + description: process.env.DYNAMIC_BEDROCK_RUNTIME_DESCRIPTION ?? 'runtime', + environmentVariables: { + TEST_VAR: process.env.DYNAMIC_BEDROCK_RUNTIME_ENV_VAR ?? 'original', + }, + }); + runtime.node.addDependency(role); + new cdk.CfnOutput(this, 'RuntimeId', { value: runtime.ref }); + } +} + class DockerStack extends cdk.Stack { constructor(parent, id, props) { super(parent, id, props); @@ -928,6 +966,7 @@ switch (stackSet) { new SessionTagsWithNoExecutionRoleCustomSynthesizerStack(app, `${stackPrefix}-session-tags-with-custom-synthesizer`); new LambdaHotswapStack(app, `${stackPrefix}-lambda-hotswap`); new EcsHotswapStack(app, `${stackPrefix}-ecs-hotswap`); + new BedrockAgentCoreRuntimeHotswapStack(app, `${stackPrefix}-bedrock-agentcore-runtime-hotswap`); new AppSyncHotswapStack(app, `${stackPrefix}-appsync-hotswap`); new DockerStack(app, `${stackPrefix}-docker`); new DockerInUseStack(app, `${stackPrefix}-docker-in-use`); diff --git a/packages/@aws-cdk-testing/cli-integ/tests/cli-integ-tests/hotswap/cdk-hotswap-deployment-supports-bedrock-agentcore-runtime.integtest.ts b/packages/@aws-cdk-testing/cli-integ/tests/cli-integ-tests/hotswap/cdk-hotswap-deployment-supports-bedrock-agentcore-runtime.integtest.ts new file mode 100644 index 000000000..15d08b533 --- /dev/null +++ b/packages/@aws-cdk-testing/cli-integ/tests/cli-integ-tests/hotswap/cdk-hotswap-deployment-supports-bedrock-agentcore-runtime.integtest.ts @@ -0,0 +1,45 @@ +import { DescribeStacksCommand } from '@aws-sdk/client-cloudformation'; +import { integTest, withDefaultFixture } from '../../../lib'; + +jest.setTimeout(2 * 60 * 60_000); // Includes the time to acquire locks, worst-case single-threaded runtime + +integTest( + 'hotswap deployment supports Bedrock AgentCore Runtime', + withDefaultFixture(async (fixture) => { + // GIVEN + const stackArn = await fixture.cdkDeploy('bedrock-agentcore-runtime-hotswap', { + captureStderr: false, + modEnv: { + DYNAMIC_BEDROCK_RUNTIME_DESCRIPTION: 'original description', + DYNAMIC_BEDROCK_RUNTIME_ENV_VAR: 'original value', + }, + }); + + // WHEN + const deployOutput = await fixture.cdkDeploy('bedrock-agentcore-runtime-hotswap', { + options: ['--hotswap'], + captureStderr: true, + onlyStderr: true, + modEnv: { + DYNAMIC_BEDROCK_RUNTIME_DESCRIPTION: 'new description', + DYNAMIC_BEDROCK_RUNTIME_ENV_VAR: 'new value', + }, + }); + + const response = await fixture.aws.cloudFormation.send( + new DescribeStacksCommand({ + StackName: stackArn, + }), + ); + const runtimeId = response.Stacks?.[0].Outputs?.find((output) => output.OutputKey === 'RuntimeId')?.OutputValue; + + // THEN + + // The deployment should not trigger a full deployment, thus the stack's status must remains + // "CREATE_COMPLETE" + expect(response.Stacks?.[0].StackStatus).toEqual('CREATE_COMPLETE'); + // The entire string fails locally due to formatting. Making this test less specific + expect(deployOutput).toMatch(/hotswapped!/); + expect(deployOutput).toContain(runtimeId); + }), +); diff --git a/packages/@aws-cdk/integ-runner/THIRD_PARTY_LICENSES b/packages/@aws-cdk/integ-runner/THIRD_PARTY_LICENSES index 885016856..250442584 100644 --- a/packages/@aws-cdk/integ-runner/THIRD_PARTY_LICENSES +++ b/packages/@aws-cdk/integ-runner/THIRD_PARTY_LICENSES @@ -822,6 +822,212 @@ The @aws-cdk/integ-runner package includes the following third-party software/li limitations under the License. +---------------- + +** @aws-sdk/client-bedrock-agentcore-control@3.953.0 - https://www.npmjs.com/package/@aws-sdk/client-bedrock-agentcore-control/v/3.953.0 | Apache-2.0 + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018-2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + ---------------- ** @aws-sdk/client-cloudcontrol@3.953.0 - https://www.npmjs.com/package/@aws-sdk/client-cloudcontrol/v/3.953.0 | Apache-2.0 diff --git a/packages/@aws-cdk/toolkit-lib/.projen/deps.json b/packages/@aws-cdk/toolkit-lib/.projen/deps.json index b8a584971..f3b3afc0c 100644 --- a/packages/@aws-cdk/toolkit-lib/.projen/deps.json +++ b/packages/@aws-cdk/toolkit-lib/.projen/deps.json @@ -189,6 +189,11 @@ "version": "^3", "type": "runtime" }, + { + "name": "@aws-sdk/client-bedrock-agentcore-control", + "version": "^3", + "type": "runtime" + }, { "name": "@aws-sdk/client-cloudcontrol", "version": "^3", diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts index 82583fe2b..588cd48cd 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts @@ -22,6 +22,17 @@ import { UpdateFunctionCommand, UpdateResolverCommand, } from '@aws-sdk/client-appsync'; +import type { + GetAgentRuntimeCommandInput, + GetAgentRuntimeCommandOutput, + UpdateAgentRuntimeCommandInput, + UpdateAgentRuntimeCommandOutput, +} from '@aws-sdk/client-bedrock-agentcore-control'; +import { + BedrockAgentCoreControlClient, + GetAgentRuntimeCommand, + UpdateAgentRuntimeCommand, +} from '@aws-sdk/client-bedrock-agentcore-control'; import type { GetResourceCommandInput, GetResourceCommandOutput, @@ -428,6 +439,11 @@ export interface IAppSyncClient { listFunctions(input: ListFunctionsCommandInput): Promise; } +export interface IBedrockAgentCoreControlClient { + getAgentRuntime(input: GetAgentRuntimeCommandInput): Promise; + updateAgentRuntime(input: UpdateAgentRuntimeCommandInput): Promise; +} + export interface ICloudControlClient { listResources(input: ListResourcesCommandInput): Promise; getResource(input: GetResourceCommandInput): Promise; @@ -682,6 +698,16 @@ export class SDK { }; } + public bedrockAgentCoreControl(): IBedrockAgentCoreControlClient { + const client = new BedrockAgentCoreControlClient(this.config); + return { + getAgentRuntime: (input: GetAgentRuntimeCommandInput): Promise => + client.send(new GetAgentRuntimeCommand(input)), + updateAgentRuntime: (input: UpdateAgentRuntimeCommandInput): Promise => + client.send(new UpdateAgentRuntimeCommand(input)), + }; + } + public cloudControl(): ICloudControlClient { const client = new CloudControlClient(this.config); return { diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/hotswap/bedrock-agentcore-runtimes.ts b/packages/@aws-cdk/toolkit-lib/lib/api/hotswap/bedrock-agentcore-runtimes.ts new file mode 100644 index 000000000..aea11740c --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/lib/api/hotswap/bedrock-agentcore-runtimes.ts @@ -0,0 +1,236 @@ +import type { PropertyDifference } from '@aws-cdk/cloudformation-diff'; +import type { + AgentRuntimeArtifact as SdkAgentRuntimeArtifact, + AgentManagedRuntimeType, +} from '@aws-sdk/client-bedrock-agentcore-control'; +import type { HotswapChange } from './common'; +import { classifyChanges } from './common'; +import type { ResourceChange } from '../../payloads/hotswap'; +import { ToolkitError } from '../../toolkit/toolkit-error'; +import type { SDK } from '../aws-auth/private'; +import type { EvaluateCloudFormationTemplate } from '../cloudformation'; + +export async function isHotswappableBedrockAgentCoreRuntimeChange( + logicalId: string, + change: ResourceChange, + evaluateCfnTemplate: EvaluateCloudFormationTemplate, +): Promise { + if (change.newValue.Type !== 'AWS::BedrockAgentCore::Runtime') { + return []; + } + + const ret: HotswapChange[] = []; + const classifiedChanges = classifyChanges(change, [ + 'AgentRuntimeArtifact', + 'EnvironmentVariables', + 'Description', + ]); + classifiedChanges.reportNonHotswappablePropertyChanges(ret); + + const namesOfHotswappableChanges = Object.keys(classifiedChanges.hotswappableProps); + if (namesOfHotswappableChanges.length === 0) { + return ret; + } + + const agentRuntimeId = await evaluateCfnTemplate.findPhysicalNameFor(logicalId); + if (!agentRuntimeId) { + return ret; + } + + const runtimeChange = await evaluateBedrockAgentCoreRuntimeProps( + classifiedChanges.hotswappableProps, + evaluateCfnTemplate, + ); + + ret.push({ + change: { + cause: change, + resources: [{ + logicalId, + resourceType: change.newValue.Type, + physicalName: agentRuntimeId, + metadata: evaluateCfnTemplate.metadataFor(logicalId), + }], + }, + hotswappable: true, + service: 'bedrock-agentcore', + apply: async (sdk: SDK) => { + const bedrockAgentCore = sdk.bedrockAgentCoreControl(); + + const currentRuntime = await bedrockAgentCore.getAgentRuntime({ + agentRuntimeId, + }); + + // While UpdateAgentRuntimeRequest type allows undefined, + // the API will fail at runtime if these required properties are not provided. + if (!currentRuntime.agentRuntimeArtifact) { + throw new ToolkitError('Current runtime does not have an artifact'); + } + if (!currentRuntime.roleArn) { + throw new ToolkitError('Current runtime does not have a roleArn'); + } + if (!currentRuntime.networkConfiguration) { + throw new ToolkitError('Current runtime does not have a networkConfiguration'); + } + + // All properties must be explicitly specified, otherwise they will be reset to + // default values. We pass all properties from the current runtime and override + // only the ones that have changed. + await bedrockAgentCore.updateAgentRuntime({ + agentRuntimeId, + agentRuntimeArtifact: runtimeChange.artifact + ? toSdkAgentRuntimeArtifact(runtimeChange.artifact) + : currentRuntime.agentRuntimeArtifact, + roleArn: currentRuntime.roleArn, + networkConfiguration: currentRuntime.networkConfiguration, + description: runtimeChange.description ?? currentRuntime.description, + authorizerConfiguration: currentRuntime.authorizerConfiguration, + requestHeaderConfiguration: currentRuntime.requestHeaderConfiguration, + protocolConfiguration: currentRuntime.protocolConfiguration, + lifecycleConfiguration: currentRuntime.lifecycleConfiguration, + environmentVariables: runtimeChange.environmentVariables ?? currentRuntime.environmentVariables, + }); + }, + }); + + return ret; +} + +async function evaluateBedrockAgentCoreRuntimeProps( + hotswappablePropChanges: Record>, + evaluateCfnTemplate: EvaluateCloudFormationTemplate, +): Promise { + const runtimeChange: BedrockAgentCoreRuntimeChange = {}; + + for (const updatedPropName in hotswappablePropChanges) { + const updatedProp = hotswappablePropChanges[updatedPropName]; + + switch (updatedPropName) { + case 'AgentRuntimeArtifact': + runtimeChange.artifact = await evaluateAgentRuntimeArtifact( + updatedProp.newValue as CfnAgentRuntimeArtifact, + evaluateCfnTemplate, + ); + break; + + case 'Description': + runtimeChange.description = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue); + break; + + case 'EnvironmentVariables': + runtimeChange.environmentVariables = await evaluateCfnTemplate.evaluateCfnExpression(updatedProp.newValue); + break; + + default: + // never reached + throw new ToolkitError( + 'Unexpected hotswappable property for BedrockAgentCore Runtime. Please report this at github.com/aws/aws-cdk/issues/new/choose', + ); + } + } + + return runtimeChange; +} + +async function evaluateAgentRuntimeArtifact( + artifactValue: CfnAgentRuntimeArtifact, + evaluateCfnTemplate: EvaluateCloudFormationTemplate, +): Promise { + if (artifactValue.CodeConfiguration) { + const codeConfig = artifactValue.CodeConfiguration; + const code = codeConfig.Code; + + const s3Location = code.S3 ? { + bucket: await evaluateCfnTemplate.evaluateCfnExpression(code.S3.Bucket), + prefix: await evaluateCfnTemplate.evaluateCfnExpression(code.S3.Prefix), + versionId: code.S3.VersionId + ? await evaluateCfnTemplate.evaluateCfnExpression(code.S3.VersionId) + : undefined, + } : undefined; + + return { + codeConfiguration: { + code: s3Location ? { s3: s3Location } : {}, + runtime: await evaluateCfnTemplate.evaluateCfnExpression(codeConfig.Runtime), + entryPoint: await evaluateCfnTemplate.evaluateCfnExpression(codeConfig.EntryPoint), + }, + }; + } + + if (artifactValue.ContainerConfiguration) { + return { + containerConfiguration: { + containerUri: await evaluateCfnTemplate.evaluateCfnExpression( + artifactValue.ContainerConfiguration.ContainerUri, + ), + }, + }; + } + + return undefined; +} + +function toSdkAgentRuntimeArtifact(artifact: AgentRuntimeArtifact): SdkAgentRuntimeArtifact { + if (artifact.codeConfiguration) { + const code = artifact.codeConfiguration.code.s3 + ? { s3: artifact.codeConfiguration.code.s3 } + : undefined; + + return { + codeConfiguration: { + code, + runtime: artifact.codeConfiguration.runtime as AgentManagedRuntimeType, + entryPoint: artifact.codeConfiguration.entryPoint, + }, + }; + } + + if (artifact.containerConfiguration) { + return { + containerConfiguration: artifact.containerConfiguration, + }; + } + + // never reached + throw new ToolkitError('AgentRuntimeArtifact must have either codeConfiguration or containerConfiguration'); +} + +interface CfnAgentRuntimeArtifact { + readonly CodeConfiguration?: { + readonly Code: { + readonly S3?: { + readonly Bucket: unknown; + readonly Prefix: unknown; + readonly VersionId?: unknown; + }; + }; + readonly Runtime: unknown; + readonly EntryPoint: unknown; + }; + readonly ContainerConfiguration?: { + readonly ContainerUri: unknown; + }; +} + +interface AgentRuntimeArtifact { + readonly codeConfiguration?: { + readonly code: { + readonly s3?: { + readonly bucket: string; + readonly prefix: string; + readonly versionId?: string; + }; + }; + readonly runtime: string; + readonly entryPoint: string[]; + }; + readonly containerConfiguration?: { + readonly containerUri: string; + }; +} + +interface BedrockAgentCoreRuntimeChange { + artifact?: AgentRuntimeArtifact; + description?: string; + environmentVariables?: Record; +} diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/hotswap/hotswap-deployments.ts b/packages/@aws-cdk/toolkit-lib/lib/api/hotswap/hotswap-deployments.ts index eeb72eee3..3976e1536 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/hotswap/hotswap-deployments.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/hotswap/hotswap-deployments.ts @@ -10,6 +10,7 @@ import type { SDK, SdkProvider } from '../aws-auth/private'; import type { CloudFormationStack, NestedStackTemplates } from '../cloudformation'; import { loadCurrentTemplateWithNestedStacks, EvaluateCloudFormationTemplate } from '../cloudformation'; import { isHotswappableAppSyncChange } from './appsync-mapping-templates'; +import { isHotswappableBedrockAgentCoreRuntimeChange } from './bedrock-agentcore-runtimes'; import { isHotswappableCodeBuildProjectChange } from './code-build-projects'; import type { HotswapChange, @@ -59,6 +60,7 @@ const RESOURCE_DETECTORS: { [key: string]: HotswapDetector } = { 'AWS::AppSync::GraphQLSchema': isHotswappableAppSyncChange, 'AWS::AppSync::ApiKey': isHotswappableAppSyncChange, + 'AWS::BedrockAgentCore::Runtime': isHotswappableBedrockAgentCoreRuntimeChange, 'AWS::ECS::TaskDefinition': isHotswappableEcsServiceChange, 'AWS::CodeBuild::Project': isHotswappableCodeBuildProjectChange, 'AWS::StepFunctions::StateMachine': isHotswappableStateMachineChange, diff --git a/packages/@aws-cdk/toolkit-lib/package.json b/packages/@aws-cdk/toolkit-lib/package.json index a1e193c2e..a2bfed2ee 100644 --- a/packages/@aws-cdk/toolkit-lib/package.json +++ b/packages/@aws-cdk/toolkit-lib/package.json @@ -83,6 +83,7 @@ "@aws-cdk/cloudformation-diff": "^0.0.0", "@aws-cdk/cx-api": "^2", "@aws-sdk/client-appsync": "^3", + "@aws-sdk/client-bedrock-agentcore-control": "^3", "@aws-sdk/client-cloudcontrol": "^3", "@aws-sdk/client-cloudformation": "^3", "@aws-sdk/client-cloudwatch-logs": "^3", diff --git a/packages/@aws-cdk/toolkit-lib/test/_helpers/mock-sdk.ts b/packages/@aws-cdk/toolkit-lib/test/_helpers/mock-sdk.ts index 184b53e7f..87567a097 100644 --- a/packages/@aws-cdk/toolkit-lib/test/_helpers/mock-sdk.ts +++ b/packages/@aws-cdk/toolkit-lib/test/_helpers/mock-sdk.ts @@ -3,6 +3,7 @@ import { type Account } from '@aws-cdk/cdk-assets-lib'; import type { SDKv3CompatibleCredentials } from '@aws-cdk/cli-plugin-contract'; import type { Environment } from '@aws-cdk/cx-api'; import { AppSyncClient } from '@aws-sdk/client-appsync'; +import { BedrockAgentCoreControlClient } from '@aws-sdk/client-bedrock-agentcore-control'; import { CloudControlClient } from '@aws-sdk/client-cloudcontrol'; import type { Stack } from '@aws-sdk/client-cloudformation'; import { CloudFormationClient, StackStatus } from '@aws-sdk/client-cloudformation'; @@ -38,6 +39,7 @@ export const FAKE_CREDENTIAL_CHAIN = createCredentialChain(() => Promise.resolve // Default implementations export const awsMock = { appSync: mockClient(AppSyncClient), + bedrockAgentCoreControl: mockClient(BedrockAgentCoreControlClient), cloudControl: mockClient(CloudControlClient), cloudFormation: mockClient(CloudFormationClient), cloudWatch: mockClient(CloudWatchLogsClient), @@ -59,6 +61,7 @@ export const awsMock = { // Global aliases for the mock clients for backwards compatibility export const mockAppSyncClient = awsMock.appSync; +export const mockBedrockAgentCoreControlClient = awsMock.bedrockAgentCoreControl; export const mockCloudControlClient = awsMock.cloudControl; export const mockCloudFormationClient = awsMock.cloudFormation; export const mockCloudWatchClient = awsMock.cloudWatch; diff --git a/packages/@aws-cdk/toolkit-lib/test/api/hotswap/bedrock-agentcore-runtimes-hotswap-deployments.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/hotswap/bedrock-agentcore-runtimes-hotswap-deployments.test.ts new file mode 100644 index 000000000..b5de65a4d --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/test/api/hotswap/bedrock-agentcore-runtimes-hotswap-deployments.test.ts @@ -0,0 +1,651 @@ +import { GetAgentRuntimeCommand, UpdateAgentRuntimeCommand } from '@aws-sdk/client-bedrock-agentcore-control'; +import { HotswapMode } from '../../../lib/api/hotswap'; +import { mockBedrockAgentCoreControlClient } from '../../_helpers/mock-sdk'; +import * as setup from '../_helpers/hotswap-test-setup'; + +let hotswapMockSdkProvider: setup.HotswapMockSdkProvider; + +beforeEach(() => { + hotswapMockSdkProvider = setup.setupHotswapTests(); + mockBedrockAgentCoreControlClient.on(GetAgentRuntimeCommand).resolves({ + agentRuntimeId: 'my-runtime', + roleArn: 'arn:aws:iam::123456789012:role/MyRole', + networkConfiguration: { + networkMode: 'VPC', + networkModeConfig: { + subnets: ['subnet-1', 'subnet-2'], + securityGroups: ['sg-1'], + }, + }, + agentRuntimeArtifact: { + codeConfiguration: { + code: { + s3: { + bucket: 'my-bucket', + prefix: 'code.zip', + }, + }, + runtime: 'PYTHON_3_13', + entryPoint: ['app.py'], + }, + }, + }); +}); + +describe.each([HotswapMode.FALL_BACK, HotswapMode.HOTSWAP_ONLY])('%p mode', (hotswapMode) => { + test('calls the updateAgentRuntime() API when it receives only an S3 code difference in a Runtime', async () => { + // GIVEN + setup.setCurrentCfnStackTemplate({ + Resources: { + Runtime: { + Type: 'AWS::BedrockAgentCore::Runtime', + Properties: { + RuntimeName: 'my-runtime', + RoleArn: 'arn:aws:iam::123456789012:role/MyRole', + NetworkConfiguration: { + NetworkMode: 'VPC', + NetworkModeConfig: { + Subnets: ['subnet-1', 'subnet-2'], + SecurityGroups: ['sg-1'], + }, + }, + AgentRuntimeArtifact: { + CodeConfiguration: { + Code: { + S3: { + Bucket: 'my-bucket', + Prefix: 'old-code.zip', + }, + }, + Runtime: 'PYTHON_3_13', + EntryPoint: ['app.py'], + }, + }, + }, + }, + }, + }); + setup.pushStackResourceSummaries( + setup.stackSummaryOf('Runtime', 'AWS::BedrockAgentCore::Runtime', 'my-runtime'), + ); + const cdkStackArtifact = setup.cdkStackArtifactOf({ + template: { + Resources: { + Runtime: { + Type: 'AWS::BedrockAgentCore::Runtime', + Properties: { + RuntimeName: 'my-runtime', + RoleArn: 'arn:aws:iam::123456789012:role/MyRole', + NetworkConfiguration: { + NetworkMode: 'VPC', + NetworkModeConfig: { + Subnets: ['subnet-1', 'subnet-2'], + SecurityGroups: ['sg-1'], + }, + }, + AgentRuntimeArtifact: { + CodeConfiguration: { + Code: { + S3: { + Bucket: 'my-bucket', + Prefix: 'new-code.zip', + }, + }, + Runtime: 'PYTHON_3_13', + EntryPoint: ['app.py'], + }, + }, + }, + }, + }, + }, + }); + + // WHEN + const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(hotswapMode, cdkStackArtifact); + + // THEN + expect(deployStackResult).not.toBeUndefined(); + expect(mockBedrockAgentCoreControlClient).toHaveReceivedCommandWith(UpdateAgentRuntimeCommand, { + agentRuntimeId: 'my-runtime', + agentRuntimeArtifact: { + codeConfiguration: { + code: { + s3: { + bucket: 'my-bucket', + prefix: 'new-code.zip', + }, + }, + runtime: 'PYTHON_3_13', + entryPoint: ['app.py'], + }, + }, + roleArn: 'arn:aws:iam::123456789012:role/MyRole', + networkConfiguration: { + networkMode: 'VPC', + networkModeConfig: { + subnets: ['subnet-1', 'subnet-2'], + securityGroups: ['sg-1'], + }, + }, + }); + }); + + test('calls the updateAgentRuntime() API when it receives only a container image difference in a Runtime', async () => { + // GIVEN + setup.setCurrentCfnStackTemplate({ + Resources: { + Runtime: { + Type: 'AWS::BedrockAgentCore::Runtime', + Properties: { + RuntimeName: 'my-runtime', + RoleArn: 'arn:aws:iam::123456789012:role/MyRole', + NetworkConfiguration: { + NetworkMode: 'VPC', + NetworkModeConfig: { + Subnets: ['subnet-1', 'subnet-2'], + SecurityGroups: ['sg-1'], + }, + }, + AgentRuntimeArtifact: { + ContainerConfiguration: { + ContainerUri: '123456789012.dkr.ecr.us-east-1.amazonaws.com/my-repo:old-tag', + }, + }, + }, + }, + }, + }); + setup.pushStackResourceSummaries( + setup.stackSummaryOf('Runtime', 'AWS::BedrockAgentCore::Runtime', 'my-runtime'), + ); + const cdkStackArtifact = setup.cdkStackArtifactOf({ + template: { + Resources: { + Runtime: { + Type: 'AWS::BedrockAgentCore::Runtime', + Properties: { + RuntimeName: 'my-runtime', + RoleArn: 'arn:aws:iam::123456789012:role/MyRole', + NetworkConfiguration: { + NetworkMode: 'VPC', + NetworkModeConfig: { + Subnets: ['subnet-1', 'subnet-2'], + SecurityGroups: ['sg-1'], + }, + }, + AgentRuntimeArtifact: { + ContainerConfiguration: { + ContainerUri: '123456789012.dkr.ecr.us-east-1.amazonaws.com/my-repo:new-tag', + }, + }, + }, + }, + }, + }, + }); + + // WHEN + const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(hotswapMode, cdkStackArtifact); + + // THEN + expect(deployStackResult).not.toBeUndefined(); + expect(mockBedrockAgentCoreControlClient).toHaveReceivedCommandWith(UpdateAgentRuntimeCommand, { + agentRuntimeId: 'my-runtime', + agentRuntimeArtifact: { + containerConfiguration: { + containerUri: '123456789012.dkr.ecr.us-east-1.amazonaws.com/my-repo:new-tag', + }, + }, + roleArn: 'arn:aws:iam::123456789012:role/MyRole', + networkConfiguration: { + networkMode: 'VPC', + networkModeConfig: { + subnets: ['subnet-1', 'subnet-2'], + securityGroups: ['sg-1'], + }, + }, + }); + }); + + test('calls the updateAgentRuntime() API when it receives only a description change', async () => { + // GIVEN + setup.setCurrentCfnStackTemplate({ + Resources: { + Runtime: { + Type: 'AWS::BedrockAgentCore::Runtime', + Properties: { + RuntimeName: 'my-runtime', + RoleArn: 'arn:aws:iam::123456789012:role/MyRole', + NetworkConfiguration: { + NetworkMode: 'VPC', + NetworkModeConfig: { + Subnets: ['subnet-1', 'subnet-2'], + SecurityGroups: ['sg-1'], + }, + }, + AgentRuntimeArtifact: { + CodeConfiguration: { + Code: { + S3: { + Bucket: 'my-bucket', + Prefix: 'code.zip', + }, + }, + Runtime: 'PYTHON_3_13', + EntryPoint: ['app.py'], + }, + }, + Description: 'Old description', + }, + }, + }, + }); + setup.pushStackResourceSummaries( + setup.stackSummaryOf('Runtime', 'AWS::BedrockAgentCore::Runtime', 'my-runtime'), + ); + mockBedrockAgentCoreControlClient.on(GetAgentRuntimeCommand).resolves({ + agentRuntimeId: 'my-runtime', + roleArn: 'arn:aws:iam::123456789012:role/MyRole', + networkConfiguration: { + networkMode: 'VPC', + networkModeConfig: { + subnets: ['subnet-1', 'subnet-2'], + securityGroups: ['sg-1'], + }, + }, + agentRuntimeArtifact: { + codeConfiguration: { + code: { + s3: { + bucket: 'my-bucket', + prefix: 'code.zip', + }, + }, + runtime: 'PYTHON_3_13', + entryPoint: ['app.py'], + }, + }, + description: 'Old description', + }); + const cdkStackArtifact = setup.cdkStackArtifactOf({ + template: { + Resources: { + Runtime: { + Type: 'AWS::BedrockAgentCore::Runtime', + Properties: { + RuntimeName: 'my-runtime', + RoleArn: 'arn:aws:iam::123456789012:role/MyRole', + NetworkConfiguration: { + NetworkMode: 'VPC', + NetworkModeConfig: { + Subnets: ['subnet-1', 'subnet-2'], + SecurityGroups: ['sg-1'], + }, + }, + AgentRuntimeArtifact: { + CodeConfiguration: { + Code: { + S3: { + Bucket: 'my-bucket', + Prefix: 'code.zip', + }, + }, + Runtime: 'PYTHON_3_13', + EntryPoint: ['app.py'], + }, + }, + Description: 'New description', + }, + }, + }, + }, + }); + + // WHEN + const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(hotswapMode, cdkStackArtifact); + + // THEN + expect(deployStackResult).not.toBeUndefined(); + expect(mockBedrockAgentCoreControlClient).toHaveReceivedCommandWith(UpdateAgentRuntimeCommand, { + agentRuntimeId: 'my-runtime', + agentRuntimeArtifact: { + codeConfiguration: { + code: { + s3: { + bucket: 'my-bucket', + prefix: 'code.zip', + }, + }, + runtime: 'PYTHON_3_13', + entryPoint: ['app.py'], + }, + }, + roleArn: 'arn:aws:iam::123456789012:role/MyRole', + networkConfiguration: { + networkMode: 'VPC', + networkModeConfig: { + subnets: ['subnet-1', 'subnet-2'], + securityGroups: ['sg-1'], + }, + }, + description: 'New description', + }); + }); + + test('calls the updateAgentRuntime() API when it receives only environment variables changes', async () => { + // GIVEN + setup.setCurrentCfnStackTemplate({ + Resources: { + Runtime: { + Type: 'AWS::BedrockAgentCore::Runtime', + Properties: { + RuntimeName: 'my-runtime', + RoleArn: 'arn:aws:iam::123456789012:role/MyRole', + NetworkConfiguration: { + NetworkMode: 'VPC', + NetworkModeConfig: { + Subnets: ['subnet-1', 'subnet-2'], + SecurityGroups: ['sg-1'], + }, + }, + AgentRuntimeArtifact: { + CodeConfiguration: { + Code: { + S3: { + Bucket: 'my-bucket', + Prefix: 'code.zip', + }, + }, + Runtime: 'PYTHON_3_13', + EntryPoint: ['app.py'], + }, + }, + EnvironmentVariables: { + KEY1: 'value1', + }, + }, + }, + }, + }); + setup.pushStackResourceSummaries( + setup.stackSummaryOf('Runtime', 'AWS::BedrockAgentCore::Runtime', 'my-runtime'), + ); + mockBedrockAgentCoreControlClient.on(GetAgentRuntimeCommand).resolves({ + agentRuntimeId: 'my-runtime', + roleArn: 'arn:aws:iam::123456789012:role/MyRole', + networkConfiguration: { + networkMode: 'VPC', + networkModeConfig: { + subnets: ['subnet-1', 'subnet-2'], + securityGroups: ['sg-1'], + }, + }, + agentRuntimeArtifact: { + codeConfiguration: { + code: { + s3: { + bucket: 'my-bucket', + prefix: 'code.zip', + }, + }, + runtime: 'PYTHON_3_13', + entryPoint: ['app.py'], + }, + }, + environmentVariables: { + KEY1: 'value1', + }, + }); + const cdkStackArtifact = setup.cdkStackArtifactOf({ + template: { + Resources: { + Runtime: { + Type: 'AWS::BedrockAgentCore::Runtime', + Properties: { + RuntimeName: 'my-runtime', + RoleArn: 'arn:aws:iam::123456789012:role/MyRole', + NetworkConfiguration: { + NetworkMode: 'VPC', + NetworkModeConfig: { + Subnets: ['subnet-1', 'subnet-2'], + SecurityGroups: ['sg-1'], + }, + }, + AgentRuntimeArtifact: { + CodeConfiguration: { + Code: { + S3: { + Bucket: 'my-bucket', + Prefix: 'code.zip', + }, + }, + Runtime: 'PYTHON_3_13', + EntryPoint: ['app.py'], + }, + }, + EnvironmentVariables: { + KEY1: 'value1', + KEY2: 'value2', + }, + }, + }, + }, + }, + }); + + // WHEN + const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(hotswapMode, cdkStackArtifact); + + // THEN + expect(deployStackResult).not.toBeUndefined(); + expect(mockBedrockAgentCoreControlClient).toHaveReceivedCommandWith(UpdateAgentRuntimeCommand, { + agentRuntimeId: 'my-runtime', + agentRuntimeArtifact: { + codeConfiguration: { + code: { + s3: { + bucket: 'my-bucket', + prefix: 'code.zip', + }, + }, + runtime: 'PYTHON_3_13', + entryPoint: ['app.py'], + }, + }, + roleArn: 'arn:aws:iam::123456789012:role/MyRole', + networkConfiguration: { + networkMode: 'VPC', + networkModeConfig: { + subnets: ['subnet-1', 'subnet-2'], + securityGroups: ['sg-1'], + }, + }, + environmentVariables: { + KEY1: 'value1', + KEY2: 'value2', + }, + }); + }); + + test('does not call the updateAgentRuntime() API when a non-hotswappable property changes', async () => { + // GIVEN + setup.setCurrentCfnStackTemplate({ + Resources: { + Runtime: { + Type: 'AWS::BedrockAgentCore::Runtime', + Properties: { + RuntimeName: 'my-runtime', + RoleArn: 'arn:aws:iam::123456789012:role/MyRole', + NetworkConfiguration: { + NetworkMode: 'VPC', + NetworkModeConfig: { + Subnets: ['subnet-1', 'subnet-2'], + SecurityGroups: ['sg-1'], + }, + }, + AgentRuntimeArtifact: { + CodeConfiguration: { + Code: { + S3: { + Bucket: 'my-bucket', + Prefix: 'code.zip', + }, + }, + Runtime: 'PYTHON_3_13', + EntryPoint: ['app.py'], + }, + }, + }, + }, + }, + }); + setup.pushStackResourceSummaries( + setup.stackSummaryOf('Runtime', 'AWS::BedrockAgentCore::Runtime', 'my-runtime'), + ); + const cdkStackArtifact = setup.cdkStackArtifactOf({ + template: { + Resources: { + Runtime: { + Type: 'AWS::BedrockAgentCore::Runtime', + Properties: { + RuntimeName: 'my-runtime', + RoleArn: 'arn:aws:iam::123456789012:role/DifferentRole', // non-hotswappable change + NetworkConfiguration: { + NetworkMode: 'VPC', + NetworkModeConfig: { + Subnets: ['subnet-1', 'subnet-2'], + SecurityGroups: ['sg-1'], + }, + }, + AgentRuntimeArtifact: { + CodeConfiguration: { + Code: { + S3: { + Bucket: 'my-bucket', + Prefix: 'code.zip', + }, + }, + Runtime: 'PYTHON_3_13', + EntryPoint: ['app.py'], + }, + }, + }, + }, + }, + }, + }); + + // WHEN + const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(hotswapMode, cdkStackArtifact); + + // THEN + if (hotswapMode === HotswapMode.FALL_BACK) { + expect(deployStackResult).toBeUndefined(); + } else { + expect(deployStackResult).not.toBeUndefined(); + } + expect(mockBedrockAgentCoreControlClient).not.toHaveReceivedCommand(UpdateAgentRuntimeCommand); + }); + + test('calls the updateAgentRuntime() API with S3 versionId when specified', async () => { + // GIVEN + setup.setCurrentCfnStackTemplate({ + Resources: { + Runtime: { + Type: 'AWS::BedrockAgentCore::Runtime', + Properties: { + RuntimeName: 'my-runtime', + RoleArn: 'arn:aws:iam::123456789012:role/MyRole', + NetworkConfiguration: { + NetworkMode: 'VPC', + NetworkModeConfig: { + Subnets: ['subnet-1', 'subnet-2'], + SecurityGroups: ['sg-1'], + }, + }, + AgentRuntimeArtifact: { + CodeConfiguration: { + Code: { + S3: { + Bucket: 'my-bucket', + Prefix: 'code.zip', + VersionId: 'v1', + }, + }, + Runtime: 'PYTHON_3_13', + EntryPoint: ['app.py'], + }, + }, + }, + }, + }, + }); + setup.pushStackResourceSummaries( + setup.stackSummaryOf('Runtime', 'AWS::BedrockAgentCore::Runtime', 'my-runtime'), + ); + const cdkStackArtifact = setup.cdkStackArtifactOf({ + template: { + Resources: { + Runtime: { + Type: 'AWS::BedrockAgentCore::Runtime', + Properties: { + RuntimeName: 'my-runtime', + RoleArn: 'arn:aws:iam::123456789012:role/MyRole', + NetworkConfiguration: { + NetworkMode: 'VPC', + NetworkModeConfig: { + Subnets: ['subnet-1', 'subnet-2'], + SecurityGroups: ['sg-1'], + }, + }, + AgentRuntimeArtifact: { + CodeConfiguration: { + Code: { + S3: { + Bucket: 'my-bucket', + Prefix: 'code.zip', + VersionId: 'v2', + }, + }, + Runtime: 'PYTHON_3_13', + EntryPoint: ['app.py'], + }, + }, + }, + }, + }, + }, + }); + + // WHEN + const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(hotswapMode, cdkStackArtifact); + + // THEN + expect(deployStackResult).not.toBeUndefined(); + expect(mockBedrockAgentCoreControlClient).toHaveReceivedCommandWith(UpdateAgentRuntimeCommand, { + agentRuntimeId: 'my-runtime', + agentRuntimeArtifact: { + codeConfiguration: { + code: { + s3: { + bucket: 'my-bucket', + prefix: 'code.zip', + versionId: 'v2', + }, + }, + runtime: 'PYTHON_3_13', + entryPoint: ['app.py'], + }, + }, + roleArn: 'arn:aws:iam::123456789012:role/MyRole', + networkConfiguration: { + networkMode: 'VPC', + networkModeConfig: { + subnets: ['subnet-1', 'subnet-2'], + securityGroups: ['sg-1'], + }, + }, + }); + }); +}); diff --git a/packages/aws-cdk/.projen/deps.json b/packages/aws-cdk/.projen/deps.json index 410a27cbd..f5c4e838f 100644 --- a/packages/aws-cdk/.projen/deps.json +++ b/packages/aws-cdk/.projen/deps.json @@ -209,6 +209,10 @@ "name": "@aws-sdk/client-appsync", "type": "runtime" }, + { + "name": "@aws-sdk/client-bedrock-agentcore-control", + "type": "runtime" + }, { "name": "@aws-sdk/client-cloudcontrol", "type": "runtime" diff --git a/packages/aws-cdk/.projen/tasks.json b/packages/aws-cdk/.projen/tasks.json index dbd9ac7d0..2a880a8e0 100644 --- a/packages/aws-cdk/.projen/tasks.json +++ b/packages/aws-cdk/.projen/tasks.json @@ -53,7 +53,7 @@ }, "steps": [ { - "exec": "npx npm-check-updates@18 --upgrade --target=minor --peer --no-deprecated --dep=dev,peer,prod,optional --filter=@cdklabs/eslint-plugin,@types/archiver,@types/jest,@types/mockery,@types/promptly,@types/semver,@types/sinon,aws-sdk-client-mock,aws-sdk-client-mock-jest,axios,eslint-config-prettier,eslint-import-resolver-typescript,eslint-plugin-import,eslint-plugin-jest,eslint-plugin-jsdoc,eslint-plugin-prettier,fast-check,jest,jest-environment-node,jest-mock,license-checker,madge,node-backpack,sinon,ts-jest,ts-mock-imports,xml-js,@aws-cdk/cx-api,@aws-sdk/client-appsync,@aws-sdk/client-cloudcontrol,@aws-sdk/client-cloudformation,@aws-sdk/client-cloudwatch-logs,@aws-sdk/client-codebuild,@aws-sdk/client-ec2,@aws-sdk/client-ecr,@aws-sdk/client-ecs,@aws-sdk/client-elastic-load-balancing-v2,@aws-sdk/client-iam,@aws-sdk/client-kms,@aws-sdk/client-lambda,@aws-sdk/client-route-53,@aws-sdk/client-s3,@aws-sdk/client-secrets-manager,@aws-sdk/client-sfn,@aws-sdk/client-ssm,@aws-sdk/client-sts,@aws-sdk/credential-providers,@aws-sdk/ec2-metadata-service,@aws-sdk/lib-storage,@smithy/middleware-endpoint,@smithy/property-provider,@smithy/shared-ini-file-loader,@smithy/types,@smithy/util-retry,@smithy/util-waiter,archiver,cdk-from-cfn,enquirer,glob,promptly,proxy-agent,semver,uuid" + "exec": "npx npm-check-updates@18 --upgrade --target=minor --peer --no-deprecated --dep=dev,peer,prod,optional --filter=@cdklabs/eslint-plugin,@types/archiver,@types/jest,@types/mockery,@types/promptly,@types/semver,@types/sinon,aws-sdk-client-mock,aws-sdk-client-mock-jest,axios,eslint-config-prettier,eslint-import-resolver-typescript,eslint-plugin-import,eslint-plugin-jest,eslint-plugin-jsdoc,eslint-plugin-prettier,fast-check,jest,jest-environment-node,jest-mock,license-checker,madge,node-backpack,sinon,ts-jest,ts-mock-imports,xml-js,@aws-cdk/cx-api,@aws-sdk/client-appsync,@aws-sdk/client-bedrock-agentcore-control,@aws-sdk/client-cloudcontrol,@aws-sdk/client-cloudformation,@aws-sdk/client-cloudwatch-logs,@aws-sdk/client-codebuild,@aws-sdk/client-ec2,@aws-sdk/client-ecr,@aws-sdk/client-ecs,@aws-sdk/client-elastic-load-balancing-v2,@aws-sdk/client-iam,@aws-sdk/client-kms,@aws-sdk/client-lambda,@aws-sdk/client-route-53,@aws-sdk/client-s3,@aws-sdk/client-secrets-manager,@aws-sdk/client-sfn,@aws-sdk/client-ssm,@aws-sdk/client-sts,@aws-sdk/credential-providers,@aws-sdk/ec2-metadata-service,@aws-sdk/lib-storage,@smithy/middleware-endpoint,@smithy/property-provider,@smithy/shared-ini-file-loader,@smithy/types,@smithy/util-retry,@smithy/util-waiter,archiver,cdk-from-cfn,enquirer,glob,promptly,proxy-agent,semver,uuid" } ] }, diff --git a/packages/aws-cdk/README.md b/packages/aws-cdk/README.md index 60f1b163e..99ce23f03 100644 --- a/packages/aws-cdk/README.md +++ b/packages/aws-cdk/README.md @@ -517,6 +517,49 @@ Hotswapping is currently supported for the following changes - Source and Environment changes of AWS CodeBuild Projects. - VTL mapping template changes for AppSync Resolvers and Functions. - Schema changes for AppSync GraphQL Apis. +- Code files (S3-based) and container image (ECR-based) changes, along with environment variable + and description changes of Amazon Bedrock AgentCore Runtimes. + - **Note**: For S3-based code changes to be detected, use `Asset` from `aws-cdk-lib/aws-s3-assets`: + + ```typescript + // ✅ Recommended (hotswap works) + const asset = new aws_s3_assets.Asset(this, 'CodeAsset', { + path: path.join(__dirname, 'agent-code'), + }); + + const agentRuntimeArtifact = AgentRuntimeArtifact.fromS3( + { + bucketName: asset.s3BucketName, + objectKey: asset.s3ObjectKey, // Content hash, changes when code changes + }, + AgentCoreRuntime.PYTHON_3_13, + ['app.py'], + ); + new Runtime(this, 'Runtime', { + runtimeName: 'runtime', + agentRuntimeArtifact, + }); + ``` + + - Do not use `Source.asset()` with `BucketDeployment`, as the generated object key is a token resolved at deployment time and does not change in the CloudFormation template (hotswap will not work): + + ```typescript + // ❌ Not recommended (hotswap doesn't work) + const deployment = new aws_s3_deployment.BucketDeployment(this, 'Deploy', { + sources: [aws_s3_deployment.Source.asset(path.join(__dirname, 'agent-code'))], + destinationBucket: bucket, + extract: false, + }); + + const agentRuntimeArtifact = AgentRuntimeArtifact.fromS3( + { + bucketName: bucket.bucketName, + objectKey: cdk.Fn.select(0, deployment.objectKeys), // Token, resolved at deployment time + }, + AgentCoreRuntime.PYTHON_3_13, + ['app.py'], + ); + ``` You can optionally configure the behavior of your hotswap deployments. Currently you can only configure ECS hotswap behavior: diff --git a/packages/aws-cdk/THIRD_PARTY_LICENSES b/packages/aws-cdk/THIRD_PARTY_LICENSES index b2861debb..4028c872e 100644 --- a/packages/aws-cdk/THIRD_PARTY_LICENSES +++ b/packages/aws-cdk/THIRD_PARTY_LICENSES @@ -822,6 +822,212 @@ The aws-cdk package includes the following third-party software/licensing: limitations under the License. +---------------- + +** @aws-sdk/client-bedrock-agentcore-control@3.953.0 - https://www.npmjs.com/package/@aws-sdk/client-bedrock-agentcore-control/v/3.953.0 | Apache-2.0 + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018-2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + ---------------- ** @aws-sdk/client-cloudcontrol@3.953.0 - https://www.npmjs.com/package/@aws-sdk/client-cloudcontrol/v/3.953.0 | Apache-2.0 diff --git a/packages/aws-cdk/package.json b/packages/aws-cdk/package.json index b04ca060d..1d9dee7d9 100644 --- a/packages/aws-cdk/package.json +++ b/packages/aws-cdk/package.json @@ -87,6 +87,7 @@ "@aws-cdk/cx-api": "^2.232.2", "@aws-cdk/toolkit-lib": "^0.0.0", "@aws-sdk/client-appsync": "^3", + "@aws-sdk/client-bedrock-agentcore-control": "^3", "@aws-sdk/client-cloudcontrol": "^3", "@aws-sdk/client-cloudformation": "^3", "@aws-sdk/client-cloudwatch-logs": "^3", diff --git a/packages/aws-cdk/test/_helpers/mock-sdk.ts b/packages/aws-cdk/test/_helpers/mock-sdk.ts index ba3c8cc06..9c0d9b1ce 100644 --- a/packages/aws-cdk/test/_helpers/mock-sdk.ts +++ b/packages/aws-cdk/test/_helpers/mock-sdk.ts @@ -3,6 +3,7 @@ import { type Account } from '@aws-cdk/cdk-assets-lib'; import type { SDKv3CompatibleCredentials } from '@aws-cdk/cli-plugin-contract'; import type { Environment } from '@aws-cdk/cx-api'; import { AppSyncClient } from '@aws-sdk/client-appsync'; +import { BedrockAgentCoreControlClient } from '@aws-sdk/client-bedrock-agentcore-control'; import { CloudControlClient } from '@aws-sdk/client-cloudcontrol'; import type { Stack } from '@aws-sdk/client-cloudformation'; import { CloudFormationClient, StackStatus } from '@aws-sdk/client-cloudformation'; @@ -37,6 +38,7 @@ export const FAKE_CREDENTIAL_CHAIN = createCredentialChain(() => Promise.resolve // Default implementations export const mockAppSyncClient = mockClient(AppSyncClient); +export const mockBedrockAgentCoreControlClient = mockClient(BedrockAgentCoreControlClient); export const mockCloudControlClient = mockClient(CloudControlClient); export const mockCloudFormationClient = mockClient(CloudFormationClient); export const mockCloudWatchClient = mockClient(CloudWatchLogsClient); @@ -68,6 +70,7 @@ export const restoreSdkMocksToDefault = () => { applyToAllMocks('reset'); mockAppSyncClient.onAnyCommand().resolves({}); + mockBedrockAgentCoreControlClient.onAnyCommand().resolves({}); mockCloudControlClient.onAnyCommand().resolves({}); mockCloudFormationClient.onAnyCommand().resolves({}); mockCloudWatchClient.onAnyCommand().resolves({}); @@ -103,6 +106,7 @@ export function undoAllSdkMocks() { function applyToAllMocks(meth: 'reset' | 'restore') { mockAppSyncClient[meth](); + mockBedrockAgentCoreControlClient[meth](); mockCloudFormationClient[meth](); mockCloudWatchClient[meth](); mockCodeBuildClient[meth](); diff --git a/yarn.lock b/yarn.lock index 66e0bdffc..b6549f6c3 100644 --- a/yarn.lock +++ b/yarn.lock @@ -213,6 +213,52 @@ "@smithy/util-utf8" "^4.2.0" tslib "^2.6.2" +"@aws-sdk/client-bedrock-agentcore-control@^3": + version "3.953.0" + resolved "https://registry.yarnpkg.com/@aws-sdk/client-bedrock-agentcore-control/-/client-bedrock-agentcore-control-3.953.0.tgz#96d4dbf765e404c00525403a4255f897985743e9" + integrity sha512-YIUGvIEEAfgIUq14h7GHu24OBdoSOR3GhYFL0NDE2I8UvzB/TOtvoDfTlp7Fnl4GBHKF+fZISmT3PjbRuHKEhA== + dependencies: + "@aws-crypto/sha256-browser" "5.2.0" + "@aws-crypto/sha256-js" "5.2.0" + "@aws-sdk/core" "3.953.0" + "@aws-sdk/credential-provider-node" "3.953.0" + "@aws-sdk/middleware-host-header" "3.953.0" + "@aws-sdk/middleware-logger" "3.953.0" + "@aws-sdk/middleware-recursion-detection" "3.953.0" + "@aws-sdk/middleware-user-agent" "3.953.0" + "@aws-sdk/region-config-resolver" "3.953.0" + "@aws-sdk/types" "3.953.0" + "@aws-sdk/util-endpoints" "3.953.0" + "@aws-sdk/util-user-agent-browser" "3.953.0" + "@aws-sdk/util-user-agent-node" "3.953.0" + "@smithy/config-resolver" "^4.4.4" + "@smithy/core" "^3.19.0" + "@smithy/fetch-http-handler" "^5.3.7" + "@smithy/hash-node" "^4.2.6" + "@smithy/invalid-dependency" "^4.2.6" + "@smithy/middleware-content-length" "^4.2.6" + "@smithy/middleware-endpoint" "^4.3.15" + "@smithy/middleware-retry" "^4.4.15" + "@smithy/middleware-serde" "^4.2.7" + "@smithy/middleware-stack" "^4.2.6" + "@smithy/node-config-provider" "^4.3.6" + "@smithy/node-http-handler" "^4.4.6" + "@smithy/protocol-http" "^5.3.6" + "@smithy/smithy-client" "^4.10.0" + "@smithy/types" "^4.10.0" + "@smithy/url-parser" "^4.2.6" + "@smithy/util-base64" "^4.3.0" + "@smithy/util-body-length-browser" "^4.2.0" + "@smithy/util-body-length-node" "^4.2.1" + "@smithy/util-defaults-mode-browser" "^4.3.14" + "@smithy/util-defaults-mode-node" "^4.2.17" + "@smithy/util-endpoints" "^3.2.6" + "@smithy/util-middleware" "^4.2.6" + "@smithy/util-retry" "^4.2.6" + "@smithy/util-utf8" "^4.2.0" + "@smithy/util-waiter" "^4.2.6" + tslib "^2.6.2" + "@aws-sdk/client-cloudcontrol@^3": version "3.953.0" resolved "https://registry.yarnpkg.com/@aws-sdk/client-cloudcontrol/-/client-cloudcontrol-3.953.0.tgz#e5e23d69e8905fa8c0b6b441757d634a3bd2d607"