TypeScript Agent를 관계형 데이터베이스에 연결
connection 생성기는 TypeScript Agent를 관계형 데이터베이스 프로젝트에 연결하여 에이전트 팩토리 내에서 Prisma 클라이언트를 사용할 수 있도록 합니다.
사전 요구 사항
섹션 제목: “사전 요구 사항”이 생성기를 사용하기 전에 다음이 필요합니다:
사용법
섹션 제목: “사용법”생성기 실행
섹션 제목: “생성기 실행”- 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
- VSCode에서 Nx 콘솔 열기
- 클릭
Generate (UI)"Common Nx Commands" 섹션에서 - 검색
@aws/nx-plugin - connection - 필수 매개변수 입력
- 클릭
Generate
pnpm nx g @aws/nx-plugin:connectionyarn nx g @aws/nx-plugin:connectionnpx nx g @aws/nx-plugin:connectionbunx nx g @aws/nx-plugin:connectionAgent 프로젝트를 소스로, 관계형 데이터베이스 프로젝트를 타겟으로 선택합니다. 프로젝트에 여러 에이전트 컴포넌트가 포함된 경우 sourceComponent를 지정하여 명확히 구분합니다.
| 매개변수 | 타입 | 기본값 | 설명 |
|---|---|---|---|
| sourceProject 필수 | string | - | 소스 프로젝트 |
| targetProject 필수 | string | - | 연결할 대상 프로젝트 |
| sourceComponent | string | - | 연결을 시작할 소스 컴포넌트 (컴포넌트 이름, 소스 프로젝트 루트 기준 상대 경로, 또는 generator id). 프로젝트를 소스로 명시적으로 선택하려면 '.'을 사용하세요. |
| targetComponent | string | - | 연결할 대상 컴포넌트 (컴포넌트 이름, 대상 프로젝트 루트 기준 상대 경로, 또는 generator id). 프로젝트를 대상으로 명시적으로 선택하려면 '.'을 사용하세요. |
| preferInstallDependencies | boolean | true | 생성기 실행 후 의존성 설치를 선호할지 여부입니다. 여러 생성기를 일괄 처리할 때 설치를 연기하려면 false로 설정하세요 (후속 생성기가 Nx 프로젝트 그래프를 계산할 수 있도록 필요한 경우 설치는 여전히 실행됩니다); 마지막에 한 번만 설치합니다. |
생성기 출력
섹션 제목: “생성기 출력”생성기는 에이전트의 소스 디렉토리에서 두 개의 파일을 수정합니다:
디렉터리packages/my-service/src/my-agent
- agent.ts
getAgent내부에서 가져온 Prisma 클라이언트가 도구에서 사용 가능 - Dockerfile Aurora에 대한 SSL 연결을 위해 RDS CA 번들 설치
- agent.ts
또한 에이전트의 <agent-name>-dev 타겟이 데이터베이스의 dev 타겟에 의존하도록 업데이트됩니다.
Agent 도구에서 데이터베이스 사용
섹션 제목: “Agent 도구에서 데이터베이스 사용”Prisma 클라이언트는 getAgent() 내부에서 인스턴스화됩니다. ts#agent 생성기가 세션당 단일 Agent를 구성하므로 클라이언트도 세션의 수명 동안 재사용됩니다:
import { getPrisma as getMyDb } from ':my-scope/my-db';
export const getAgent = async () => { const myDb = await getMyDb(); // ... return new Agent({ /* use myDb in tools */ });};여러 데이터베이스
섹션 제목: “여러 데이터베이스”다른 타겟으로 생성기를 다시 실행하면 첫 번째 데이터베이스와 함께 두 번째 데이터베이스가 추가됩니다:
import { getPrisma as getMyDb } from ':my-scope/my-db';import { getPrisma as getOtherDb } from ':my-scope/other-db';
export const getAgent = async () => { const myDb = await getMyDb(); const otherDb = await getOtherDb(); // ... return new Agent({ /* use both clients in tools */ });};인프라
섹션 제목: “인프라”생성된 에이전트 구성은 IGrantable 및 IConnectable을 구현하므로 구성에서 직접 데이터베이스에 대한 네트워크 및 IAM 액세스 권한을 부여할 수 있습니다.
import { SecurityGroup } from 'aws-cdk-lib/aws-ec2';import { RuntimeNetworkConfiguration } from 'aws-cdk-lib/aws-bedrockagentcore';import { MyDatabase } from '@my-scope/common-constructs';
const db = new MyDatabase(this, 'Db', { vpc, ... });
const myAgent = new MyAgent(this, 'MyAgent', { networkConfiguration: RuntimeNetworkConfiguration.usingVpc(this, { vpc, vpcSubnets: { subnetType: SubnetType.PRIVATE_WITH_EGRESS }, securityGroups: [ new SecurityGroup(this, 'MyAgentSecurityGroup', { vpc, allowAllOutbound: true }), ], }),});
db.allowDefaultPortFrom(myAgent);db.grantConnect(myAgent);allowDefaultPortFrom은 에이전트 런타임이 데이터베이스 포트에 도달할 수 있도록 보안 그룹 규칙을 엽니다. grantConnect는 에이전트의 실행 역할에 IAM rds-db:connect 권한을 부여합니다.
데이터베이스와 동일한 VPC 내에서 에이전트를 실행하고, additional_iam_policy_statements를 통해 rds-db:connect 권한을 부여하며, 보안 그룹 규칙 쌍으로 네트워크 경로를 엽니다. aws_vpc.main 및 aws_subnet 리소스는 데이터베이스 배포 가이드에 정의되어 있습니다:
module "my_database" { source = "../../common/terraform/src/app/dbs/my-database" vpc_id = aws_vpc.main.id database_subnet_ids = aws_subnet.database[*].id lambda_subnet_ids = aws_subnet.private[*].id}
module "my_agent" { source = "../../common/terraform/src/app/agents/my-agent" enable_vpc = true vpc_id = aws_vpc.main.id subnet_ids = aws_subnet.private[*].id
appconfig_application_id = module.runtime_config_appconfig.application_id appconfig_application_arn = module.runtime_config_appconfig.application_arn
additional_iam_policy_statements = [ { Effect = "Allow" Action = ["rds-db:connect"] Resource = [ "arn:aws:rds-db:${data.aws_region.current.region}:${data.aws_caller_identity.current.account_id}:dbuser:${module.my_database.connect_resource_id}/${module.my_database.database_runtime_user}" ] } ]}
resource "aws_vpc_security_group_ingress_rule" "agent_to_database" { description = "Allow the agent runtime to connect to the database" security_group_id = module.my_database.security_group_id referenced_security_group_id = module.my_agent.security_group_id from_port = module.my_database.cluster_port to_port = module.my_database.cluster_port ip_protocol = "tcp"}
resource "aws_vpc_security_group_egress_rule" "agent_to_database" { description = "Allow outbound traffic from the agent runtime to the database" security_group_id = module.my_agent.security_group_id referenced_security_group_id = module.my_database.security_group_id from_port = module.my_database.cluster_port to_port = module.my_database.cluster_port ip_protocol = "tcp"}appconfig_application_id/appconfig_application_arn은 데이터베이스 모듈이 아닌 루트 모듈에서 한 번 선언된 공유 런타임 구성 AppConfig 애플리케이션에서 가져옵니다. 데이터베이스 모듈의 런타임 구성 항목이 배포되도록 인스턴스화할 때 database 네임스페이스를 포함합니다:
module "runtime_config_appconfig" { source = "../../common/terraform/src/core/runtime-config/appconfig"
application_name = "my-app-runtime-config" namespaces = ["connection", "agentcore", "database"]}RDS Proxy 없이 연결할 때 SSL 요구 사항
섹션 제목: “RDS Proxy 없이 연결할 때 SSL 요구 사항”연결 생성기는 Dockerfile을 업데이트하여 Amazon RDS CA 번들을 /usr/local/share/ca-certificates/rds-bundle.crt에 설치합니다. RDS Proxy 없이 연결할 때 Node.js가 인증서를 신뢰하도록 NODE_EXTRA_CA_CERTS를 해당 경로로 설정하세요:
new MyAgent(this, 'MyAgent', { ... environmentVariables: { NODE_EXTRA_CA_CERTS: '/usr/local/share/ca-certificates/rds-bundle.crt', },});module "my_agent" { ... environment_variables = { NODE_EXTRA_CA_CERTS = "/usr/local/share/ca-certificates/rds-bundle.crt" }}자세한 내용은 Amazon RDS SSL/TLS 문서를 참조하세요. RDS Proxy를 사용하는 경우 NODE_EXTRA_CA_CERTS를 구성할 필요가 없습니다.
로컬 개발
섹션 제목: “로컬 개발”pnpm nx <agent-name>-dev <project-name>yarn nx <agent-name>-dev <project-name>npx nx <agent-name>-dev <project-name>bunx nx <agent-name>-dev <project-name>이는 에이전트와 연결된 모든 데이터베이스를 시작합니다. LOCAL_DEV=true 환경 변수는 각 Prisma 클라이언트가 Aurora 대신 로컬 Docker 데이터베이스에 연결하도록 합니다.