AWS tips
Cloudformation
template
AWS Example (snippets)
This section provides a number of example scenarios that you can use to understand how to declare various AWS CloudFormation template parts. You can also use the snippets as a starting point for sections of your custom templates.TopicsGeneral template snippetsAuto scaling template snippetsAWS Billing Console template snippetsAWS CloudFormation template snippetsAmazon CloudFront template snippetsAmazon CloudWatch template snippetsAmazon CloudWatch Logs template snippetsAmazon DynamoDB template snippetsAmazon EC2 CloudFormation template snippetsAmazon Elastic Container Service template snippetsAmazon Elastic File System Sample TemplateElastic Beanstalk template snippetsElastic Load Balancing template snippetsAWS Identity and Access Management template snippetsAWS Lambda templateAWS OpsWorks template snippetsAmazon Redshift template snippetsAmazon RDS template snippetsRoute 53 template snippetsAmazon S3 template snippetsAmazon SNS template snippetsAmazon SQS template snippets
aTemplate Formats
skeletonhttps://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/format-version-structure.htmlhttps://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-description-structure.html
aMetadata
AWS::CloudFormation::Interface is a metadata key that defines how parameters are grouped and sorted in the AWS CloudFormation console. When you create or update stacks in the console, the console lists input parameters in alphabetical order by their logical IDs. By using this key, you can define your own parameter grouping and ordering so that users can efficiently specify parameter values. For example, you could group all EC2-related parameters in one group and all VPC-related parameters in another group.https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudformation-interface.html####### Metadata #########Metadata: AWS::CloudFormation::Interface: ParameterGroups: - Label: default: "KMS Key Information" Parameters: - KMSDescription - Label: default: "Project Information" Parameters: - S3BucketIdentifier - ProjectCode - ProjectName - EnvironmentConditions: HasBackendBucket: !Equals [!Ref BackendBucket, 'enable']
Parameters
Use the optional Parameters section to customize your templates. Parameters enable you to input custom values to your template each time you create or update a stack.https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html####### Parameters #########Parameters: KMSDescription: Description: The Description of the KMS Type: String Default: KMS symetric Key used for EBS, RDS and S3 encryption S3BucketIdentifier: Description: Lowercase Name to identify your bucket for infrasctructure code Type: String Default: infra ProjectCode: Description: Lower case Project Aspire Code Type: String ProjectName: Description: A Lowercase friendly name of the service (i.e OneSearch) Type: String Environment: Description: Solution Environment Type: String Default: prod AllowedValues: - dev - int - val - prod - prod2 BackendBucket: Description: To use a backend s3 bucket to store application file Type: String AllowedValues: - enable - disable Default: disable
Mappings
similaire au dico de python, ex:YAMLAWSTemplateFormatVersion: "2010-09-09" Mappings: RegionMap: us-east-1: HVM64: ami-0ff8a91507f77f867 HVMG2: ami-0a584ac55a7631c0c us-west-1: HVM64: ami-0bdb828fd58c52235 HVMG2: ami-066ee5fd4a9ef77f1 eu-west-1: HVM64: ami-047bb4163c506cd98 HVMG2: ami-0a7c483d527806435 ap-northeast-1: HVM64: ami-06cd52961ce9f0d85 HVMG2: ami-053cdd503598e4a9d ap-southeast-1: HVM64: ami-08569b978cc4dfa10 HVMG2: ami-0be9df32ae9f92309 Resources: myEC2Instance: Type: "AWS::EC2::Instance" Properties: ImageId: !FindInMap [RegionMap, !Ref "AWS::Region", HVM64] InstanceType: m1.small
Conditions
permet de définir une action à partir de critéres, ex:Conditions: CreateProdResources: !Equals - !Ref EnvType - prod... MountPoint: Type: 'AWS::EC2::VolumeAttachment' Condition: CreateProdResources Properties: InstanceId: !Ref EC2Instance VolumeId: !Ref NewVolume Device: /dev/sdh NewVolume: Type: 'AWS::EC2::Volume' Condition: CreateProdResources Properties: Size: 100 AvailabilityZone: !GetAtt - EC2Instance - AvailabilityZonefonctions possibles: Condition intrinsic functionsYou can use the following intrinsic functions to define conditions:Fn::AndFn::EqualsFn::ForEachFn::IfFn::NotFn::OrFor the syntax and information about each function, see Condition functions.
aTransform
optionnel et spécifique, permet d'utiliser des macros dans l'IaC:https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-macros.htmlpermet aussi d'appeler des macros définies par AWS : https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-reference.html
aRules
The optional Rules section validates a parameter or a combination of parameters passed to a template during a stack creation or stack update. To use template rules, explicitly declare Rules in your template followed by an assertion. Use the rules section to validate parameter values before creating or updating resources.Each template rule consists of two properties:Rule condition (optional) – determines when a rule takes effect.Assertions (required) – describes what values users can specify for a particular parameter.Rule-specific intrinsic functionsTo define a rule condition and assertions, use rule-specific intrinsic functions, which are functions that can only be used in the Rules section of a template. You can nest functions, but the final result of a rule condition or assertion must be either true or false.You can use the following rule-specific intrinsic functions to define rule conditions and assertions:Fn::AndFn::ContainsFn::EachMemberEqualsFn::EachMemberInFn::EqualsFn::IfFn::NotFn::OrFn::RefAllFn::ValueOfFn::ValueOfAllExamplesConditionally verify a parameter valueIn the following example, the two rules check the value of the InstanceType parameter. Depending on the value of the environment parameter (test or prod), the user must specify a1.medium or a1.large for the InstanceType parameter. The InstanceType and Environment parameters must be declared in the Parameters section of the same template.Rules: testInstanceType: RuleCondition: !Equals - !Ref Environment - test Assertions: - Assert: 'Fn::Contains': - - a1.medium - !Ref InstanceType AssertDescription: 'For a test environment, the instance type must be a1.medium' prodInstanceType: RuleCondition: !Equals - !Ref Environment - prod Assertions: - Assert: 'Fn::Contains': - - a1.large - !Ref InstanceType AssertDescription: 'For a production environment, the instance type must be a1.large'
aResources
The required Resources section declares the AWS resources that you want to include in the stack, such as an Amazon EC2 instance or an Amazon S3 bucket.Resources: # AWS Service Role for AutoScaling, required as a KMS policy principal (ASG needs KMS symmetric # key access to launch EBS-encrypted-based EC2s. # NOTE: contrary to the console, the custom suffix cannot be set to NULL in CloudFormation. AWSServiceRoleForASG: Type: AWS::IAM::ServiceLinkedRole Properties: AWSServiceName: autoscaling.amazonaws.com CustomSuffix: !Ref ProjectCode Description: Allows EC2 Auto Scaling to use or manage AWS services and resources on your behalf. # KMS key with root, lambda, cloud watch events and asg as principals KMSKey: Type: AWS::KMS::Key DeletionPolicy: Retain Properties: Description: !Ref KMSDescription EnableKeyRotation: true KeyPolicy: Version: "2012-10-17" Id: keypolicy Statement: - Sid: keyAdmin Effect: Allow Principal: AWS: Fn::Sub: arn:aws:iam::${AWS::AccountId}:root Action: - kms:* Resource: "*" - Sid: S3CryptDecrypt Effect: Allow Principal: Service: s3.amazonaws.com Action: - kms:Encrypt - kms:Decrypt - kms:ReEncrypt* - kms:GenerateDataKey* Resource: "*" - Sid: LambdaCryptDecrypt Effect: Allow Principal: Service: lambda.amazonaws.com Action: - kms:Encrypt - kms:Decrypt - kms:ReEncrypt* - kms:GenerateDataKey* - kms:DescribeKey Resource: "*" - Sid: EventsCryptDecrypt Effect: Allow Principal: Service: events.amazonaws.com Action: - kms:Encrypt - kms:Decrypt - kms:ReEncrypt* - kms:GenerateDataKey* - kms:DescribeKey Resource: "*" - Sid: ASGCryptDecrypt Effect: Allow Principal: AWS: Fn::Sub: - arn:aws:iam::${AWS::AccountId}:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling_${ProjectCode} - ProjectCode: !Ref ProjectCode Action: - kms:Encrypt - kms:Decrypt - kms:ReEncrypt* - kms:GenerateDataKey* - kms:DescribeKey Resource: "*" - Sid: ASG Allow attachment of persistent resources Effect: Allow Principal: AWS: Fn::Sub: - arn:aws:iam::${AWS::AccountId}:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling_${ProjectCode} - ProjectCode: !Ref ProjectCode Action: - kms:CreateGrant Resource: "*" Condition: Bool: kms:GrantIsForAWSResource : true Tags: - Key: "Origin" Value: !Sub Stack_${AWS::StackName} - Key: "<Cie>:billing" Value: !Ref ProjectCode - Key: "<Cie>:environment" Value: !Ref Environment - Key: "<Cie>:application_code" Value: !Ref ProjectCode - Key: "app:project" Value: !Ref ProjectName DependsOn: AWSServiceRoleForASG KMSAlias: Type: AWS::KMS::Alias Properties: AliasName: !Sub alias/kms-key-${ProjectCode}-${Environment}-${AWS::Region} TargetKeyId: Ref: KMSKey # bucket for ProjectCloudFormation files and sources CloudFormationBucket: Type: AWS::S3::Bucket Properties: AccessControl: Private PublicAccessBlockConfiguration: BlockPublicAcls: true BlockPublicPolicy: true IgnorePublicAcls: true RestrictPublicBuckets: true # SCO add -${AWS::Region} to the bucket name BucketName: !Join ["-", ["s3", !Ref ProjectCode, !Ref ProjectName, !Ref Environment, !Ref S3BucketIdentifier, !Ref 'AWS::Region']] BucketEncryption: ServerSideEncryptionConfiguration: - ServerSideEncryptionByDefault: #SSEAlgorithm: AES256 KMSMasterKeyID: !Ref KMSKey SSEAlgorithm: aws:kms Tags: - Key: "Origin" Value: !Sub Stack_${AWS::StackName} - Key: "<Cie>:billing" Value: !Ref ProjectCode - Key: "<Cie>:environment" Value: !Ref Environment - Key: "<Cie>:application_code" Value: !Ref ProjectCode - Key: "app:project" Value: !Ref ProjectName DeletionPolicy: Delete# bucket for Project application sources ApplicationBucket: Condition: HasBackendBucket Type: AWS::S3::Bucket Properties: AccessControl: Private PublicAccessBlockConfiguration: BlockPublicAcls: true BlockPublicPolicy: true IgnorePublicAcls: true RestrictPublicBuckets: true # SCO add -${AWS::Region} to the bucket name BucketName: !Join ["-", ["s3", !Ref ProjectCode, !Ref ProjectName, !Ref Environment, !Ref S3BucketIdentifier, 'application', !Ref 'AWS::Region']] BucketEncryption: ServerSideEncryptionConfiguration: - ServerSideEncryptionByDefault: #SSEAlgorithm: AES256 KMSMasterKeyID: !Ref KMSKey SSEAlgorithm: aws:kms Tags: - Key: "Origin" Value: !Sub Stack_${AWS::StackName} - Key: "<Cie>:billing" Value: !Ref ProjectCode - Key: "<Cie>:environment" Value: !Ref Environment - Key: "<Cie>:application_code" Value: !Ref ProjectCode - Key: "app:project" Value: !Ref ProjectName DeletionPolicy: Deletehttps://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html
Outputs
The optional Outputs section declares output values that you can import into other stacks (to create cross-stack references), return in response (to describe stack calls), or view on the AWS CloudFormation console. For example, you can output the S3 bucket name for a stack to make the bucket easier to find.####### Outputs #########Outputs: KMSArn: Value: !GetAtt KMSKey.Arn Description: the KMS Key Arn KMSId: Value: !Ref KMSKey Description: the KMS Key ID CloudFormationBucket: Value: !Ref CloudFormationBucket Description: the CloudFormationBucket source bucket ApplicationBucket: Condition: HasBackendBucket Value: !Ref ApplicationBucket Description: the Application backend source buckethttps://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html
aIntrinsic Fn
The term "Intrinsic Fn" refers to the intrinsic functions in AWS CloudFormation. Intrinsic functions are built-in functions that allow you to perform various operations within your CloudFormation templates. These functions are used to dynamically define values or conditionally control the resources being created. There are several intrinsic functions available in CloudFormation, such as `Fn::Ref`, `Fn::Sub`, `Fn::Join`, `Fn::If`, and `Fn::Not`. - `Fn::Ref` is used to get the value of the specified parameter or resource. - `Fn::Sub` is used to substitute variables within a string with their corresponding values. - `Fn::Join` is used to concatenate multiple values together. - `Fn::If` is used to conditionally create resources or specify values based on a condition. - `Fn::Not` is used to negate a condition. These intrinsic functions can be used to make your CloudFormation templates more dynamic and flexible by allowing you to reference and manipulate values based on different conditions or inputs.
aDependsOn
DependsOn"DependsOn":"CloudWatchTransformFunctionRole" This attribute is used to define that the creation of a specific resource follows another. I often use it if a certain resource requires an IAM role or CloudWatch LogGroup created beforehand and I need to ensure the order is followed. Otherwise, the CloudFormation template may fail with an error message that the ARN can not be referenced.
EC2
Type
AWS CLI
AWS CLI est une interface de ligne de commande qui permet aux utilisateurs d'interagir avec les services Amazon Web Services (AWS) via la ligne de commande au lieu d'utiliser l'interface utilisateur graphique. Avec AWS CLI, les utilisateurs peuvent gérer efficacement les ressources, configurer les services et automatiser les tâches dans AWS. Fournit des commandes pour accéder et gérer une large gamme de services AWS, tels que EC2, S3, RDS, Lambda, etc. Avec l'AWS CLI, les utilisateurs peuvent écrire des scripts et des commandes personnalisés pour automatiser des tâches répétitives ou complexes dans AWS.
aAmazon CloudWatch
Classes de log
Logs Insights
Détecter et déboguer à l'aide de Live Tail
Other actions
Surveillez les journaux des instances Amazon EC2 : vous pouvez utiliser les CloudWatch journaux pour surveiller les applications et les systèmes à l'aide des données des journaux. Par exemple, CloudWatch Logs peut suivre le nombre d'erreurs qui se produisent dans les journaux de vos applications et vous envoyer une notification chaque fois que le taux d'erreurs dépasse un seuil que vous spécifiez. CloudWatch Logs utilise les données de vos journaux à des fins de surveillance ; aucune modification de code n'est donc requise. Par exemple, vous pouvez surveiller les journaux des applications pour détecter des termes littéraux spécifiques (tels que NullReferenceException « ») ou compter le nombre d'occurrences d'un terme littéral à une position donnée dans les données des journaux (tels que les codes d'état « 404 » dans un journal d'accès Apache). Lorsque le terme que vous recherchez est trouvé, CloudWatch Logs rapporte les données selon une CloudWatch métrique que vous spécifiez. Les données des journaux sont chiffrées, pendant le transit et pendant le repos. Consultez Commencer à utiliser CloudWatch Logs pour démarrer.Surveiller les événements AWS CloudTrail enregistrés : vous pouvez créer des alarmes CloudWatch et recevoir des notifications concernant une activité d'API particulière telle qu'elle est capturée, CloudTrail et utiliser la notification pour résoudre les problèmes. Pour commencer, consultez la section Envoyer CloudTrail des événements aux CloudWatch journaux dans le guide de AWS CloudTrail l'utilisateur.Auditez et masquez les données sensibles : si vos journaux contiennent des données sensibles, vous pouvez les protéger grâce à des politiques de protection des données. Ces politiques vous permettent d'auditer et de masquer les données sensibles. Si vous activez la protection des données, les données sensibles correspondant aux identifiants de données que vous sélectionnez sont masquées par défaut. Pour plus d’informations, consultez Aider à protéger les données sensibles des journaux grâce au masquage.Conservation des journaux : par défaut, les journaux sont conservés indéfiniment et n'expirent jamais. Vous pouvez ajuster la stratégie de conservation pour chaque groupe de journaux. Elle peut être indéfinie ou comprise entre 10 ans et un jour.Archiver les données du journal : vous pouvez utiliser CloudWatch les journaux pour stocker les données de vos journaux dans un espace de stockage hautement durable. L'agent CloudWatch Logs permet d'envoyer rapidement des données de journal avec ou sans rotation depuis un hôte vers le service de journalisation. Vous pouvez ensuite accéder aux données brutes des journaux lorsque vous en avez besoin.Consigner les requêtes DNS de Route 53 : vous pouvez utiliser CloudWatch les journaux pour enregistrer les informations relatives aux requêtes DNS reçues par Route 53. Pour plus d'informations, consultez Consignation des requêtes DNS dans le Guide du développeur Amazon Route 53.
a