콘텐츠로 이동

CDK 인프라

AWS CDK는 코드로 클라우드 인프라를 정의하고 AWS CloudFormation을 통해 프로비저닝하는 프레임워크입니다.

TypeScript 인프라 생성기는 TypeScript로 작성된 AWS CDK 인프라 애플리케이션을 생성합니다. 생성된 애플리케이션에는 Checkov 보안 검사를 통한 보안 모범 사례가 포함됩니다.

새 인프라 프로젝트를 두 가지 방법으로 생성할 수 있습니다:

  1. 설치 Nx Console VSCode Plugin 아직 설치하지 않았다면
  2. VSCode에서 Nx 콘솔 열기
  3. 클릭 Generate (UI) "Common Nx Commands" 섹션에서
  4. 검색 @aws/nx-plugin - ts#infra
  5. 필수 매개변수 입력
    • 클릭 Generate
    매개변수 타입 기본값 설명
    name 필수 string - The name of the application.
    directory string packages The directory of the new application.

    생성기는 <directory>/<name> 디렉토리에 다음 프로젝트 구조를 생성합니다:

    • 디렉터리src
      • main.ts CDK 스테이지를 인스턴스화하는 애플리케이션 진입점
      • 디렉터리stages CDK 스테이지 정의
        • application-stage.ts 스테이지에서 배포할 스택 컬렉션 정의
      • 디렉터리stacks CDK 스택 정의
        • application-stack.ts 메인 애플리케이션 스택
    • cdk.json CDK 구성 파일
    • project.json 프로젝트 구성 및 빌드 타겟
    • checkov.yml Checkov 구성 파일

    src/stacks/application-stack.ts 파일 내에서 CDK 인프라 작성을 시작할 수 있습니다. 예시:

    src/stacks/application-stack.ts
    import { Stack, StackProps } from 'aws-cdk-lib';
    import { Bucket } from 'aws-cdk-lib/aws-s3'
    import { Construct } from 'constructs';
    export class ApplicationStack extends Stack {
    constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    // 인프라 리소스 선언
    new Bucket(this, 'MyBucket');
    }
    }

    최상위 src/main.ts 파일이 <namespace>-sandbox 이름의 CDK 스테이지를 인스턴스화하는 것을 확인할 수 있습니다. 이 스테이지는 개발 및 테스트용으로 사용됩니다.

    src/main.ts
    new ApplicationStage(app, 'project-sandbox', {
    env: {
    account: process.env.CDK_DEFAULT_ACCOUNT,
    region: process.env.CDK_DEFAULT_REGION,
    },
    });

    betaprod 스테이지를 추가하여 별도 환경에 배포할 수 있습니다:

    src/main.ts
    new ApplicationStage(app, 'project-beta', {
    env: {
    account: '123456789012', // 베타 계정
    region: 'us-west-2',
    },
    });
    new ApplicationStage(app, 'project-prod', {
    env: {
    account: '098765432109', // 프로덕션 계정
    region: 'us-west-2',
    },
    });

    스테이지는 애플리케이션을 구성하는 스택 컬렉션을 정의합니다. 스테이지 내에서 원하는 만큼 스택을 생성할 수 있습니다:

    src/stages/application-stage.ts
    import { Stage, StageProps } from 'aws-cdk-lib';
    import { Construct } from 'constructs';
    import { BackendStack } from '../stacks/backend-stack.js';
    import { FrontendStack } from '../stacks/frontend-stack.js';
    /**
    * 애플리케이션을 구성하는 CDK 스택 컬렉션 정의
    */
    export class ApplicationStage extends Stage {
    constructor(scope: Construct, id: string, props?: StageProps) {
    super(scope, id, props);
    new BackendStack(this, 'Backend', {
    crossRegionReferences: true,
    })
    new FrontendStack(this, 'Frontend', {
    crossRegionReferences: true,
    });
    }
    }

    tRPC API 또는 FastAPI 생성기를 사용한 경우 packages/common/constructs에 배포용 구문이 이미 존재합니다.

    예를 들어 my-api 이름의 tRPC API를 생성한 경우, 구문을 임포트하여 인프라에 추가할 수 있습니다:

    src/stacks/application-stack.ts
    import * as cdk from 'aws-cdk-lib';
    import { Construct } from 'constructs';
    import { MyApi } from ':my-scope/common-constructs';
    export class ApplicationStack extends cdk.Stack {
    constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    // API 인프라 추가
    new MyApi(this, 'MyApi', {
    integrations: MyApi.defaultIntegrations(this).build(),
    });
    }
    }

    CloudScape 웹사이트 생성기를 사용한 경우 packages/common/constructs에 배포용 구문이 존재합니다:

    src/stacks/application-stack.ts
    import * as cdk from 'aws-cdk-lib';
    import { Construct } from 'constructs';
    import { MyWebsite } from ':my-scope/common-constructs';
    export class ApplicationStack extends cdk.Stack {
    constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    // 웹사이트 인프라 추가
    new MyWebsite(this, 'MyWebsite');
    }
    }

    웹사이트 런타임 구성에 모든 API 설정이 포함되도록 API 구문 선언 후 웹사이트를 선언해야 합니다.

    build 타겟의 일부로 기본 컴파일, 린트, 테스트 외에 인프라 프로젝트를 CloudFormation으로 _합성_합니다. synth 타겟을 실행하여 별도로 수행할 수도 있습니다:

    Terminal window
    pnpm nx run <my-infra>:synth

    합성된 클라우드 어셈블리는 루트 dist 폴더의 dist/packages/<my-infra-project>/cdk.out에서 확인할 수 있습니다.

    Checkov를 사용하여 인프라 보안 검사를 수행하는 checkov 타겟이 프로젝트에 추가됩니다:

    Terminal window
    pnpm nx run <my-infra>:checkov

    보안 테스트 결과는 루트 dist 폴더의 dist/packages/<my-infra-project>/checkov에서 확인할 수 있습니다.

    특정 리소스에 대한 규칙을 비활성화하는 두 가지 방법이 있습니다:

    import { suppressRules } from ':my-scope/common-constructs';
    // 해당 구문에 CKV_AWS_XXX 규칙 비활성화
    suppressRules(construct, ['CKV_AWS_XXX'], '사유');
    import { suppressRules } from ':my-scope/common-constructs';
    // Bucket 인스턴스인 경우 구문 또는 하위 구문에서 CKV_AWS_XXX 규칙 비활성화
    suppressRules(construct, ['CKV_AWS_XXX'], '사유', (construct) => construct instanceof Bucket);

    AWS 계정에 CDK 애플리케이션을 처음 배포할 때 부트스트랩이 필요합니다.

    먼저 AWS 계정 자격 증명 구성이 필요합니다.

    다음으로 cdk bootstrap 명령을 사용합니다:

    Terminal window
    npx cdk bootstrap aws://<account-id>/<region>

    자세한 내용은 CDK 문서를 참조하세요.

    빌드 후 deploy 타겟을 사용하여 인프라를 AWS에 배포할 수 있습니다.

    먼저 AWS 계정 자격 증명 구성이 필요합니다.

    다음으로 배포 타겟을 실행합니다:

    Terminal window
    pnpm nx run <my-infra>:deploy <my-infra>-sandbox/*

    CI/CD 파이프라인에서 배포할 경우 deploy-ci 타겟을 사용합니다:

    Terminal window
    pnpm nx run <my-infra>:deploy-ci my-stage/*

    이 타겟은 실시간 합성 대신 사전 합성된 클라우드 어셈블리를 배포하여 패키지 버전 변경으로 인한 비결정적 문제를 방지합니다.

    destroy 타겟으로 리소스를 정리할 수 있습니다:

    Terminal window
    pnpm nx run <my-infra>:destroy <my-infra>-sandbox/*

    CDK에 대한 자세한 내용은 CDK 개발자 가이드API 참조 문서를 참조하세요.