-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0c01bfe
commit 7ef91b3
Showing
21 changed files
with
399 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 changes: 40 additions & 0 deletions
40
...Creating-and-Restoring-EC2-Backups-to-Another-Region-using-AWS-Backup/README.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
# Configuring Automated Backups with AWS Backup | ||
## Preparation | ||
This recipe requires some “prep work” which deploys resources that you’ll build the solution on. You will use the AWS CDK to deploy these resources. | ||
|
||
### In the root of this chapter’s repo, cd to the “307-Creating-and-Restoring-EC2-Backups-to-Another-Region-using-AWS-Backup/cdk-AWS-Cookbook-307” directory and follow the subsequent steps: | ||
``` | ||
cd 307-Creating-and-Restoring-EC2-Backups-to-Another-Region-using-AWS-Backup/cdk-AWS-Cookbook-307/ | ||
test -d .venv || python3 -m venv .venv | ||
source .venv/bin/activate | ||
pip install --upgrade pip | ||
pip install -r requirements.txt | ||
cdk deploy | ||
``` | ||
|
||
### Wait for the cdk deploy command to complete. | ||
|
||
### We created a helper.py script (available in this Chapter’s repo) to let you easily create and export environment variables to make subsequent commands easier. Run the script, and copy the output to your terminal to export variables: | ||
|
||
`python helper.py` | ||
|
||
|
||
## Clean up | ||
### Delete the recovery point in the backup vault within your destination region. | ||
|
||
### Terminate the EC2 instance you restored in the destination region. | ||
|
||
### Delete the recovery point in the backup vault within your source region. | ||
|
||
### To clean up the environment variables, run the helper.py script in this recipe’s cdk- directory with the --unset flag, and copy the output to your terminal to export variables: | ||
|
||
`python helper.py --unset` | ||
|
||
### Unset the environment variable that you created manually: | ||
``` | ||
``` | ||
|
||
### Use the AWS CDK to destroy the resources, deactivate your Python virtual environment, and go to the root of the chapter: | ||
|
||
`cdk destroy && deactivate && rm -r .venv/ && cd ../..` |
10 changes: 10 additions & 0 deletions
10
...-Restoring-EC2-Backups-to-Another-Region-using-AWS-Backup/cdk-AWS-Cookbook-307/.gitignore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
*.swp | ||
package-lock.json | ||
__pycache__ | ||
.pytest_cache | ||
.venv | ||
*.egg-info | ||
|
||
# CDK asset staging directory | ||
.cdk.staging | ||
cdk.out |
58 changes: 58 additions & 0 deletions
58
...g-EC2-Backups-to-Another-Region-using-AWS-Backup/cdk-AWS-Cookbook-307/README.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
|
||
# Welcome to your CDK Python project! | ||
|
||
This is a blank project for Python development with CDK. | ||
|
||
The `cdk.json` file tells the CDK Toolkit how to execute your app. | ||
|
||
This project is set up like a standard Python project. The initialization | ||
process also creates a virtualenv within this project, stored under the `.venv` | ||
directory. To create the virtualenv it assumes that there is a `python3` | ||
(or `python` for Windows) executable in your path with access to the `venv` | ||
package. If for any reason the automatic creation of the virtualenv fails, | ||
you can create the virtualenv manually. | ||
|
||
To manually create a virtualenv on MacOS and Linux: | ||
|
||
``` | ||
$ python3 -m venv .venv | ||
``` | ||
|
||
After the init process completes and the virtualenv is created, you can use the following | ||
step to activate your virtualenv. | ||
|
||
``` | ||
$ source .venv/bin/activate | ||
``` | ||
|
||
If you are a Windows platform, you would activate the virtualenv like this: | ||
|
||
``` | ||
% .venv\Scripts\activate.bat | ||
``` | ||
|
||
Once the virtualenv is activated, you can install the required dependencies. | ||
|
||
``` | ||
$ pip install -r requirements.txt | ||
``` | ||
|
||
At this point you can now synthesize the CloudFormation template for this code. | ||
|
||
``` | ||
$ cdk synth | ||
``` | ||
|
||
To add additional dependencies, for example other CDK libraries, just add | ||
them to your `setup.py` file and rerun the `pip install -r requirements.txt` | ||
command. | ||
|
||
## Useful commands | ||
|
||
* `cdk ls` list all stacks in the app | ||
* `cdk synth` emits the synthesized CloudFormation template | ||
* `cdk deploy` deploy this stack to your default AWS account/region | ||
* `cdk diff` compare deployed stack with current state | ||
* `cdk docs` open CDK documentation | ||
|
||
Enjoy! |
28 changes: 28 additions & 0 deletions
28
...-and-Restoring-EC2-Backups-to-Another-Region-using-AWS-Backup/cdk-AWS-Cookbook-307/app.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
#!/usr/bin/env python3 | ||
import os | ||
|
||
import aws_cdk as cdk | ||
|
||
from cdk_aws_cookbook_307.cdk_aws_cookbook_307_stack import CdkAwsCookbook307Stack | ||
|
||
|
||
app = cdk.App() | ||
CdkAwsCookbook307Stack(app, "cdk-aws-cookbook-307", | ||
# If you don't specify 'env', this stack will be environment-agnostic. | ||
# Account/Region-dependent features and context lookups will not work, | ||
# but a single synthesized template can be deployed anywhere. | ||
|
||
# Uncomment the next line to specialize this stack for the AWS Account | ||
# and Region that are implied by the current CLI configuration. | ||
|
||
#env=cdk.Environment(account=os.getenv('CDK_DEFAULT_ACCOUNT'), region=os.getenv('CDK_DEFAULT_REGION')), | ||
|
||
# Uncomment the next line if you know exactly what Account and Region you | ||
# want to deploy the stack to. */ | ||
|
||
#env=cdk.Environment(account='123456789012', region='us-east-1'), | ||
|
||
# For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html | ||
) | ||
|
||
app.synth() |
24 changes: 24 additions & 0 deletions
24
...nd-Restoring-EC2-Backups-to-Another-Region-using-AWS-Backup/cdk-AWS-Cookbook-307/cdk.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
{ | ||
"app": "python3 app.py", | ||
"watch": { | ||
"include": [ | ||
"**" | ||
], | ||
"exclude": [ | ||
"README.md", | ||
"cdk*.json", | ||
"requirements*.txt", | ||
"source.bat", | ||
"**/__init__.py", | ||
"python/__pycache__", | ||
"tests" | ||
] | ||
}, | ||
"context": { | ||
"@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": true, | ||
"@aws-cdk/core:stackRelativeExports": true, | ||
"@aws-cdk/aws-rds:lowercaseDbIdentifier": true, | ||
"@aws-cdk/aws-lambda:recognizeVersionProps": true, | ||
"@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": true | ||
} | ||
} |
Empty file.
93 changes: 93 additions & 0 deletions
93
...-using-AWS-Backup/cdk-AWS-Cookbook-307/cdk_aws_cookbook_307/cdk_aws_cookbook_307_stack.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
from constructs import Construct | ||
from aws_cdk import ( | ||
aws_ec2 as ec2, | ||
aws_iam as iam, | ||
Stack, | ||
CfnOutput, | ||
RemovalPolicy | ||
) | ||
|
||
|
||
class CdkAwsCookbook307Stack(Stack): | ||
|
||
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: | ||
super().__init__(scope, construct_id, **kwargs) | ||
|
||
isolated_subnets = ec2.SubnetConfiguration( | ||
name="ISOLATED", | ||
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED, | ||
cidr_mask=24 | ||
) | ||
|
||
# create VPC | ||
vpc = ec2.Vpc( | ||
self, | ||
'AWS-Cookbook-VPC-307', | ||
cidr='10.10.0.0/23', | ||
subnet_configuration=[isolated_subnets] | ||
) | ||
|
||
# -------- Begin EC2 Helper --------- | ||
vpc.add_interface_endpoint( | ||
'VPCSSMInterfaceEndpoint', | ||
service=ec2.InterfaceVpcEndpointAwsService('ssm'), # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames' | ||
private_dns_enabled=True, | ||
subnets=ec2.SubnetSelection( | ||
one_per_az=False, | ||
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED | ||
), | ||
) | ||
|
||
vpc.add_interface_endpoint( | ||
'VPCEC2MessagesInterfaceEndpoint', | ||
service=ec2.InterfaceVpcEndpointAwsService('ec2messages'), # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames' | ||
private_dns_enabled=True, | ||
subnets=ec2.SubnetSelection( | ||
one_per_az=False, | ||
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED | ||
), | ||
) | ||
|
||
vpc.add_interface_endpoint( | ||
'VPCSSMMessagesInterfaceEndpoint', | ||
service=ec2.InterfaceVpcEndpointAwsService('ssmmessages'), # Find names with - aws ec2 describe-vpc-endpoint-services | jq '.ServiceNames' | ||
private_dns_enabled=True, | ||
subnets=ec2.SubnetSelection( | ||
one_per_az=False, | ||
subnet_type=ec2.SubnetType.PRIVATE_ISOLATED | ||
), | ||
) | ||
|
||
ami = ec2.MachineImage.latest_amazon_linux( | ||
generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2, | ||
edition=ec2.AmazonLinuxEdition.STANDARD, | ||
virtualization=ec2.AmazonLinuxVirt.HVM, | ||
storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE | ||
) | ||
user_data = ec2.UserData.for_linux() | ||
# user_data.add_commands('sudo yum -y update', | ||
# 'sudo yum install -y httpd', | ||
# 'sudo systemctl start httpd') | ||
|
||
iam_role = iam.Role(self, "InstanceSSM", assumed_by=iam.ServicePrincipal("ec2.amazonaws.com")) | ||
|
||
iam_role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("AmazonSSMManagedInstanceCore")) | ||
|
||
instance = ec2.Instance( | ||
self, | ||
"Instance", | ||
instance_type=ec2.InstanceType("t3.nano"), | ||
machine_image=ami, | ||
user_data=user_data, | ||
role=iam_role, | ||
vpc=vpc, | ||
) | ||
|
||
CfnOutput( | ||
self, | ||
'InstanceId', | ||
value=instance.instance_id | ||
) | ||
# -------- End EC2 Helper --------- | ||
|
||
# outputs |
49 changes: 49 additions & 0 deletions
49
...d-Restoring-EC2-Backups-to-Another-Region-using-AWS-Backup/cdk-AWS-Cookbook-307/helper.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import os | ||
import boto3 | ||
import argparse | ||
|
||
|
||
def change_case(str): | ||
res = [str[0]] | ||
for c in str[1:]: | ||
if c in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'): | ||
res.append('_') | ||
res.append(c) | ||
elif c in ('123456789'): | ||
res.append('_') | ||
res.append(c) | ||
else: | ||
res.append(c.upper()) | ||
|
||
return ''.join(res) | ||
|
||
|
||
parser = argparse.ArgumentParser(description="Generate commands to set and unset environment variables") | ||
parser.add_argument('--unset', action='store_true', help="Generate commands to unset environment variables by setting this flag") | ||
|
||
args = parser.parse_args() | ||
|
||
os.environ['AWS_DEFAULT_REGION'] = os.environ.get('AWS_REGION') | ||
|
||
cfn = boto3.client('cloudformation') | ||
stackname = os.path.basename(os.getcwd()).lower() | ||
response = cfn.describe_stacks(StackName=stackname) | ||
unsets = [] | ||
sets = [] | ||
|
||
outputs = response["Stacks"][0]["Outputs"] | ||
print("Copy and paste the commands below into your terminal") | ||
print("") | ||
for output in outputs: | ||
if ', ' in output["OutputValue"]: | ||
sets.append(change_case(output["OutputKey"]) + "='" + ', '.join('"{}"'.format(word) for word in output["OutputValue"].split(", ")) + "'") | ||
else: | ||
sets.append(change_case(output["OutputKey"]) + "='" + output["OutputValue"] + "'") | ||
unsets.append("unset " + change_case(output["OutputKey"])) | ||
|
||
if (args.unset): | ||
print('\n'.join(map(str, unsets))) | ||
else: | ||
print('\n'.join(map(str, sets))) | ||
|
||
print("") |
1 change: 1 addition & 0 deletions
1
...-EC2-Backups-to-Another-Region-using-AWS-Backup/cdk-AWS-Cookbook-307/requirements-dev.txt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
pytest==6.2.5 |
2 changes: 2 additions & 0 deletions
2
...ring-EC2-Backups-to-Another-Region-using-AWS-Backup/cdk-AWS-Cookbook-307/requirements.txt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
-e . | ||
boto3 |
Oops, something went wrong.