

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# Procédure pas à pas - Partie 1
<a name="walkthrough-part-1"></a>

**Note**  
Constructions AWS Solutions est pris en charge sur les versions AWS CDK ≥ 1.46.0. 

 Ce didacticiel vous explique comment créer et déployer une application AWS CDK simple « Hello Constructs » qui utilise un modèle issu de AWS Solutions Constructs, de l'initialisation du projet au déploiement du modèle AWS CloudFormation résultant. L'application Hello Constructs va créer la solution simple suivante : 

![Schéma de l'architecture](http://docs.aws.amazon.com/fr_fr/solutions/latest/constructs/images/tutorial-part1.png)


## Hello Constructions
<a name="hello-konstruk"></a>

 Commençons à créer notre première application AWS CDK à l'aide d'un développement basé sur des modèles. 

**Note**  
 Ceci est un exemple de modification de`Hello CDK!`à partir des[Atelier CDK](https://cdkworkshop.com/). Si c'est la première fois que vous utilisez le CDK AWS, nous vous recommandons de commencer par cet atelier pour une procédure pas à pas pratique et comment tirer parti du CDK pour construire un projet réel. 

## Création de l'annuaire des applications et initialisation du CDK AWS
<a name="creating-the-app-directory-and-initializing-the-aws-cdk"></a>

 Créez un répertoire pour votre application CDK, puis créez une application AWS CDK dans ce répertoire. 

------
#### [ TypeScript ]

```
  mkdir hello-constructs     
  cd hello-constructs     
  cdk init --language typescript
```

------
#### [ Python ]

```
  mkdir hello-constructs     
  cd hello-constructs     
  cdk init --language python
```

------

**Astuce**  
C'est le bon moment pour ouvrir le projet dans votre IDE préféré et explorer. Pour en savoir plus sur la structure du projet, sélectionnez le lien approprié :  
[TypeScript](https://cdkworkshop.com/20-typescript/20-create-project/300-structure.html)
[Python](https://cdkworkshop.com/30-python/20-create-project/300-structure.html)

## Modification des dépendances de base de projet
<a name="update-project-base-dependencies-to-use-aws-cdk"></a>

**Avertissement**  
Pour garantir une bonne fonctionnalité, les packages AWS Solutions Constructs et AWS CDK doivent utiliser le même numéro de version dans votre projet. Par exemple, si vous utilisez AWS Solutions Constructs v.1.52.0, vous devez également utiliser AWS CDK v.1.52.0. 

**Astuce**  
 Prenez note de la version la plus récente d'AWS Solutions Constructs et appliquez ce numéro de version au`VERSION_NUMBER`dans les étapes ci-dessous (pour les conceptions AWS Solutions et les packages CDK AWS). Pour vérifier toutes les versions publiques de la bibliothèque Constructs,[Cliquez ici](https://github.com/awslabs/aws-solutions-constructs/releases).

------
#### [ TypeScript ]

Modifiez l'outil`package.json`avec les informations suivantes : 

```
  "devDependencies": {
    "@aws-cdk/assert": "VERSION_NUMBER",
    "@types/jest": "^24.0.22",
    "@types/node": "10.17.5",
    "jest": "^24.9.0",
    "ts-jest": "^24.1.0",
    "aws-cdk": "VERSION_NUMBER",
    "ts-node": "^8.1.0",
    "typescript": "~3.7.2"
  },
  "dependencies": {
    "@aws-cdk/core": "VERSION_NUMBER",
    "source-map-support": "^0.5.16"
  }
```

------
#### [ Python ]

Modifiez l'outil`setup.py`avec les informations suivantes :

```
install_requires=[
    "aws-cdk.core==VERSION_NUMBER",
],
```

------

 Installez les dépendances de base des projets. 

------
#### [ TypeScript ]

```
npm install      
```

------
#### [ Python ]

```
source .venv/bin/activate
pip install -r requirements.txt
```

------

 Créez et exécutez l'application et confirmez qu'elle crée une pile vide. 

------
#### [ TypeScript ]

```
 npm run build 
 cdk synth
```

------
#### [ Python ]

```
 cdk synth           
```

------

 Vous devriez voir une pile comme suit, où`CDK-VERSION`est la version du CDK. (Votre sortie peut différer légèrement de ce qui est montré ici.) 

------
#### [ TypeScript ]

```
Resources:
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
          Modules: aws-cdk=CDK-VERSION,@aws-cdk/core=VERSION_NUMBER,@aws-cdk/cx-api=VERSION_NUMBER,jsii-runtime=node.js/10.17.0
```

------
#### [ Python ]

```
Resources:
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
          Modules: aws-cdk=CDK-VERSION,@aws-cdk/core=VERSION_NUMBER,@aws-cdk/cx-api=VERSION_NUMBER,jsii-runtime=Python/3.7.7
```

------

## Code de gestionnaire Lambda
<a name="lambda-handler-code"></a>

 Nous commencerons par le code du gestionnaire AWS Lambda. 

 Créer un annuaire`lambda`à la racine de votre arbre de projet. 

------
#### [ TypeScript ]

Ajouter un fichier, appelé`lambda/hello.js`avec les éléments suivants : 

```
exports.handler = async function(event) {
  console.log("request:", JSON.stringify(event, null, 2));
  return {
    statusCode: 200,
    headers: { "Content-Type": "text/plain" },
    body: `Hello, AWS Solutions Constructs! You've hit ${event.path}\n`
  };
};
```

------
#### [ Python ]

Ajouter un fichier, appelé`lambda/hello.py`avec les éléments suivants :

```
import json

def handler(event, context):
    print('request: {}'.format(json.dumps(event)))
    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'text/plain'
        },
        'body': 'Hello, CDK! You have hit {}\n'.format(event['path'])
    }
```

------

 Ceci est une simple fonction Lambda qui renvoie le texte « Bonjour, Constructs \! Vous avez frappé [url path] ». La sortie de la fonction inclut également le code d'état HTTP et les en-têtes HTTP. Ceux-ci sont utilisés par API Gateway pour formuler la réponse HTTP à l'utilisateur. 

 Ce Lambda est fourni en JavaScript. Pour plus d'informations sur l'écriture des fonctions Lambda dans la langue de votre choix, reportez-vous à la[Documentation AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html).

## Installer les dépendances AWS CDK et AWS Solutions Construit
<a name="install-the-aws-cdk-and-aws-solutions-constructs-library-dependencies"></a>

 Les constructions AWS Solutions sont livrées avec une vaste bibliothèque de constructions. La bibliothèque est divisée en modules, un pour chaque modèle bien conçu. Par exemple, si vous souhaitez définir une API Amazon API Gateway Rest vers une fonction AWS Lambda, nous devrons utiliser la méthode`aws-apigateway-lambda`Bibliothèque de modèles. 

 Nous devons également ajouter la bibliothèque de construction AWS Lambda et Amazon API Gateway à partir du CDK AWS. 

 Installez le module AWS Lambda et toutes ses dépendances dans notre projet : 

**Note**  
N'oubliez pas de remplacer la version correcte et correspondante à utiliser à la fois pour les constructions AWS Solutions et pour le CDK AWS dans le répertoire`VERSION_NUMBER`pour chaque commande. L'inadéquation des versions entre les packages peut entraîner des erreurs.

------
#### [ TypeScript ]

```
 npm install -s @aws-cdk/aws-lambda@VERSION_NUMBER       
```

------
#### [ Python ]

```
 pip install aws_cdk.aws_lambda==VERSION_NUMBER 
```

------

 Ensuite, installez le module Amazon API Gateway et toutes ses dépendances dans notre projet : 

------
#### [ TypeScript ]

```
 npm install -s @aws-cdk/aws-apigateway@VERSION_NUMBER         
```

------
#### [ Python ]

```
 pip install aws_cdk.aws_apigateway==VERSION_NUMBER          
```

------

 Enfin, installez les constructions AWS Solutions`aws-apigateway-lambda`et toutes ses dépendances dans notre projet : 

------
#### [ TypeScript ]

```
 npm install -s @aws-solutions-constructs/aws-apigateway-lambda@VERSION_NUMBER        
```

------
#### [ Python ]

```
 pip install aws_solutions_constructs.aws_apigateway_lambda==VERSION_NUMBER          
```

------

## Ajouter un modèle Amazon API Gateway/AWS Lambda à votre pile
<a name="add-an-aws-api-gatewayaws-lambda-pattern-to-your-stack"></a>

 Désormais, définissons le modèle AWS Solutions Constructs pour implémenter un Amazon API Gateway avec un proxy AWS Lambda. 

------
#### [ TypeScript ]

Modification du fichier`lib/hello-constructs.ts`avec les éléments suivants :

```
import * as cdk from '@aws-cdk/core';
import * as lambda from '@aws-cdk/aws-lambda';
import * as api from '@aws-cdk/aws-apigateway';
import { ApiGatewayToLambda, ApiGatewayToLambdaProps } from '@aws-solutions-constructs/aws-apigateway-lambda';

export class HelloConstructsStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // The code that defines your stack goes here
    const api_lambda_props: ApiGatewayToLambdaProps = {
      lambdaFunctionProps: {
        code: lambda.Code.fromAsset('lambda'),
        runtime: lambda.Runtime.NODEJS_12_X,
        handler: 'hello.handler'
      },
      apiGatewayProps: {
        defaultMethodOptions: {
          authorizationType: api.AuthorizationType.NONE
        }
      }
    };

    new ApiGatewayToLambda(this, 'ApiGatewayToLambda', api_lambda_props);
  }
}
```

------
#### [ Python ]

Modification du fichier`hello_constructs/hello_constructs_stack.py`avec les éléments suivants : 

```
from aws_cdk import (
    aws_lambda as _lambda,
    aws_apigateway as apigw,
    core,
)

from aws_solutions_constructs import (
    aws_apigateway_lambda as apigw_lambda
)

class HelloConstructsStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # The code that defines your stack goes here

        apigw_lambda.ApiGatewayToLambda(
            self, 'ApiGatewayToLambda',
            lambda_function_props=_lambda.FunctionProps(
                runtime=_lambda.Runtime.PYTHON_3_7,
                code=_lambda.Code.asset('lambda'),
                handler='hello.handler',
            ),
            api_gateway_props=apigw.RestApiProps(
                default_method_options=apigw.MethodOptions(
                    authorization_type=apigw.AuthorizationType.NONE
                )
            )
        )
```

------

 C'est ça. C'est tout ce que vous devez faire pour définir une API Gateway qui envoie toutes les requêtes à une fonction AWS Lambda. Comparons notre nouvelle pile à celle d'origine : 

------
#### [ TypeScript ]

```
npm run build    
cdk diff
```

------
#### [ Python ]

```
cdk diff       
```

------

 La sortie doit se présenter comme suit : 

```
Stack HelloConstructsStack
IAM Statement Changes
┌───┬─────────────────────────────┬────────┬─────────────────────────────┬─────────────────────────────┬──────────────────────────────┐
│   │ Resource                    │ Effect │ Action                      │ Principal                   │ Condition                    │
├───┼─────────────────────────────┼────────┼─────────────────────────────┼─────────────────────────────┼──────────────────────────────┤
│ + │ ${LambdaFunction.Arn}       │ Allow  │ lambda:InvokeFunction       │ Service:apigateway.amazonaw │ "ArnLike": {                 │
│   │                             │        │                             │ s.com                       │   "AWS:SourceArn": "arn:${AW │
│   │                             │        │                             │                             │ S::Partition}:execute-api:${ │
│   │                             │        │                             │                             │ AWS::Region}:${AWS::AccountI │
│   │                             │        │                             │                             │ d}:${RestApi0C43BF4B}/${Rest │
│   │                             │        │                             │                             │ Api/DeploymentStage.prod}/*/ │
│   │                             │        │                             │                             │ {proxy+}"                    │
│   │                             │        │                             │                             │ }                            │
│ + │ ${LambdaFunction.Arn}       │ Allow  │ lambda:InvokeFunction       │ Service:apigateway.amazonaw │ "ArnLike": {                 │
│   │                             │        │                             │ s.com                       │   "AWS:SourceArn": "arn:${AW │
│   │                             │        │                             │                             │ S::Partition}:execute-api:${ │
│   │                             │        │                             │                             │ AWS::Region}:${AWS::AccountI │
│   │                             │        │                             │                             │ d}:${RestApi0C43BF4B}/test-i │
│   │                             │        │                             │                             │ nvoke-stage/*/{proxy+}"      │
│   │                             │        │                             │                             │ }                            │
│ + │ ${LambdaFunction.Arn}       │ Allow  │ lambda:InvokeFunction       │ Service:apigateway.amazonaw │ "ArnLike": {                 │
│   │                             │        │                             │ s.com                       │   "AWS:SourceArn": "arn:${AW │
│   │                             │        │                             │                             │ S::Partition}:execute-api:${ │
│   │                             │        │                             │                             │ AWS::Region}:${AWS::AccountI │
│   │                             │        │                             │                             │ d}:${RestApi0C43BF4B}/${Rest │
│   │                             │        │                             │                             │ Api/DeploymentStage.prod}/*/ │
│   │                             │        │                             │                             │ "                            │
│   │                             │        │                             │                             │ }                            │
│ + │ ${LambdaFunction.Arn}       │ Allow  │ lambda:InvokeFunction       │ Service:apigateway.amazonaw │ "ArnLike": {                 │
│   │                             │        │                             │ s.com                       │   "AWS:SourceArn": "arn:${AW │
│   │                             │        │                             │                             │ S::Partition}:execute-api:${ │
│   │                             │        │                             │                             │ AWS::Region}:${AWS::AccountI │
│   │                             │        │                             │                             │ d}:${RestApi0C43BF4B}/test-i │
│   │                             │        │                             │                             │ nvoke-stage/*/"              │
│   │                             │        │                             │                             │ }                            │
├───┼─────────────────────────────┼────────┼─────────────────────────────┼─────────────────────────────┼──────────────────────────────┤
│ + │ ${LambdaFunctionServiceRole │ Allow  │ sts:AssumeRole              │ Service:lambda.amazonaws.co │                              │
│   │ .Arn}                       │        │                             │ m                           │                              │
├───┼─────────────────────────────┼────────┼─────────────────────────────┼─────────────────────────────┼──────────────────────────────┤
│ + │ ${LambdaRestApiCloudWatchRo │ Allow  │ sts:AssumeRole              │ Service:apigateway.amazonaw │                              │
│   │ le.Arn}                     │        │                             │ s.com                       │                              │
├───┼─────────────────────────────┼────────┼─────────────────────────────┼─────────────────────────────┼──────────────────────────────┤
│ + │ arn:aws:logs:${AWS::Region} │ Allow  │ logs:CreateLogGroup         │ AWS:${LambdaRestApiCloudWat │                              │
│   │ :${AWS::AccountId}:*        │        │ logs:CreateLogStream        │ chRole}                     │                              │
│   │                             │        │ logs:DescribeLogGroups      │                             │                              │
│   │                             │        │ logs:DescribeLogStreams     │                             │                              │
│   │                             │        │ logs:FilterLogEvents        │                             │                              │
│   │                             │        │ logs:GetLogEvents           │                             │                              │
│   │                             │        │ logs:PutLogEvents           │                             │                              │
├───┼─────────────────────────────┼────────┼─────────────────────────────┼─────────────────────────────┼──────────────────────────────┤
│ + │ arn:aws:logs:${AWS::Region} │ Allow  │ logs:CreateLogGroup         │ AWS:${LambdaFunctionService │                              │
│   │ :${AWS::AccountId}:log-grou │        │ logs:CreateLogStream        │ Role}                       │                              │
│   │ p:/aws/lambda/*             │        │ logs:PutLogEvents           │                             │                              │
└───┴─────────────────────────────┴────────┴─────────────────────────────┴─────────────────────────────┴──────────────────────────────┘
(NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299)

Parameters
[+] Parameter AssetParameters/ba91444ebd644d9419e8cfee417f3aaa728507dd428788a2fc40574646c4340a/S3Bucket AssetParametersba91444ebd644d9419e8cfee417f3aaa728507dd428788a2fc40574646c4340aS3Bucket9780A3BC: {"Type":"String","Description":"S3 bucket for asset \"ba91444ebd644d9419e8cfee417f3aaa728507dd428788a2fc40574646c4340a\""}
[+] Parameter AssetParameters/ba91444ebd644d9419e8cfee417f3aaa728507dd428788a2fc40574646c4340a/S3VersionKey AssetParametersba91444ebd644d9419e8cfee417f3aaa728507dd428788a2fc40574646c4340aS3VersionKey37F36FFB: {"Type":"String","Description":"S3 key for asset version \"ba91444ebd644d9419e8cfee417f3aaa728507dd428788a2fc40574646c4340a\""}
[+] Parameter AssetParameters/ba91444ebd644d9419e8cfee417f3aaa728507dd428788a2fc40574646c4340a/ArtifactHash AssetParametersba91444ebd644d9419e8cfee417f3aaa728507dd428788a2fc40574646c4340aArtifactHash80199FBC: {"Type":"String","Description":"Artifact hash for asset \"ba91444ebd644d9419e8cfee417f3aaa728507dd428788a2fc40574646c4340a\""}

Conditions
[+] Condition CDKMetadataAvailable: {"Fn::Or":[{"Fn::Or":[{"Fn::Equals":[{"Ref":"AWS::Region"},"ap-east-1"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"ap-northeast-1"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"ap-northeast-2"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"ap-south-1"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"ap-southeast-1"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"ap-southeast-2"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"ca-central-1"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"cn-north-1"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"cn-northwest-1"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"eu-central-1"]}]},{"Fn::Or":[{"Fn::Equals":[{"Ref":"AWS::Region"},"eu-north-1"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"eu-west-1"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"eu-west-2"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"eu-west-3"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"me-south-1"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"sa-east-1"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"us-east-1"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"us-east-2"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"us-west-1"]},{"Fn::Equals":[{"Ref":"AWS::Region"},"us-west-2"]}]}]}

Resources
[+] AWS::Logs::LogGroup ApiGatewayToLambda/ApiAccessLogGroup ApiGatewayToLambdaApiAccessLogGroupE2B41502 
[+] AWS::IAM::Role LambdaFunctionServiceRole LambdaFunctionServiceRole0C4CDE0B 
[+] AWS::Lambda::Function LambdaFunction LambdaFunctionBF21E41F 
[+] AWS::ApiGateway::RestApi RestApi RestApi0C43BF4B 
[+] AWS::ApiGateway::Deployment RestApi/Deployment RestApiDeployment180EC503d2c6df3c8dc8b7193b98c1a0bff4e677 
[+] AWS::ApiGateway::Stage RestApi/DeploymentStage.prod RestApiDeploymentStageprod3855DE66 
[+] AWS::ApiGateway::Resource RestApi/Default/{proxy+} RestApiproxyC95856DD 
[+] AWS::Lambda::Permission RestApi/Default/{proxy+}/ANY/ApiPermission.HelloConstructsStackRestApiFDB18C2E.ANY..{proxy+} RestApiproxyANYApiPermissionHelloConstructsStackRestApiFDB18C2EANYproxyE43D39B3 
[+] AWS::Lambda::Permission RestApi/Default/{proxy+}/ANY/ApiPermission.Test.HelloConstructsStackRestApiFDB18C2E.ANY..{proxy+} RestApiproxyANYApiPermissionTestHelloConstructsStackRestApiFDB18C2EANYproxy0B23CDC7 
[+] AWS::ApiGateway::Method RestApi/Default/{proxy+}/ANY RestApiproxyANY1786B242 
[+] AWS::Lambda::Permission RestApi/Default/ANY/ApiPermission.HelloConstructsStackRestApiFDB18C2E.ANY.. RestApiANYApiPermissionHelloConstructsStackRestApiFDB18C2EANY5684C1E6 
[+] AWS::Lambda::Permission RestApi/Default/ANY/ApiPermission.Test.HelloConstructsStackRestApiFDB18C2E.ANY.. RestApiANYApiPermissionTestHelloConstructsStackRestApiFDB18C2EANY81DBDF56 
[+] AWS::ApiGateway::Method RestApi/Default/ANY RestApiANYA7C1DC94 
[+] AWS::ApiGateway::UsagePlan RestApi/UsagePlan RestApiUsagePlan6E1C537A 
[+] AWS::Logs::LogGroup ApiAccessLogGroup ApiAccessLogGroupCEA70788 
[+] AWS::IAM::Role LambdaRestApiCloudWatchRole LambdaRestApiCloudWatchRoleF339D4E6 
[+] AWS::ApiGateway::Account LambdaRestApiAccount LambdaRestApiAccount 

Outputs
[+] Output RestApi/Endpoint RestApiEndpoint0551178A: {"Value":{"Fn::Join":["",["https://",{"Ref":"RestApi0C43BF4B"},".execute-api.",{"Ref":"AWS::Region"},".",{"Ref":"AWS::URLSuffix"},"/",{"Ref":"RestApiDeploymentStageprod3855DE66"},"/"]]}}
```

 C'est sympa. Cet exemple simple avec un modèle bien conçu issu des constructions AWS Solutions a ajouté 21 nouvelles ressources à votre pile. 

## Déploiement sur cdk
<a name="cdk-deploy"></a>

**Astuce**  
Avant de pouvoir déployer votre première application AWS CDK contenant une fonction Lambda, vous devez amorcer votre environnement AWS. Cela crée un compartiment intermédiaire que le CDK AWS utilise pour déployer des piles contenant des ressources. Si c'est la première fois que vous utilisez le CDK AWS pour déployer des ressources, vous devrez exécuter le`cdk bootstrap`pour déployer la pile CDK Toolkit dans votre environnement AWS. 

 Ok, prêt à effectuer le déploiement ? 

```
cdk deploy
```

## Sortie de pile
<a name="stack-outputs"></a>

 Lorsque le déploiement est terminé, vous remarquerez cette ligne : 

```
Outputs:
HelloConstructsStack.RestApiEndpoint0551178A = https://{{xxxxxxxxxx}}.execute-api.us-east-1.amazonaws.com/prod/
```

 Il s'agit d'une sortie de pile qui est automatiquement ajoutée par le modèle AWS Solutions Constructs et inclut l'URL du point de terminaison API Gateway. 

## Tester votre application
<a name="testing-your-app"></a>

 Essayons de frapper ce point de terminaison avec`curl`. Copiez l'URL et exécutez (votre préfixe et votre région seront probablement différents). 

```
curl https://{{xxxxxxxxxx}}.execute-api.us-east-1.amazonaws.com/prod/
```

 Sortie doit se présenter comme suit : 

```
Hello, AWS Solutions Constructs! You've hit /
```

 Si c'est la sortie que vous avez reçue, votre application fonctionne \! 