Module 10 - Challenge Lab_ Automating Infrastructure Deployment
Module 10 - Challenge Lab_ Automating Infrastructure Deployment
Deployment
Scenario
Up to this point, the café staff created their AWS resources and configured their applications manually—mostly by using the AWS
Management Console. This approach worked well as a way for the café to get started with a web presence quickly. However, they
find it challenging to replicate their deployments to new AWS Regions so that they can support new café locations in multiple
countries. They would also like to have separate development and production environments that reliably have matching
configurations.
In this challenge lab, you will take on the role of Sofía as you work to automate the café's deployments and replicate them to
another AWS Region.
When you start the lab, the following resources are already created for you in the AWS account:
Note that in this challenge lab, you will encounter a few tasks where step-by-step instructions are not provided. You must figure
out how to complete the tasks on your own.
Duration
This lab will require approximately 90 minutes to complete.
5. Navigate to the AWS Cloud9 service and open the integrated development environment (IDE) of the existing AWS Cloud9
instance.
6. In the AWS Cloud9 IDE, choose File > New File, then choose File > Save, and save the new file as: S3.yaml
AWSTemplateFormatVersion: "2010-09-09"
Description:
Resources:
S3Bucket:
Type: AWS::S3::Bucket
Tip: Make sure that you keep the correct number of spaces for each indentation level. The Resources: line should have no
indentation. The S3Bucket: line should be indented by 2 spaces. Finally, the Type: AWS::S3::Bucket line should be
indented by 4 spaces.
AWS CloudFormation supports the YAML Version 1.1 specification, with a few exceptions. For more information about YAML,
go to the YAML website.
9. Add a description (such as "cafe S3 template" ) on the Description: line. Before you start your description, be sure that you
have a space after the colon (:). After you enter the description, Save the changes to file.
In the guided lab earlier in this module, you used the AWS Management Console to create an AWS CloudFormation stack.
Here, you use the AWS CLI instead.
The first line of code that you ran returned the default AWS Region of the AWS CLI client that is installed on the AWS Cloud9
instance. You could modify the default AWS Region by running aws configure . However, for this lab, you should leave the
default Region.
The second line of code that you ran created a stack that used the template you defined. Because you did not specify the
Region in the command, the stack will be created in the default Region.
If the create-stack command ran successfully, you should see some output that is formatted in JavaScript Object Notation
(JSON). This output should indicate a StackId.
This diagram illustrates the actions you just completed.
11. In the AWS Management Console, navigate to the AWS CloudFormation service and observe the details of the CreateBucket
stack.
For example, look at the information in the Events, Resources, Outputs, and Template tabs.
12. Navigate to the Amazon S3 service page to observe the bucket that your template created.
Tip: The bucket has the bucket name createbucket-s3bucket-<random-string>.
14. In the page that you loaded, submit answers for each of the following questions:
Question 1: Was an S3 bucket created, even if you did not specify a name for the bucket? If so, what name was it given?
Question 2: What Region was the bucket created in, and why was it created in this Region?
Question 3: To define an S3 bucket, how many lines of code did you need to enter in the Resources: section of the
template file?
Note: Leave the browser tab with the questions in it open, so that you can return to it later in the lab.
15. Set bucket ownership controls and public access and then upload the static website assets to the bucket.
To do this task, run the following commands in the Bash terminal (replace all three occurences of <BUCKET-NAME> with your
actual bucket name):
16. In a new browser tab, open the AWS CloudFormation template documentation for defining S3 bucket resources.
Go to the AWS resource and property types reference documentation
Scroll down, choose Amazon S3, and then choose the AWS::S3::Bucket resource type.
17. Using the documentation as a reference, modify your S3.yaml template to set the following characteristics on the S3 bucket
resource:
Attach a deletion policy that will retain the bucket
Configure the bucket to host a static website with index.html set as the index document
Tip: You can accomplish this task by adding as few as four additional lines of code to your template. See the code in the
Examples section of the documentation page that you opened in the last step.
18. To your AWS CloudFormation template, add an output that provides the website URL.
Again, consult the Examples section of the documentation as a reference.
cd ../
aws cloudformation validate-template --template-body file://S3.yaml
If the output indicates that your template has syntax or other errors, correct them, and then run the command again to verify
that they have been resolved.
Tip: Proper YAML syntax is important. If you receive a ValidationError when you run update-stack , review your use of colons
and confirm that you indented each line appropriately. The example templates in the documentation provide a good
reference for well-structured YAML templates.
22. Browse to the AWS CloudFormation service and confirm that your stack update completed successfully.
The stack should soon show status UPDATE_COMPLETE.
If the stack does not attain a status of UPDATE_COMPLETE, try these troubleshooting tips.
If you see that the stack has a ROLLBACK status of some kind, go the Events tab and search for an UPDATE_FAILED
entry. (Read the Status reason for that event to understand why the stack update failed.)
After you think that you resolved any errors, run the update-stack command again. In the console, return to the
AWS CloudFormation stack and go to the Events tab to confirm whether you successfully updated the stack.
Repeat as necessary.
23. Verify success.
Does the stack's Outputs tab list an output with a URL value? If so, choose the link.
Does the static website open? (You previously copied the website assets into the bucket.)
If so, congratulations!
Note: If the stack does not have any output—or if the output hyperlink does not display the contents of the café website
—you can try these troubleshooting steps.
Browse to the Amazon S3 console and choose your bucket. The Overview tab should list the index.html file and
two folders that are named css and images. If these resources are not listed, you might want to revisit the first step
in this challenge section.
Choose the index.html file and then choose Permissions. For Everyone(Public access), the value in the Object
column should be Read.
Return to the bucket view. In the Properties tab, confirm that Static website hosting is enabled, with a Hosting
type of Bucket hosting.
All of the permissions and properties that are described in this list were either set by the AWS CLI S3 commands
you ran, or were set in your S3.yaml template. If necessary, adjust the details in the template and run the update-
stack AWS CLI command again.
Note: In this first challenge, you manually copied the website files into the bucket. You can also perform this action
by using a custom resource from AWS CloudFormation, combined with an AWS Lambda function. Both of these
resources can be defined in an AWS CloudFormation template. This approach is a more advanced use of AWS
CloudFormation beyond the scope of this lab. However, if you are interested in this topic, refer to the AWS Lambda-
backed custom resources page in the AWS Documentation.
24. Browse to the CodeCommit service and in your account, notice the repository that is named CFTemplatesRepo.
CodeCommit is a source control service that can be used to host Git-based repositories. It can be used in a way that's similar to
GitHub repositories. For details about AWS CodeCommit, see the AWS Documentation.
27. In the breadcrumbs at the top of the page, choose Repositories and in the Clone URL column, choose HTTPS.
This action copies the CodeCommit repository's HTTPS clone URL to your clipboard.
28. Return to the AWS Cloud9 IDE and clone the existing CodeCommit repository to your workspace (replace <url> with the clone
URL that you copied)
In the Bash terminal in the AWS Cloud9 IDE, enter this command:
This command clones a copy of the CodeCommit repository that you just observed. The command creates a CFTemplatesRepo
directory that should now appear in the navigation pane (which is the left pane in the IDE).
Use the Git client software to analyze your local copy of the repository.
cd CFTemplatesRepo
git status
The git status command shows what branch of the repository you are connected to. It also shows that your local copy is
up to date with the source branch in CodeCommit.
29. Create a new AWS CloudFormation template that will create a VPC, public subnet, and other resources.
In the navigation pane of the AWS Cloud9 IDE, expand the CFTemplatesRepo/templates directory.
In the templates directory, right-click template1.yaml and create a duplicate of it.
Rename the duplicate to: cafe-network.yaml
In the text editor, open cafe-network.yaml and set the description to: Network layer for the cafe
Observe the details of the seven resources that this template creates.
30. Observe the AWS CodePipeline details that were preconfigured in your account.
In the AWS Management Console, in the search box to the right of *Services*, search for and choose CodePipeline to
open the CodePipeline console.
Choose Pipelines.
Notice that two pipelines have been predefined for you:
CafeAppPipeline
CafeNetworkPipeline
Important: The status of the most recent attempt to run each pipeline will show that they failed. However, this status is
expected. The AWS CloudFormation template files that the pipelines reference do not exist in their expected location.
For more details about AWS CodePipeline, refer to the AWS Documentation.
33. Return to the AWS Cloud9 instance and trigger the creation of the update-cafe-network by checking your AWS CloudFormation
template into CodeCommit.
Observe how the local copy of the repository differs from the origin. In the Bash terminal, run the following command:
git status
The output should show that the cafe-network.yaml file that you created is currently untracked in Git.
Run these two commands to add the new file to the repository and then commit it to the repository with a comment.
git status
The information that is returned should report that your branch is ahead of the origin by one commit.
Finally, push the commit to the remote repository (this command actually copies the file to CodeCommit):
git push
36. In the Amazon VPC console, observe that the resources defined in the cafe-network.yaml template were created in the AWS
account.
For example, the console should list a VPC named Cafe VPC, and a subnet named Cafe Public Subnet.
Congratulations! You have successfully created the network resources that are needed to run the café website.
Outputs:
PublicSubnet:
Description: The subnet ID to use for public web servers
Value:
Ref: PublicSubnet
Export:
Name:
'Fn::Sub': '${AWS::StackName}-SubnetID'
VpcId:
Description: The VPC ID
Value:
Ref: VPC
Export:
Name:
'Fn::Sub': '${AWS::StackName}-VpcID'
38. Save the change and in the Bash terminal, add and commit the code, and then push it to CodeCommit by using Git.
39. Verify that the AWS CloudFormation stack update occurs. Also verify that the Outputs tab now lists two keys with export
names.
PublicSubnet update-cafe-network-SubnetID
VpcId update-cafe-network-VpcID
Task 6: Defining an EC2 instance resource and creating the application stack
In this task, you will create a new AWS CloudFormation template that will be used to create a stack. The new stack deploys a
dynamic website for the café. The CafeAppPipeline pipeline (which you observed earlier) creates or updates the update-cafe-app
stack when you push the cafe-app.yaml template to the CodeCommit repository.
40. Back in AWS Cloud9, duplicate the template2.yaml file in the templates directory and rename the duplicate as cafe-
app.yaml .
42. In the cafe-app.yaml template, define a third parameter so that a user can choose between different instance types when they
launch an EC2 instance.
Browse to the AWS Documentation. Under the Defining a parameter in a template section, copy the example YAML
parameter.
Paste the parameter into your template. Then, modify the parameter so that the permitted instance types are t2.micro,
t2.small, t3.micro, and t3.small. Also, set the default to t2.small and update the description so that it reflects the
options that a user can choose.
43. In a new browser tab, open the AWS Documentation and use the information in that page as a reference.
44. Back in the cafe-app.yaml template, create a new EC2 instance resource that has the following characteristics:
Set the Logical ID to CafeInstance (see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource
s-section-structure.html for reference, if needed)
Include an ImageId that references the LatestAmiId parameter
For instance type, reference the instance type parameter that you defined in the previous step.
For KeyName, use the following line of code, which references the RegionMap mapping that is already defined in the
template:
For the instance profile (the AWS Identity and Access Management, or IAM, role that is attached to the instance), specify
CafeRole
Note: The CafeRole IAM role already exists in your account. Attaching it grants your EC2 instance the permissions to
retrieve Parameter Store values from AWS Systems Manager.
In the Properties section, include the following lines of code:
NetworkInterfaces:
- DeviceIndex: '0'
AssociatePublicIpAddress: 'true'
SubnetId: !ImportValue
'Fn::Sub': '${CafeNetworkParameter}-SubnetID'
GroupSet:
- !Ref CafeSG
Analysis: The previous lines help ensure that your instance deploys to the Public Subnet that you created when you
ran the café network stack. Recall that at the beginning of this task, you updated the network stack to define
outputs with export names. In the preceding code, you import the value for the SubnetId. The preceding code also
helps ensure that the instance you create will be in the CafeSG security group that is already defined for you in this
template.
Set a tag with a key of Name and a value of Cafe Web Server
Tip: Observe how a Name tag was applied to the security group resource that is already defined in the template.
In the Properties section, include the following additional UserData code:
UserData:
Fn::Base64:
!Sub |
#!/bin/bash
yum -y update
yum install -y httpd mariadb-server wget
amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2
systemctl enable httpd
systemctl start httpd
systemctl enable mariadb
systemctl start mariadb
wget https://aws-tc-largeobjects.s3.us-west-2.amazonaws.com/CUR-TF-200-ACACAD-2-91555/14-
lab-mod10-challenge-CFn/s3/cafe-app.sh
chmod +x cafe-app.sh
./cafe-app.sh
Analysis: The previous code runs on the instance at the end of the boot process. It installs an Apache HTTP web server,
a MariaDB database, and PHP on the Amazon Linux instance. Next, it starts the web server and the database. Then, it
downloads a script named cafe-app.sh and runs it. The cafe-app script configures the database and installs the PHP code
that makes the café website function.
45. After you are satisfied with your template updates, save the changes. To validate the template format in the Bash terminal,
run the following command:
If you receive a JSON-formatted response that includes the three parameters that were defined at the top of your template,
then your template passed the validation. However, if you received a ValidationError response (or some other error response),
you must correct the issue. Then, save the changes and run the validate-template command again.
46. If your template passed the validation check, add the file to CodeCommit. In the Bash terminal, run git commands to add
the file, commit it, and push it to the repository.
Tip: If it helps, refer back to the Git commands in Task 3. However, remember that the name of the template that you want
to push to CodeCommit for this task is different.
48. In the AWS CloudFormation console, confirm that the update-cafe-app stack ran successfully and has a status of
CREATE_COMPLETE.
49. Go to the Amazon EC2 console. Observe that the EC2 instance and security group resources (which were defined in the cafe-
app.yaml template) were created.
50. After the EC2 instance has started and passed both status checks, test the café website. In a browser tab, load the following
URL, where <public-ip-address> is the public IPv4 address of the EC2 instance that you defined: http://<public-ip-
address>/cafe
You should see the café website.
Tip: It can take 2 minutes or so for the user data script details that you defined to finish running. Be patient if you do not see
the website immediately.
Notice that the website shows server information, such as the Region and Availability Zone where the web server is running.
Congratulations! You deployed a network layer and an application layer by using a CI/CD pipeline and an IaC approach.
Task 7: Duplicating the café network and website to another AWS Region
In this final lab task, you will experience how quickly you can duplicate a deployment. A quick deployment is possible because you
defined all your resources in AWS CloudFormation templates.
In Tasks 4, 5, and 6, the AWS CloudFormation stacks were created or updated automatically. A pipeline was defined to monitor
when the CodeCommit repository was updated. It then invoked AWS CloudFormation to create or update the stack. However, in
this task, you will use the AWS CLI to duplicate the café network resources in another AWS Region. Then, you will use the AWS
CloudFormation console to create the application stack in the second Region.
52. Back in the AWS Cloud9 IDE, run the following command to duplicate the café network to another AWS Region:
It should return a StackId. Notice that you could override the default Region for the creation of this stack by specifying the
Region when you ran the command.
53. Browse to the AWS CloudFormation console and change the Region to US West (Oregon) us-west-2.
The update-cafe-network stack should be listed
Verify that the status of the second update-cafe-region stack eventually changes to CREATE_COMPLETE
Tip: Use the refresh icon to see the status change more quickly when it completes.
54. Browse to the Amazon VPC service page, and also confirm that you are using the Oregon Region (us-west-2).
You should be able to observe the network resources that were created.
55. In the Oregon Region (us-west-2), create an EC2 key pair named cafe-oregon .
Browse to the Amazon EC2 console and confirm that you are in the Oregon Region.
From the navigation pane, choose Network & Security > Key Pairs.
Choose Create key pair.
Name the key pair cafe-oregon and choose Create key pair again.
Tip: You can optionally save the key pair, or you can choose Cancel. You don't need to use the key pair in this lab.
However, in a typical use case, you must save the key pair—you will not have another opportunity to do so.
57. In the AWS Cloud9 IDE, copy the template file to an S3 bucket. (In the following command, replace <repobucket-bucketname>
with the actual S3 bucket name in your account. Its name should contain the string repobucket.)
58. In the Amazon S3 console, copy the Object URL (which is an https address) of the file that you just uploaded.
59. In the AWS CloudFormation console, change the Region to Oregon (us-west-2).
Sofía is full with ideas as a result of what she just learned how to do!
She used AWS CloudFormation to deploy a static version of the café website successfully. She then deployed the dynamic café
website as a web application successfully. For the dynamic website, Sofía used a CI/CD pipeline that used AWS CodeCommit, AWS
CodePipeline, and AWS CloudFormation. In addition, she quickly duplicated both the network resources and the café application
resources to another AWS Region.
Sofía imagines how she could use the AWS CloudFormation templates as part of a backup and disaster recovery (DR) solution. She
just experienced how quickly she was able to re-create the essential café infrastructure. If her production deployment ever
experiences a failure for any reason, she can now recreate it or duplicate it quickly.
Sofía also thinks about how she can now spin up test environments quickly. She can be confident that the configuration details of
the test environments will match the production environment. She can also specifically control the ways that the test environment
differs from the production environment by using features such as parameters and mappings.
The benefits of DevOps automation are many. Sofía now plans to make automation and CI/CD pipelines central to the way her
team develops, tests, and deploys updates to the café's cloud resources.
Lab complete
Congratulations! You have completed the lab.
65. To confirm that you want to end the lab, at the top of this page, choose End Lab, and then choose Yes.
A panel should appear with this message: DELETE has been initiated... You may close this message box now.
©2020 Amazon Web Services, Inc. and its affiliates. All rights reserved. This work may not be reproduced or redistributed, in whole or in
part, without prior written permission from Amazon Web Services, Inc. Commercial copying, lending, or selling is prohibited.