Skip to content

Commit

Permalink
Updated READMEs
Browse files Browse the repository at this point in the history
  • Loading branch information
johnculkin committed Dec 7, 2021
1 parent 0c01bfe commit 7ef91b3
Show file tree
Hide file tree
Showing 21 changed files with 399 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::664865145641:role/cdk-aws-cookbook-305-Instance1SSM06992D3D-ML80O8CVOLOV"
"AWS": "arn:aws:iam::611652777867:role/cdk-aws-cookbook-305-Instance1SSM06992D3D-QXCUX2LC7Y0V"
},
"Action": ["s3:GetObject","s3:PutObject"],
"Resource": "arn:aws:s3:us-east-1:664865145641:accesspoint/cookbook305-app-1/object/*"
"Resource": "arn:aws:s3:us-east-1:611652777867:accesspoint/cookbook305-app-1/object/*"
}]
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::664865145641:role/cdk-aws-cookbook-305-Instance2SSM9F9326DF-K3V3PP8TD6W5"
"AWS": "arn:aws:iam::611652777867:role/cdk-aws-cookbook-305-Instance2SSM9F9326DF-6BF2OD4V1RYG"
},
"Action": ["s3:GetObject"],
"Resource": "arn:aws:s3:us-east-1:664865145641:accesspoint/cookbook305-app-2/object/*"
"Resource": "arn:aws:s3:us-east-1:611652777867:accesspoint/cookbook305-app-2/object/*"
}]
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:

iam_role1.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("AmazonSSMManagedInstanceCore"))

iam_role1.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("AmazonS3FullAccess"))

instance1 = ec2.Instance(
self,
"Instance1",
Expand All @@ -106,6 +108,8 @@ def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:

iam_role2.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("AmazonSSMManagedInstanceCore"))

iam_role2.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("AmazonS3FullAccess"))

instance2 = ec2.Instance(
self,
"Instance2",
Expand Down
6 changes: 4 additions & 2 deletions 306-Using-Amazon-S3-Bucket-Keys-with-KMS/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ RANDOM_STRING=$(aws secretsmanager get-random-password \
--password-length 6 --require-each-included-type \
--output text \
--query RandomPassword)
```

Create an S3 bucket
aws s3api create-bucket --bucket awscookbook305-$RANDOM_STRING
### Create an S3 bucket
```
aws s3api create-bucket --bucket awscookbook306-$RANDOM_STRING
```

## Clean up
Expand Down
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 ../..`
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
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!
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()
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
}
}
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
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("")
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pytest==6.2.5
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-e .
boto3
Loading

0 comments on commit 7ef91b3

Please sign in to comment.