Tutorial / Cram Notes

Infrastructure as Code (IaC) is a transformative method that allows developers and operations teams to automatically manage, provision, and deploy infrastructure through code, rather than through manual processes. It’s a key practice in DevOps and is pivotal for cloud-centric deployments. AWS offers several tools to facilitate IaC, including AWS Serverless Application Model (AWS SAM), AWS CloudFormation, and AWS Cloud Development Kit (AWS CDK). Each of these tools serves specific use cases and provides unique features while maintaining the core benefits of IaC such as consistency, speed, and scalability.

AWS Serverless Application Model (AWS SAM)

AWS SAM is an open-source framework designed specifically for building serverless applications on AWS. It extends AWS CloudFormation and provides a simplified syntax for expressing serverless resources. With SAM, you can define functions, APIs, databases, and event source mappings.

SAM Template Example

An AWS SAM template for a simple Lambda function triggered by an API Gateway event might look like this:

AWSTemplateFormatVersion: ‘2010-09-09’
Transform: ‘AWS::Serverless-2016-10-31’
Resources:
MyFunction:
Type: ‘AWS::Serverless::Function’
Properties:
Handler: index.handler
Runtime: nodejs12.x
Events:
MyApi:
Type: Api
Properties:
Path: /myresource
Method: get

Deploying a SAM Template

Deployment of an AWS SAM application typically involves the following steps:

  1. Write your SAM template.
  2. Build your application with sam build.
  3. Package your application with sam package.
  4. Deploy your application to AWS with sam deploy.

AWS CloudFormation

AWS CloudFormation is an AWS service that allows you to model your entire AWS infrastructure in a text file. It automates the provisioning of AWS resources through this template file which describes all the AWS resources (ec2 instances, Elastic Load Balancers, RDS databases) you need.

CloudFormation Template Example

A simple AWS CloudFormation snippet to create an S3 bucket might look like this:

Resources:
MyS3Bucket:
Type: ‘AWS::S3::Bucket’
Properties:
BucketName: my-unique-bucket-name

Deploying a CloudFormation Template

Deployment is straightforward:

  1. Write the CloudFormation YAML or JSON template.
  2. Use the AWS Management Console, AWS CLI, or AWS APIs to create a stack based on your template.
  3. AWS CloudFormation provisions and configures the resources as described.

AWS Cloud Development Kit (AWS CDK)

The AWS Cloud Development Kit (AWS CDK) is a software development framework for defining infrastructure as code and provisioning it through AWS CloudFormation. It allows you to use familiar programming languages such as TypeScript, Python, Java, and C# to define your cloud resources.

CDK Example

Using AWS CDK in TypeScript to create an S3 bucket might look like this:

import * as cdk from ‘@aws-cdk/core’;
import * as s3 from ‘@aws-cdk/aws-s3’;

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

new s3.Bucket(this, ‘MyUniqueBucket’, {
bucketName: ‘my-unique-bucket-name’,
removalPolicy: cdk.RemovalPolicy.DESTROY, // NOT recommended for production code
});
}
}

Deploying a CDK Stack

For AWS CDK, deployment involves:

  1. Writing your infrastructure using a supported programming language.
  2. Compiling your code to generate AWS CloudFormation Templates (if necessary).
  3. Use cdk deploy to deploy your stack.

Comparison

When comparing AWS SAM, CloudFormation, and AWS CDK consider the following aspects:

Feature AWS SAM AWS CloudFormation AWS CDK
Abstraction Level High (Serverless focused) Low (Direct AWS resource focus) High (Programmatic abstraction)
Language YAML/JSON YAML/JSON TypeScript, Python, Java, C#, etc.
Resource Coverage Serverless resources All AWS Resources All AWS Resources
Deployment Through CloudFormation Direct Through CloudFormation

Best Practices

Regardless of the IaC tool chosen, certain best practices should be adhered to:

  • Store IaC templates in source control.
  • Implement code reviews for all template changes.
  • Integrate IaC deployments with CI/CD pipelines.
  • Periodically review and refactor templates for maintainability.
  • Use parameters, mappings, variables, and environment-specific files to manage different environments and configurations.

Understanding and utilizing these AWS IaC templates is crucial for the AWS Certified DevOps Engineer – Professional (DOP-C02) exam. Candidates should be familiar with writing, deploying, and managing these templates effectively as part of their DevOps practices.

Practice Test with Explanation

True or False: AWS CloudFormation can be used to provision AWS resources in a repeatable and predictable manner.

  • (A) True
  • (B) False

Answer: A

Explanation: AWS CloudFormation allows you to model your entire infrastructure in a text file or templates. This enables you to provision and manage a collection of resources predictably and repeatedly.

The AWS Serverless Application Model (AWS SAM) is an extension of which AWS service?

  • (A) AWS Lambda
  • (B) Amazon EC2
  • (C) AWS CloudFormation
  • (D) AWS Elastic Beanstalk

Answer: C

Explanation: AWS SAM is an extension of AWS CloudFormation that provides a simplified way of defining the Amazon API Gateway APIs, AWS Lambda functions, and Amazon DynamoDB tables needed by your serverless application.

Which of the following is NOT a component of AWS CloudFormation?

  • (A) Template
  • (B) Stack
  • (C) Change set
  • (D) Pipeline

Answer: D

Explanation: Pipeline is not a direct component of AWS CloudFormation. AWS CloudFormation uses templates, stacks, and change sets to manage infrastructure, while pipelines are related to continuous integration and delivery processes.

How is AWS CDK different from AWS CloudFormation?

  • (A) AWS CDK uses programming languages to define infrastructure, while CloudFormation uses JSON or YAML.
  • (B) AWS CDK is only for serverless applications, whereas CloudFormation is for all types of applications.
  • (C) AWS CDK can only be used with AWS Lambda, but CloudFormation is more versatile.
  • (D) AWS CDK does not support rollback of changes, unlike CloudFormation.

Answer: A

Explanation: AWS CDK allows you to define your cloud resources using familiar programming languages such as TypeScript, Python, Java, and C#. AWS CloudFormation, on the other hand, uses YAML or JSON templates for infrastructure definition.

True or False: AWS CloudDevelopment Kit (AWS CDK) apps can only be written in one programming language.

  • (A) True
  • (B) False

Answer: B

Explanation: AWS CDK supports multiple programming languages such as TypeScript, Python, Java, and C#, allowing developers to use a language they are comfortable with.

With AWS SAM, what command deploys your application after you have packaged it?

  • (A) aws sam build
  • (B) aws sam deploy
  • (C) aws sam package
  • (D) aws sam release

Answer: B

Explanation: The `aws sam deploy` command is used to deploy your application after you have packaged it using `aws sam package`.

What is the primary file used to define a serverless application with AWS SAM?

  • (A) serverless.yml
  • (B) template.yaml
  • (C) app.json
  • (D) samconfig.toml

Answer: B

Explanation: The `template.yaml` is the primary file used in AWS SAM to define the serverless application’s resources.

Which AWS service can be used to manage incremental updates and changes to AWS CloudFormation stacks?

  • (A) AWS CodeCommit
  • (B) AWS Config
  • (C) AWS CloudTrail
  • (D) AWS CloudFormation Change Sets

Answer: D

Explanation: AWS CloudFormation Change Sets allow you to preview how proposed changes to a stack might impact your running resources before you implement them.

What is an AWS CDK Construct?

  • (A) A command to initialize a new CDK project
  • (B) The foundational building block of AWS CDK applications
  • (C) An AWS service that the CDK does not yet support
  • (D) A special kind of CloudFormation template

Answer: B

Explanation: An AWS CDK Construct is the basic building block of AWS CDK applications which represents a “cloud component” and encapsulates everything AWS CloudFormation needs to create the component.

True or False: Every AWS SAM template must contain an “AWSTemplateFormatVersion” and “Transform” section.

  • (A) True
  • (B) False

Answer: A

Explanation: Every AWS SAM template is an extension of AWS CloudFormation and requires an “AWSTemplateFormatVersion” section, and to indicate that the template is an AWS SAM template, it must also contain a “Transform” section, specifying “AWS::Serverless-2016-10-31”.

What AWS service provides a git-based repository for storing and versioning your CloudFormation templates?

  • (A) AWS CloudFormation
  • (B) AWS CodeBuild
  • (C) AWS CodePipeline
  • (D) AWS CodeCommit

Answer: D

Explanation: AWS CodeCommit is a source control service that hosts git-based repositories and can be used for storing, sharing, and versioning CloudFormation templates, among other code files.

Can AWS CDK apps be integrated with AWS CloudFormation custom resources?

  • (A) Yes, but it requires manual configuration outside of the CDK app
  • (B) No, AWS CDK apps are completely independent of CloudFormation
  • (C) Yes, AWS CDK apps can be integrated with CloudFormation custom resources
  • (D) No, AWS CDK apps can only use resources available in the AWS Construct Library

Answer: C

Explanation: AWS CDK apps can utilize AWS CloudFormation custom resources, allowing for more complex and flexible infrastructure setups that may require resources not covered by the AWS Construct Library.

Interview Questions

What is Infrastructure as Code (IaC), and why is it important in AWS cloud environments?

Infrastructure as Code (IAC) is a method of provisioning and managing computing resources through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools. It’s important in AWS cloud environments because it enables consistent and predictable deployments, version control of infrastructure, and the ability to scale and replicate environments quickly and with less error.

Can you explain the difference between AWS CloudFormation and AWS CDK?

AWS CloudFormation is a service that provides a common language for describing and provisioning all the infrastructure resources in AWS environments. It allows you to use JSON or YAML templates to model and provision AWS resources. AWS CDK, on the other hand, is a software development framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation. It allows developers to define cloud resources using familiar programming languages like TypeScript, Python, Java, or C#.

What are some advantages of using the AWS Serverless Application Model (AWS SAM) over direct use of AWS CloudFormation for serverless deployments?

AWS SAM is an extension of AWS CloudFormation specifically designed for serverless applications. It provides shorthand syntax to express serverless resources, which makes it easier to read, write, and maintain serverless applications. SAM also includes a command line interface (CLI) that offers additional functionality for building, testing, and deploying serverless applications.

How can you ensure your AWS CloudFormation templates adhere to best security practices?

To ensure AWS CloudFormation templates follow best security practices, one should:

  • Use IAM roles with the principle of least privilege for CloudFormation and the created resources.
  • Reference SecureString parameters from AWS Systems Manager Parameter Store to manage secrets.
  • Incorporate AWS resource policies to restrict access as needed.
  • Include encryption settings on resources that support encryption in the template.
  • Use template linting tools, such as cfn-lint and cfn-nag, to identify potential security issues in the templates.

What mechanisms can you use to update a stack safely in AWS CloudFormation without causing downtime or data loss?

To update a stack safely in AWS CloudFormation without causing downtime or data loss, you can use:

  • Stack policies to prevent unintentional updates to critical resources.
  • UpdateRollback policy to automatically roll back changes on failure.
  • Change sets to preview proposed changes before applying them.
  • Deletion policies on resources to preserve or create snapshots of stateful services like databases during updates.

How would you incorporate manual approval steps in an AWS CodePipeline that involves deployment of AWS CloudFormation templates?

To incorporate manual approval steps in AWS CodePipeline, you should use the Approval action type. You can add this approval action to the pipeline stage where you want the manual intervention to occur. This will pause the pipeline execution until someone with the right permissions approves or rejects the action.

Explain the concept of Nested Stacks in AWS CloudFormation. When would you use them?

Nested Stacks in AWS CloudFormation are stacks created as part of other stacks. They allow you to isolate repeated patterns or components of your architecture into separate templates and reuse them. Nested Stacks are useful to organize your architecture into logical parts and manage them separately, which is particularly helpful when dealing with large infrastructures or when you want to share and reuse certain components across different projects.

What are AWS CloudFormation Custom Resources and when should you use them?

AWS CloudFormation Custom Resources are placeholders that invoke AWS Lambda functions to manage resource creation, update, and deletion operations. You should use them when you need to provision resources that are not natively supported by AWS CloudFormation or to add functionality to your stack that requires custom logic during the stack operation.

Describe how you would automate the deployment of infrastructure across multiple AWS accounts or regions using AWS CloudFormation.

To automate deployment across multiple AWS accounts or regions, you could:

  • Use AWS Organizations along with Service Control Policies (SCPs) to manage permissions across accounts.
  • Employ AWS CloudFormation StackSets, which allows you to create, update, or delete stacks across multiple accounts and regions with a single operation.
  • Utilize a CI/CD pipeline with cross-account roles and triggers to execute CloudFormation templates in different accounts and regions.

Explain how you could roll back a failed deployment in AWS CloudFormation.

When a deployment fails in AWS CloudFormation, it automatically rolls back to the previous stable state if rollback configuration is not disabled. This rollback undoes any changes made during the stack update. To manually roll back a change, you can either execute a new update with a previous version of the template or use the AWS CloudFormation console or AWS CLI to continue rollback to a prior working state.

What is drift detection in AWS CloudFormation, and how is it used?

Drift detection in AWS CloudFormation is a feature that identifies configuration changes that have been made to stack resources outside of CloudFormation. This allows you to compare the expected configuration of your stack’s resources as defined in CloudFormation templates with the current configuration of those resources in the AWS environment. Drift detection is used to maintain consistency and ensure that infrastructure is as code describes it.

How do you manage secrets when using AWS CloudFormation or AWS CDK to ensure they aren’t exposed in your templates?

To manage secrets without exposing them in AWS CloudFormation or AWS CDK templates, you can use AWS Secrets Manager or the AWS Systems Manager Parameter Store to reference secrets. Secrets are stored securely, and the templates only reference those secrets by their identifiers, not including the secret values within the template itself. Access to the secrets can be controlled through IAM policies and roles, ensuring that only authorized components or users can retrieve the actual secret values.

0 0 votes
Article Rating
Subscribe
Notify of
guest
25 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Melike Dağdaş
7 months ago

This blog post on IaC templates for AWS was incredibly insightful. I finally understand the nuances between AWS SAM, CloudFormation, and CDK.

Aron Fogaça
8 months ago

Could anyone explain the main differences between using AWS CDK and AWS CloudFormation?

Ievfimiya Davidchenko
8 months ago

Found this post incredibly helpful for my exam prep. Thanks!

Kripa Nand
7 months ago

I still find CloudFormation templates a bit verbose. Is there a way to simplify them?

Anika Fries
8 months ago

Anyone using AWS SAM for serverless applications? How has your experience been?

Miriam Santiago
8 months ago

This article is a gem for anyone preparing for the AWS Certified DevOps Engineer exam. Much appreciated.

Adam White
7 months ago

I wish there were more examples of real-world deployments using these templates.

Deniz Baturalp
7 months ago

A bit off-topic, but has anyone faced challenges with AWS CDK in CI/CD pipelines?

25
0
Would love your thoughts, please comment.x
()
x