Amazon Bedrock AgentCore Runtime の CI/CD 環境をとりあえずつくる

こんにちは、広野です。

コンテナがらみのリソースは CI/CD 環境がないとデプロイするまでがコマンドだらけになって嫌気がさすので、いつも最初に CI/CD 環境をつくることから始めています。Amazon Bedrock AgentCore Runtime は Amazon S3 に配置したソースコードからの簡単なデプロイもできるのですが、今後のスケールも考えてコンテナで最初から作ろうと思いました。

 

アーキテクチャ

以下のアーキテクチャで作っています。以前作成したコンテナ Lambda の CI/CD 環境と 9 割以上同じです。これを書いてて思いましたが AgentCore Runtime はコンテナ Lambda を作ったことがある人なら馴染み易いですね。

 

どのように動くか

開発環境 (IDE) で、以下のように必要なコード群を配置して AWS CodeCommit リポジトリに push します。

コードが CodeCommit にアップロードされると、以下のように AWS CodePipeline が動き出します。画像は正常完了後のものです。

デプロイが完了すると、マネジメントコンソール内で Amazon Bedrock AgentCore Runtime が出来上がったことが確認できます。

「テストエンドポイント」を押して動作を確認してみます。

今回は、AWS Knowledge MCP Server に問い合わせてくれる単純なエージェントを作りましたので、AWS に関する質問を投げてみます。※後ほどエージェントのコードは貼り付けます。

回答が長かったので画像は途中で切れてしまっていますが、しっかりと説明してくれました。

 

エージェントのコード

IDE 内で作成したエージェント用のコードです。これ自体は全然大したものではないです。動いたサンプル程度に思って下さい。

app.py (エージェントロジック)

シンプルに、MCP サーバーに聞きに行くだけのエージェントです。LLM は Amazon Nova 2 Lite を使っています。

import os
from strands import Agent
from strands.tools.mcp import MCPClient
from mcp.client.streamable_http import streamablehttp_client
from bedrock_agentcore import BedrockAgentCoreApp
os.environ["AWS_DEFAULT_REGION"] = "ap-northeast-1"
app = BedrockAgentCoreApp()
mcp = MCPClient(
  lambda: streamablehttp_client(
    "https://knowledge-mcp.global.api.aws"
  )
)
@app.entrypoint
def invoke(payload):
  user_message = payload.get("prompt", "プロンプトの取得に失敗したのでその旨ユーザーに伝えてください。")
  try:
    with mcp:
      agent = Agent(
        model="global.amazon.nova-2-lite-v1:0",
        system_prompt="""あなたは AWS の技術仕様に精通したシニアソリューションアーキテクトです。
        ユーザーの質問に対して、提供されたツールを使用して AWS 公式ドキュメントから正確な情報を取得し、
        丁寧かつ専門的に回答してください。情報が見つからない場合は、推測で答えず正直に伝えてください。""",
        tools=mcp.list_tools_sync()
      )
      result = agent(user_message)
      return {"result": result.message}
  except Exception as e:
    app.logger.error(f"エージェントエラー: {e}")
    return {"error": "エージェントの処理中にエラーが発生しました"}
if __name__ == "__main__":
  app.run()

requirements.txt

これもシンプルに、インストールが必要な Python モジュールを並べただけです。

strands-agents
bedrock-agentcore
mcp

Dockerfile

AWS CodeBuild でビルドするときに使用します。

FROM --platform=linux/arm64 public.ecr.aws/docker/library/python:3.14-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
EXPOSE 8080
ENTRYPOINT ["python", "app.py"]

使用するコンテナイメージは Python 3.14 のスリムなものにしました。Amazon S3 からデプロイするときは執筆時点では Python 3.13 が最新のバージョンとして選べるようでしたが、コンテナイメージだとビルド環境の制約に依存しそうです。

requirements.txt を元にモジュールをインストールし、app.py を配置します。

buildspec.yml

AWS CodeBuild でビルドするときに使用します。

Amazon Bedrock AgentCore Runtime は ARM64 アーキテクチャで動作するので、コンテナイメージをビルドするコマンドに明示的に ARM64 を使用するオプションを付けます。$マークの環境変数が記載されていますが、これは CodeBuild から渡されます。

version: 0.2

phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com
  build:
    commands:
      - echo Building the Docker image...
      - docker build --platform linux/arm64 -t $IMAGE_REPO_NAME:$IMAGE_TAG .
      - docker tag $IMAGE_REPO_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
  post_build:
    commands:
      - echo Pushing the Docker image...
      - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
artifacts:
  files:
    - cfn_agentcore_runtime.yml

cfn_agentcore_runtime.yml

デプロイフェーズで使用します。

ビルドフェーズでは、ここまでのファイルを使用してコンテナイメージを作成し、Amazon ECR リポジトリに保存するまでを担当しました。

デプロイフェーズでは、作成されたコンテナイメージから Amazon Bedrock AgentCore Runtime をデプロイします。このとき、アタッチする IAM ロールも作成します。今後別の機能を使用することを想定して、広めに権限を付けています。

Parameters で定義されているパラメータは、AWS CodePipeline から環境変数を渡されオーバーライドされます。値は何でもいいのですがパラメータの定義をしておかないと、エラーになります。

AWSTemplateFormatVersion: 2010-09-09
Description: The CloudFormation template that creates a Bedrock AgentCore runtime and a relevant IAM role.
# ------------------------------------------------------------#
# Input Parameters
# ------------------------------------------------------------#
Parameters:
  SystemName:
    Type: String
    Description: System name. use lower case only. (e.g. example)
    Default: example
    MaxLength: 10
    MinLength: 1
  SubName:
    Type: String
    Description: System sub name. use lower case only. (e.g. prod or dev)
    Default: dev
    MaxLength: 10
    MinLength: 1
  ImageTag:
    Type: String
    Default: xxxxxxxxxxxxxxxxxxxx
    MaxLength: 100
    MinLength: 1
  ImgRepoName:
    Type: String
    Default: xxxxxxxxxxxxxxxxxxxx
    MaxLength: 100
    MinLength: 1

Resources:
# ------------------------------------------------------------#
# Bedrock AgentCore Runtime
# ------------------------------------------------------------#
  AgentCoreRuntime:
    Type: AWS::BedrockAgentCore::Runtime
    Properties:
      AgentRuntimeName: !Sub ${SystemName}_${SubName}_agent
      Description: !Sub AI Agent for ${SystemName}-${SubName}
      AgentRuntimeArtifact:
        ContainerConfiguration:
          ContainerUri: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${ImgRepoName}:${ImageTag}
      NetworkConfiguration:
        NetworkMode: PUBLIC
      ProtocolConfiguration: HTTP
      RequestHeaderConfiguration:
        RequestHeaderAllowlist:
          - Authorization
      RoleArn: !GetAtt AgentCoreRuntimeRole.Arn
      Tags: 
        Cost: !Sub ${SystemName}-${SubName}
    DependsOn:
      - AgentCoreRuntimeRole

# ------------------------------------------------------------#
# Bedrock AgentCore Runtime Role (IAM)
# ------------------------------------------------------------#
  AgentCoreRuntimeRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub AgentCoreRuntimeRole-${SystemName}-${SubName}
      Description: This role allows Bedrock AgentCore Runtime to invoke models and push logs.
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - bedrock-agentcore.amazonaws.com
            Action:
              - sts:AssumeRole
            Condition:
              StringEquals:
                "aws:SourceAccount": !Ref AWS::AccountId
              ArnLike:
                "aws:SourceArn": !Sub "arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:*"
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess
      Policies:
        - PolicyName: !Sub AgentCoreRuntimePolicy-${SystemName}-${SubName}
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - logs:DescribeLogStreams
                  - logs:CreateLogGroup
                Resource:
                  - !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/bedrock-agentcore/runtimes/*
              - Effect: Allow
                Action:
                  - logs:DescribeLogGroups
                Resource:
                  - !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:*
              - Effect: Allow
                Action:
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource:
                  - !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/bedrock-agentcore/runtimes/*:log-stream:*
              - Effect: Allow
                Action: cloudwatch:PutMetricData
                Resource: "*"
                Condition:
                  StringEquals:
                    cloudwatch:namespace: bedrock-agentcore
              - Effect: Allow
                Action:
                  - logs:CreateLogGroup
                  - logs:PutDeliverySource
                  - logs:PutDeliveryDestination
                  - logs:CreateDelivery
                  - logs:GetDeliverySource
                  - logs:DeleteDeliverySource
                  - logs:DeleteDeliveryDestination
                Resource: "*"
              - Sid: BedrockModelInvocation
                Effect: Allow
                Action:
                  - bedrock:InvokeModel
                  - bedrock:InvokeModelWithResponseStream
                  - bedrock:ApplyGuardrail
                Resource:
                  - arn:aws:bedrock:*::foundation-model/*
                  - arn:aws:bedrock:*:*:inference-profile/*
                  - !Sub arn:aws:bedrock:${AWS::Region}:${AWS::AccountId}:*
              - Effect: Allow
                Action:
                  - ecr:BatchGetImage
                  - ecr:GetDownloadUrlForLayer
                Resource:
                  - !Sub arn:aws:ecr:${AWS::Region}:${AWS::AccountId}:repository/${ImgRepoName}
              - Effect: Allow
                Action:
                  - ecr:GetAuthorizationToken
                Resource: "*"
              - Effect: Allow
                Action:
                  - bedrock-agentcore:GetWorkloadAccessToken
                  - bedrock-agentcore:GetWorkloadAccessTokenForJWT
                  - bedrock-agentcore:GetWorkloadAccessTokenForUserId
                Resource:
                  - !Sub arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:workload-identity-directory/default
                  - !Sub arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:workload-identity-directory/default/workload-identity/${SystemName}_${SubName}_agent-*
              - Effect: Allow
                Action:
                  - bedrock-agentcore:GetResourceApiKey
                Resource:
                  - !Sub arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:token-vault/default
                  - !Sub arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:token-vault/default/apikeycredentialprovider/*
                  - !Sub arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:workload-identity-directory/default
                  - !Sub arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:workload-identity-directory/default/workload-identity/*
              - Effect: Allow
                Action:
                  - secretsmanager:GetSecretValue
                Resource:
                  - !Sub arn:aws:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:bedrock-agentcore-identity!default/oauth2/*
                  - !Sub arn:aws:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:bedrock-agentcore-identity!default/apikey/*
              - Effect: Allow
                Action:
                  - bedrock-agentcore:GetResourceOauth2Token
                Resource:
                  - !Sub arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:token-vault/default
                  - !Sub arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:token-vault/default/oauth2credentialprovider/*
                  - !Sub arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:workload-identity-directory/default
                  - !Sub arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:workload-identity-directory/default/workload-identity/${SystemName}_${SubName}_agent-*
              - Effect: Allow
                Action:
                  - aws-marketplace:ViewSubscriptions
                  - aws-marketplace:Subscribe
                Resource: "*"
                Condition:
                  StringEquals:
                    aws:CalledViaLast: bedrock.amazonaws.com
              - Effect: Allow
                Action:
                  - bedrock-agentcore:StartCodeInterpreterSession
                  - bedrock-agentcore:InvokeCodeInterpreter
                  - bedrock-agentcore:StopCodeInterpreterSession
                  - bedrock-agentcore:GetCodeInterpreter
                  - bedrock-agentcore:GetCodeInterpreterSession
                  - bedrock-agentcore:ListCodeInterpreterSessions
                Resource:
                  - !Sub arn:aws:bedrock-agentcore:${AWS::Region}:aws:code-interpreter/aws.codeinterpreter.v1
              - Effect: Allow
                Action:
                  - bedrock-agentcore:CreateWorkloadIdentity
                  - bedrock-agentcore:GetWorkloadAccessTokenForUserId
                Resource:
                  - !Sub arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:workload-identity-directory/default
                  - !Sub arn:aws:bedrock-agentcore:${AWS::Region}:${AWS::AccountId}:workload-identity-directory/default/workload-identity/*
              - Effect: Allow
                Action: sts:GetWebIdentityToken
                Resource: "*"

# ------------------------------------------------------------#
# Output Parameters
# ------------------------------------------------------------#
Outputs:
# AgentCore
  AgentRuntimeArn:
    Value: !GetAtt AgentCoreRuntime.AgentRuntimeArn
  AgentRuntimeId:
    Value: !GetAtt AgentCoreRuntime.AgentRuntimeId
  AgentRuntimeVersion:
    Value: !GetAtt AgentCoreRuntime.AgentRuntimeVersion

 

CI/CD 環境の AWS CloudFormation テンプレート

最後になりましたが、まずこれを流して CI/CD 環境を構築しました。これがないと何も始まらないです。(私は)

AgentCore Runtime 用に気を付けたのは、ARM64 用のビルド環境にすることです。”aws/codebuild/amazonlinux-aarch64-standard:3.0″ というイメージを指定しています。

AWSTemplateFormatVersion: 2010-09-09
Description: The CloudFormation template that creates a CI/CD environment for the AI agent. The created container image runs in Amazon Bedrock AgentCore.

# ------------------------------------------------------------#
# Input Parameters
# ------------------------------------------------------------#
Parameters:
  SystemName:
    Type: String
    Description: System name. use lower case only. (e.g. example)
    Default: example
    MaxLength: 10
    MinLength: 1
    AllowedPattern: "^[a-z0-9]+$"

  SubName:
    Type: String
    Description: System sub name. use lower case only. (e.g. prod or dev)
    Default: dev
    MaxLength: 10
    MinLength: 1
    AllowedPattern: "^[a-z0-9]+$"

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: "General Configuration"
        Parameters:
          - SystemName
          - SubName

Resources:
# ------------------------------------------------------------#
# S3
# ------------------------------------------------------------#
  S3BucketArtifact:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub ${SystemName}-${SubName}-aiagent-artifact
      LifecycleConfiguration:
        Rules:
          - Id: AutoDelete
            Status: Enabled
            ExpirationInDays: 14
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      Tags:
        - Key: Cost
          Value: !Sub ${SystemName}-${SubName}

  S3BucketLogs:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub ${SystemName}-${SubName}-aiagent-logs
      LifecycleConfiguration:
        Rules:
          - Id: AutoDelete
            Status: Enabled
            ExpirationInDays: 365
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      Tags:
        - Key: Cost
          Value: !Sub ${SystemName}-${SubName}

# ------------------------------------------------------------#
# ECR
# ------------------------------------------------------------#
  EcrRepositoryAiAgent:
    Type: AWS::ECR::Repository
    Properties:
      RepositoryName: !Sub ${SystemName}-${SubName}-aiagent
      EncryptionConfiguration:
        EncryptionType: AES256
      ImageScanningConfiguration:
        ScanOnPush: true
      ImageTagMutability: IMMUTABLE
      LifecyclePolicy:
        LifecyclePolicyText: |
          {
            "rules": [
              {
                "rulePriority": 1,
                "description": "Keep only 5 images, expire all others",
                "selection": {
                  "tagStatus": "any",
                  "countType": "imageCountMoreThan",
                  "countNumber": 5
                },
                "action": {
                  "type": "expire"
                }
              }
            ]
          }
      EmptyOnDelete: true
      Tags:
        - Key: Cost
          Value: !Sub ${SystemName}-${SubName}

# ------------------------------------------------------------#
# CodeCommit Repository
# ------------------------------------------------------------#
  CodeCommitRepoAiAgent:
    Type: AWS::CodeCommit::Repository
    Properties:
      RepositoryName: !Sub ${SystemName}-${SubName}-aiagent
      RepositoryDescription: !Sub AI Agent for ${SystemName}-${SubName}
      Tags:
        - Key: Cost
          Value: !Sub ${SystemName}-${SubName}

# ------------------------------------------------------------#
# CodePipeline
# ------------------------------------------------------------#
  CodePipelineAiAgent:
    Type: AWS::CodePipeline::Pipeline
    Properties:
      Name: !Sub ${SystemName}-${SubName}-aiagent
      PipelineType: V2
      ArtifactStore:
        Location: !Ref S3BucketArtifact
        Type: S3
      RestartExecutionOnUpdate: false
      RoleArn: !GetAtt CodePipelineServiceRoleAiAgent.Arn
      Stages:
        - Name: Source
          Actions:
            - Name: Source
              RunOrder: 1
              ActionTypeId:
                Category: Source
                Owner: AWS
                Version: 1
                Provider: CodeCommit
              Configuration:
                RepositoryName: !GetAtt CodeCommitRepoAiAgent.Name
                BranchName: main
                PollForSourceChanges: false
                OutputArtifactFormat: CODEBUILD_CLONE_REF
              Namespace: SourceVariables
              OutputArtifacts:
                - Name: Source
        - Name: Build
          Actions:
            - Name: Build
              RunOrder: 1
              Region: !Sub ${AWS::Region}
              ActionTypeId:
                Category: Build
                Owner: AWS
                Version: 1
                Provider: CodeBuild
              Configuration:
                ProjectName: !Ref CodeBuildProjectAiAgent
                BatchEnabled: false
                EnvironmentVariables: |
                  [
                    {
                      "name": "IMAGE_TAG",
                      "type": "PLAINTEXT",
                      "value": "#{codepipeline.PipelineExecutionId}"
                    }
                  ]
              Namespace: BuildVariables
              InputArtifacts:
                - Name: Source
              OutputArtifacts:
                - Name: Build
        - Name: Deploy
          Actions:
            - ActionTypeId:
                Category: Deploy
                Owner: AWS
                Provider: CloudFormation
                Version: 1
              Configuration:
                StackName: !Sub ${SystemName}-${SubName}-agentcore-runtime
                Capabilities: CAPABILITY_NAMED_IAM
                RoleArn: !GetAtt CodePipelineDeployCreateUpdateRoleAiAgent.Arn
                ActionMode: CREATE_UPDATE
                TemplatePath: Build::cfn_agentcore_runtime.yml
                ParameterOverrides: !Sub '{"SystemName":"${SystemName}","SubName":"${SubName}","ImageTag":"#{codepipeline.PipelineExecutionId}","ImgRepoName":"${EcrRepositoryAiAgent}"}'
              InputArtifacts:
                - Name: Build
              Name: CreateOrUpdate
              RoleArn: !GetAtt CodePipelineDeployCreateUpdateActionRoleAiAgent.Arn
              RunOrder: 1
      Tags:
        - Key: Cost
          Value: !Sub ${SystemName}-${SubName}
    DependsOn:
      - CodePipelineServiceRoleAiAgent
      - CodeBuildProjectAiAgent
      - CodePipelineDeployCreateUpdateActionRoleAiAgent
      - EcrRepositoryAiAgent

# ------------------------------------------------------------#
# CodePipeline Service Role (IAM)
# ------------------------------------------------------------#
  CodePipelineServiceRoleAiAgent:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub CpServiceRoleAiAgent-${SystemName}-${SubName}
      Description: This role allows CodePipeline to call each stages.
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
              - codepipeline.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: /
      Policies:
        - PolicyName: !Sub CpServicePolicyAiAgent-${SystemName}-${SubName}
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - "codecommit:CancelUploadArchive"
                  - "codecommit:GetBranch"
                  - "codecommit:GetCommit"
                  - "codecommit:GetRepository"
                  - "codecommit:GetUploadArchiveStatus"
                  - "codecommit:UploadArchive"
                Resource: !GetAtt CodeCommitRepoAiAgent.Arn
              - Effect: Allow
                Action:
                  - "codebuild:BatchGetBuilds"
                  - "codebuild:StartBuild"
                  - "codebuild:BatchGetBuildBatches"
                  - "codebuild:StartBuildBatch"
                Resource: "*"
              - Effect: Allow
                Action:
                  - "cloudwatch:*"
                  - "s3:*"
                Resource: "*"
              - Effect: Allow
                Action:
                  - "lambda:InvokeFunction"
                  - "lambda:ListFunctions"
                Resource: "*"
              - Effect: Allow
                Action: "sts:AssumeRole"
                Resource:
                  - !GetAtt CodePipelineDeployCreateUpdateActionRoleAiAgent.Arn
    DependsOn:
      - CodeCommitRepoAiAgent
      - CodePipelineDeployCreateUpdateActionRoleAiAgent

# ------------------------------------------------------------#
# CodePipeline Deploy Create Update Role (IAM)
# ------------------------------------------------------------#
  CodePipelineDeployCreateUpdateRoleAiAgent:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub CpCrUpdRoleAiAgent-${SystemName}-${SubName}
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: cloudformation.amazonaws.com
        Version: "2012-10-17"
      Path: /
      Policies:
        - PolicyName: !Sub CpCrUpdPolicyAiAgent-${SystemName}-${SubName}
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Action: "*"
                Effect: Allow
                Resource: "*"

# ------------------------------------------------------------#
# CodePipeline Deploy Create Update Action Role (IAM)
# ------------------------------------------------------------#
  CodePipelineDeployCreateUpdateActionRoleAiAgent:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub CpCrUpdActionRoleAiAgent-${SystemName}-${SubName}
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              AWS:
                Fn::Join:
                  - ""
                  - - "arn:"
                    - Ref: AWS::Partition
                    - ":iam::"
                    - Ref: AWS::AccountId
                    - :root
        Version: "2012-10-17"
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AWSCloudFormationFullAccess
      Policies:
        - PolicyName: !Sub CpCrUpdPolicyAiAgent-${SystemName}-${SubName}
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Action: iam:PassRole
                Effect: Allow
                Resource: !GetAtt CodePipelineDeployCreateUpdateRoleAiAgent.Arn
              - Action:
                  - s3:GetBucket*
                  - s3:GetObject*
                  - s3:List*
                Effect: Allow
                Resource:
                  - !Sub arn:aws:s3:::${S3BucketArtifact}
                  - !Sub arn:aws:s3:::${S3BucketArtifact}/*
    DependsOn:
      - CodePipelineDeployCreateUpdateRoleAiAgent
      - S3BucketArtifact

# ------------------------------------------------------------#
# EventBridge Rule for Starting CodePipeline
# ------------------------------------------------------------#
  EventBridgeRuleStartCodePipelineAiAgent:
    Type: AWS::Events::Rule
    Properties:
      Name: !Sub ${SystemName}-${SubName}-aiagent-start-codepipeline
      Description: !Sub This rule starts pptx pdf converter CodePipeline for ${SystemName}-${SubName}. The trigger is the source code change in CodeCommit.
      EventBusName: !Sub "arn:aws:events:${AWS::Region}:${AWS::AccountId}:event-bus/default"
      EventPattern:
        source:
          - "aws.codecommit"
        detail-type:
          - "CodeCommit Repository State Change"
        resources:
          - !GetAtt CodeCommitRepoAiAgent.Arn
        detail:
          event:
            - referenceCreated
            - referenceUpdated
          referenceType:
            - branch
          referenceName:
            - main
      RoleArn: !GetAtt EventBridgeRuleStartCpRoleAiAgent.Arn
      State: ENABLED
      Targets:
        - Arn: !Sub "arn:aws:codepipeline:${AWS::Region}:${AWS::AccountId}:${CodePipelineAiAgent}"
          Id: !Sub ${SystemName}-${SubName}-aiagent-start-codepipeline
          RoleArn: !GetAtt EventBridgeRuleStartCpRoleAiAgent.Arn
    DependsOn:
      - EventBridgeRuleStartCpRoleAiAgent

# ------------------------------------------------------------#
# EventBridge Rule Start CodePipeline Role (IAM)
# ------------------------------------------------------------#
  EventBridgeRuleStartCpRoleAiAgent:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub EventBridgeStartCpRoleAiAgent-${SystemName}-${SubName}
      Description: !Sub This role allows EventBridge to start pptx pdf converter CodePipeline for ${SystemName}-${SubName}.
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
              - events.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: /
      Policies:
        - PolicyName: !Sub EventBridgeStartCpPolicyAiAgent-${SystemName}-${SubName}
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - "codepipeline:StartPipelineExecution"
                Resource:
                  - !Sub "arn:aws:codepipeline:${AWS::Region}:${AWS::AccountId}:${CodePipelineAiAgent}"
    DependsOn:
      - CodePipelineAiAgent

# ------------------------------------------------------------#
# CodeBuild Project
# ------------------------------------------------------------#
  CodeBuildProjectAiAgent:
    Type: AWS::CodeBuild::Project
    Properties:
      Name: !Sub ${SystemName}-${SubName}-aiagent
      Description: !Sub The build project for ${SystemName}-${SubName}-aiagent
      ResourceAccessRole: !GetAtt CodeBuildResourceAccessRoleAiAgent.Arn
      ServiceRole: !GetAtt CodeBuildServiceRoleAiAgent.Arn
      ConcurrentBuildLimit: 1
      Visibility: PRIVATE
      Source:
        Type: CODEPIPELINE
      SourceVersion: refs/heads/main
      Environment:
        Type: ARM_CONTAINER
        ComputeType: BUILD_GENERAL1_SMALL
        Image: "aws/codebuild/amazonlinux-aarch64-standard:3.0"
        ImagePullCredentialsType: CODEBUILD
        PrivilegedMode: true
        EnvironmentVariables:
          - Name: AWS_DEFAULT_REGION
            Type: PLAINTEXT
            Value: !Sub ${AWS::Region}
          - Name: AWS_ACCOUNT_ID
            Type: PLAINTEXT
            Value: !Sub ${AWS::AccountId}
          - Name: IMAGE_REPO_NAME
            Type: PLAINTEXT
            Value: !Ref EcrRepositoryAiAgent
      TimeoutInMinutes: 30
      QueuedTimeoutInMinutes: 60
      Artifacts:
        Type: CODEPIPELINE
      Cache:
        Type: NO_CACHE
      LogsConfig:
        CloudWatchLogs:
          GroupName: !Sub /aws/codebuild/${SystemName}-${SubName}-aiagent
          Status: ENABLED
        S3Logs:
          EncryptionDisabled: true
          Location: !Sub arn:aws:s3:::${S3BucketLogs}/codebuildBuildlog
          Status: ENABLED
      Tags:
        - Key: Cost
          Value: !Sub ${SystemName}-${SubName}
    DependsOn:
      - EcrRepositoryAiAgent
      - CodeBuildResourceAccessRoleAiAgent
      - CodeBuildServiceRoleAiAgent

# ------------------------------------------------------------#
# CodeBuild Resource Access Role (IAM)
# ------------------------------------------------------------#
  CodeBuildResourceAccessRoleAiAgent:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub CbResourceAccessRoleAiAgent-${SystemName}-${SubName}
      Description: This role allows CodeBuild to access CloudWatch Logs and Amazon S3 artifacts for the project's builds.
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
              - codebuild.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: /
      Policies:
        - PolicyName: !Sub CbResourceAccessPolicyAiAgent-${SystemName}-${SubName}
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - "logs:CreateLogGroup"
                  - "logs:CreateLogStream"
                  - "logs:PutLogEvents"
                Resource:
                  - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${SystemName}-${SubName}-aiagent"
                  - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${SystemName}-${SubName}-aiagent:*"
              - Effect: Allow
                Action:
                  - "s3:PutObject"
                  - "s3:GetObject"
                  - "s3:GetObjectVersion"
                  - "s3:GetBucketAcl"
                  - "s3:GetBucketLocation"
                Resource:
                  - !Sub arn:aws:s3:::${S3BucketLogs}
                  - !Sub arn:aws:s3:::${S3BucketLogs}/*

# ------------------------------------------------------------#
# CodeBuild Service Role (IAM)
# ------------------------------------------------------------#
  CodeBuildServiceRoleAiAgent:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub CbServiceRoleAiAgent-${SystemName}-${SubName}
      Description: This role allows CodeBuild to interact with dependant AWS services.
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
              - codebuild.amazonaws.com
            Action:
              - sts:AssumeRole
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPowerUser
      Policies:
        - PolicyName: !Sub CbServicePolicyAiAgent-${SystemName}-${SubName}
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - "codecommit:GitPull"
                Resource: !GetAtt CodeCommitRepoAiAgent.Arn
              - Effect: Allow
                Action:
                  - "ssm:GetParameters"
                Resource:
                  - !Sub "arn:aws:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${SystemName}_${SubName}_*"
              - Effect: Allow
                Action:
                  - "s3:*"
                Resource:
                  - !Sub arn:aws:s3:::${S3BucketArtifact}
                  - !Sub arn:aws:s3:::${S3BucketArtifact}/*
                  - !Sub arn:aws:s3:::${S3BucketLogs}
                  - !Sub arn:aws:s3:::${S3BucketLogs}/*
              - Effect: Allow
                Action:
                  - "logs:CreateLogGroup"
                  - "logs:CreateLogStream"
                  - "logs:PutLogEvents"
                Resource:
                  - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${SystemName}-${SubName}-aiagent"
                  - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${SystemName}-${SubName}-aiagent:*"
              - Effect: Allow
                Action:
                  - "codebuild:CreateReportGroup"
                  - "codebuild:CreateReport"
                  - "codebuild:UpdateReport"
                  - "codebuild:BatchPutTestCases"
                  - "codebuild:BatchPutCodeCoverages"
                Resource:
                  - !Sub "arn:aws:codebuild:${AWS::Region}:${AWS::AccountId}:report-group/${SystemName}-${SubName}-aiagent*"
    DependsOn:
      - CodeCommitRepoAiAgent
      - S3BucketArtifact
      - S3BucketLogs

 

まとめ

いかがでしたでしょうか?

とりあえず Amazon Bedrock AgentCore Runtime がデプロイされるところまで作りました。この後は React アプリ画面でエージェントとストリームレスポンスの会話ができるところまできちんと作り込もうと思います。

本記事が皆様のお役に立てれば幸いです。

タイトルとURLをコピーしました