Infrastructure CDK
AWS CDK est un framework permettant de définir une infrastructure cloud via du code et de la déployer via AWS CloudFormation.
Le générateur d’infrastructure TypeScript crée une application d’infrastructure AWS CDK écrite en TypeScript. L’application générée intègre des bonnes pratiques de sécurité grâce aux vérifications de Checkov.
Utilisation
Section intitulée « Utilisation »Générer un projet d’infrastructure
Section intitulée « Générer un projet d’infrastructure »Vous pouvez générer un nouveau projet d’infrastructure de deux manières :
- Installez le Nx Console VSCode Plugin si ce n'est pas déjà fait
- Ouvrez la console Nx dans VSCode
- Cliquez sur
Generate (UI)
dans la section "Common Nx Commands" - Recherchez
@aws/nx-plugin - ts#infra
- Remplissez les paramètres requis
- Cliquez sur
Generate
pnpm nx g @aws/nx-plugin:ts#infra
yarn nx g @aws/nx-plugin:ts#infra
npx nx g @aws/nx-plugin:ts#infra
bunx nx g @aws/nx-plugin:ts#infra
Vous pouvez également effectuer une simulation pour voir quels fichiers seraient modifiés
pnpm nx g @aws/nx-plugin:ts#infra --dry-run
yarn nx g @aws/nx-plugin:ts#infra --dry-run
npx nx g @aws/nx-plugin:ts#infra --dry-run
bunx nx g @aws/nx-plugin:ts#infra --dry-run
Paramètre | Type | Par défaut | Description |
---|---|---|---|
name Requis | string | - | The name of the application. |
directory | string | packages | The directory of the new application. |
Résultat du générateur
Section intitulée « Résultat du générateur »Le générateur créera la structure de projet suivante dans le répertoire <directory>/<name>
:
Répertoiresrc
- main.ts Point d’entrée de l’application instanciant les stages CDK à déployer
Répertoirestages Définitions des stages CDK
- application-stage.ts Définit un ensemble de stacks à déployer dans un stage
Répertoirestacks Définitions des stacks CDK
- application-stack.ts Stack principale de l’application
- cdk.json Configuration CDK
- project.json Configuration du projet et cibles de build
- checkov.yml Fichier de configuration Checkov
Implémentation de votre infrastructure CDK
Section intitulée « Implémentation de votre infrastructure CDK »Vous pouvez commencer à écrire votre infrastructure CDK dans src/stacks/application-stack.ts
, par exemple :
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);
// Déclarez votre infrastructure ici new Bucket(this, 'MyBucket'); }}
Stages et Stacks
Section intitulée « Stages et Stacks »Vous remarquerez que le fichier principal src/main.ts
instancie un Stage CDK nommé <namespace>-sandbox
. Ce stage est destiné à vos propres développements et tests.
new ApplicationStage(app, 'project-sandbox', { env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION, },});
Vous pouvez ajouter d’autres stages, par exemple définir des stages beta
et prod
déployés dans des environnements distincts :
new ApplicationStage(app, 'project-beta', { env: { account: '123456789012', // compte beta region: 'us-west-2', },});new ApplicationStage(app, 'project-prod', { env: { account: '098765432109', // compte prod region: 'us-west-2', },});
Un Stage définit un ensemble de stacks à déployer conjointement pour composer votre application. Vous pouvez instancier autant de stacks que nécessaire dans un stage, par exemple :
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';
/** * Définit un ensemble de stacks CDK composant votre application */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, }); }}
Infrastructure d’API
Section intitulée « Infrastructure d’API »Si vous avez utilisé les générateurs tRPC API ou FastAPI, vous remarquerez que des constructs sont déjà disponibles dans packages/common/constructs
pour les déployer.
Par exemple, si vous avez créé une API tRPC nommée my-api
, vous pouvez simplement importer et instancier le construct pour ajouter l’infrastructure nécessaire :
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);
// Ajoutez l'infrastructure pour votre API new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this).build(), }); }}
Infrastructure de site web
Section intitulée « Infrastructure de site web »Si vous avez utilisé le générateur site web CloudScape, un construct est déjà disponible dans packages/common/constructs
. Par exemple :
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);
// Ajoutez l'infrastructure pour votre site web new MyWebsite(this, 'MyWebsite'); }}
Il est important de déclarer le site web après les constructs d’API pour que la Configuration d’exécution du site inclue toutes les configs d’API.
Synthèse de votre infrastructure
Section intitulée « Synthèse de votre infrastructure »En plus des cibles de compilation, lint et test par défaut, votre projet d’infrastructure est synthétisé en CloudFormation lors du build. Cette opération peut aussi être exécutée séparément via la cible synth
:
pnpm nx run <my-infra>:synth
yarn nx run <my-infra>:synth
npx nx run <my-infra>:synth
bunx nx run <my-infra>:synth
Vous trouverez l’assembly cloud synthétisée dans le dossier dist
racine, sous dist/packages/<my-infra-project>/cdk.out
.
Tests de sécurité
Section intitulée « Tests de sécurité »Une cible checkov
est ajoutée pour exécuter des vérifications de sécurité sur votre infrastructure via Checkov.
pnpm nx run <my-infra>:checkov
yarn nx run <my-infra>:checkov
npx nx run <my-infra>:checkov
bunx nx run <my-infra>:checkov
Les résultats des tests de sécurité se trouvent dans le dossier dist
racine, sous dist/packages/<my-infra-project>/checkov
.
Suppression de vérifications Checkov
Section intitulée « Suppression de vérifications Checkov »Il peut être nécessaire de supprimer certaines règles sur des ressources. Deux méthodes sont possibles :
Supprimer une règle sur un construct donné
Section intitulée « Supprimer une règle sur un construct donné »import { suppressRules } from ':my-scope/common-constructs';
// Supprime la règle CKV_AWS_XXX pour le construct donnésuppressRules(construct, ['CKV_AWS_XXX'], 'Raison');
Supprimer une règle sur un construct descendant
Section intitulée « Supprimer une règle sur un construct descendant »import { suppressRules } from ':my-scope/common-constructs';
// Supprime CKV_AWS_XXX pour le construct ou ses descendants de type BucketsuppressRules(construct, ['CKV_AWS_XXX'], 'Raison', (construct) => construct instanceof Bucket);
Bootstrap de votre(vos) compte(s) AWS
Section intitulée « Bootstrap de votre(vos) compte(s) AWS »Si vous déployez une application CDK sur un compte AWS pour la première fois, celui-ci doit être bootstrappé.
Assurez-vous d’abord d’avoir configuré les credentials pour votre compte AWS.
Utilisez ensuite la commande cdk bootstrap
:
npx cdk bootstrap aws://<account-id>/<region>
Pour plus de détails, consultez la documentation CDK.
Déploiement sur AWS
Section intitulée « Déploiement sur AWS »Après un build, vous pouvez déployer votre infrastructure via la cible deploy
.
Assurez-vous d’avoir configuré les credentials pour votre compte AWS.
Exécutez ensuite la cible de déploiement :
pnpm nx run <my-infra>:deploy <my-infra>-sandbox/*
yarn nx run <my-infra>:deploy <my-infra>-sandbox/*
npx nx run <my-infra>:deploy <my-infra>-sandbox/*
bunx nx run <my-infra>:deploy <my-infra>-sandbox/*
Déploiement sur AWS dans un pipeline CI/CD
Section intitulée « Déploiement sur AWS dans un pipeline CI/CD »Utilisez la cible deploy-ci
pour les déploiements dans un pipeline CI/CD :
pnpm nx run <my-infra>:deploy-ci my-stage/*
yarn nx run <my-infra>:deploy-ci my-stage/*
npx nx run <my-infra>:deploy-ci my-stage/*
bunx nx run <my-infra>:deploy-ci my-stage/*
Cette cible diffère légèrement en déployant l’assembly cloud pré-synthétisée plutôt que de synthétiser à la volée. Cela évite les problèmes de non-déterminisme liés aux versions de packages, garantissant que chaque étape du pipeline déploie la même assembly cloud.
Suppression de l’infrastructure AWS
Section intitulée « Suppression de l’infrastructure AWS »Utilisez la cible destroy
pour supprimer vos ressources :
pnpm nx run <my-infra>:destroy <my-infra>-sandbox/*
yarn nx run <my-infra>:destroy <my-infra>-sandbox/*
npx nx run <my-infra>:destroy <my-infra>-sandbox/*
bunx nx run <my-infra>:destroy <my-infra>-sandbox/*
Informations complémentaires
Section intitulée « Informations complémentaires »Pour en savoir plus sur CDK, consultez le Guide développeur CDK et la Référence API.