Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ElastiCache related resources examples for CFN & CDK(Python & Typescript). #60

Merged
merged 1 commit into from
Sep 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions cdk/python/elasticache-resources/.gitignore
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 cdk/python/elasticache-resources/README.md
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 CDK development with Python.

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 cdk/python/elasticache-resources/app.py
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 elasticache_resources.elasticache_resources_stack import ElasticacheResourcesStack


app = cdk.App()
ElasticacheResourcesStack(app, "elasticache-resources",
# 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()
71 changes: 71 additions & 0 deletions cdk/python/elasticache-resources/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
{
"app": "python3 app.py",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"requirements*.txt",
"source.bat",
"**/__init__.py",
"**/__pycache__",
"tests"
]
},
"context": {
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/core:checkSecretUsage": true,
"@aws-cdk/core:target-partitions": [
"aws",
"aws-cn"
],
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
"@aws-cdk/aws-iam:minimizePolicies": true,
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
"@aws-cdk/core:enablePartitionLiterals": true,
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
"@aws-cdk/aws-route53-patters:useCertificate": true,
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
"@aws-cdk/aws-redshift:columnId": true,
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
"@aws-cdk/aws-kms:aliasNameRef": true,
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
"@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
"@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
"@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
"@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
"@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
"@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
"@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
"@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
"@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
"@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true,
"@aws-cdk/aws-eks:nodegroupNameAttribute": true,
"@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true,
"@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true,
"@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false,
"@aws-cdk/aws-s3:keepNotificationInImportedBucket": false,
"cdk-migrate": true
}
}
Binary file not shown.
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
from aws_cdk import Stack
import aws_cdk as cdk
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_elasticache as elasticache
from constructs import Construct

class ElasticacheResourcesStack(Stack):

def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)


# VPC resources to be used

vpc = ec2.Vpc(self, "TheVPC",
ip_addresses=ec2.IpAddresses.cidr("10.0.0.0/16")
)


# Security Group for EC2 instances
security_group_name = 'myec2securitygroup'
ec2SecurityGroup = ec2.SecurityGroup(self, 'EC2SecurityGroup',
vpc=vpc,
description='Security group for EC2 instances',
allow_all_outbound=True,
security_group_name=security_group_name
)

# Allowing all inbound traffic (adjust as necessary)
ec2SecurityGroup.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(0), "Allow all inbound traffic")

# Elasticache Parameter group
elastiCacheParameterGroup = elasticache.CfnParameterGroup(self, 'ElastiCacheParameterGroup',
cache_parameter_group_family = 'redis7',
description = 'Parameter group for ElastiCache',
properties = {
'maxmemory-policy': 'allkeys-lru',
},
)

# Elasticache Security group
elastiCacheSecurityGroup = elasticache.CfnSecurityGroup(self, 'ElastiCacheSecurityGroup',
description = 'Security group for ElastiCache',
tags = [
{
'key': 'Name',
'value': 'ElastiCacheSecurityGroup',
},
],
)

# Elasticache Serverless Cache
elastiCacheServerlessCache = elasticache.CfnServerlessCache(self, 'ElastiCacheServerlessCache',
engine = 'redis',
serverless_cache_name = "MyServerlessCache",
)

# Elasticache Subnet group
elastiCacheSubnetGroup = elasticache.CfnSubnetGroup(self, 'ElastiCacheSubnetGroup',
cache_subnet_group_name = "CustomCacheSubnetGroup",
description = 'Subnet group with required subnets',
subnet_ids= [vpc.public_subnets[0].subnet_id, vpc.public_subnets[1].subnet_id],
)

# Elasticache User
elastiCacheUser = elasticache.CfnUser(self, 'ElastiCacheUser',
user_name = 'default',
user_id = 'u1',
engine = 'redis',
access_string = 'on ~* +@all',
no_password_required = True,
)

# Elasticache Replication Group
elastiCacheReplicationGroup = elasticache.CfnReplicationGroup(self, 'ElastiCacheReplicationGroup',
replication_group_description = 'Replication group for ElastiCache',
replication_group_id = "MyReplicationGroup",
cache_node_type = 'cache.m5.large',
engine = 'redis',
num_cache_clusters = 2,
cache_parameter_group_name = elastiCacheParameterGroup.ref,
)

# Elasticache User Group
elastiCacheUserGroup = elasticache.CfnUserGroup(self, 'ElastiCacheUserGroup',
user_ids = [
elastiCacheUser.ref,
],
engine = 'redis',
user_group_id = 'a1',
)

# Elasticache Cluster
elasticacheCluster = elasticache.CfnCacheCluster(self, 'ElasticacheCluster',
engine = 'redis',
cache_node_type = 'cache.m5.large',
num_cache_nodes = 1,
cache_subnet_group_name = elastiCacheSubnetGroup.ref,
vpc_security_group_ids = [
ec2SecurityGroup.security_group_id,
],
)

# Elasticache Global Replication Group
elastiCacheGlobalReplicationGroup = elasticache.CfnGlobalReplicationGroup(self, 'ElastiCacheGlobalReplicationGroup',
global_replication_group_description = 'Global replication group for ElastiCaches',
global_replication_group_id_suffix = "global",
members = [
{
'replicationGroupId': elastiCacheReplicationGroup.ref,
'replicationGroupRegion': 'us-east-1',
'role': 'PRIMARY',
},
],
)

# Outputs
"""
Security Group ID for ElastiCache
"""
self.security_group_id = elastiCacheSecurityGroup.ref
cdk.CfnOutput(self, 'CfnOutputSecurityGroupId',
key = 'SecurityGroupId',
description = 'Security Group ID for ElastiCache',
value = str(self.security_group_id),
)

"""
Replication Group ID for ElastiCache
"""
self.replication_group_id = elastiCacheReplicationGroup.ref
cdk.CfnOutput(self, 'CfnOutputReplicationGroupId',
key = 'ReplicationGroupId',
description = 'Replication Group ID for ElastiCache',
value = str(self.replication_group_id),
)

"""
Global Replication Group ID for ElastiCache
"""
self.global_replication_group_id = elastiCacheGlobalReplicationGroup.ref
cdk.CfnOutput(self, 'CfnOutputGlobalReplicationGroupId',
key = 'GlobalReplicationGroupId',
description = 'Global Replication Group ID for ElastiCache',
value = str(self.global_replication_group_id),
)

"""
User Group ID for ElastiCache
"""
self.user_group_id = elastiCacheUserGroup.ref
cdk.CfnOutput(self, 'CfnOutputUserGroupId',
key = 'UserGroupId',
description = 'User Group ID for ElastiCache',
value = str(self.user_group_id),
)



1 change: 1 addition & 0 deletions cdk/python/elasticache-resources/requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pytest==6.2.5
2 changes: 2 additions & 0 deletions cdk/python/elasticache-resources/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
aws-cdk-lib==2.155.0
constructs>=10.0.0,<11.0.0
13 changes: 13 additions & 0 deletions cdk/python/elasticache-resources/source.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
@echo off

rem The sole purpose of this script is to make the command
rem
rem source .venv/bin/activate
rem
rem (which activates a Python virtualenv on Linux or Mac OS X) work on Windows.
rem On Windows, this command just runs this batch file (the argument is ignored).
rem
rem Now we don't need to document a Windows command for activating a virtualenv.

echo Executing .venv\Scripts\activate.bat for you
.venv\Scripts\activate.bat
Empty file.
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import aws_cdk as core
import aws_cdk.assertions as assertions

from elasticache_resources.elasticache_resources_stack import ElasticacheResourcesStack

# example tests. To run these tests, uncomment this file along with the example
# resource in elasticache_resources/elasticache_resources_stack.py
def test_elasticache_stack_created():
app = core.App()
stack = ElasticacheResourcesStack(app, "elasticache-resources")
template = assertions.Template.from_stack(stack)


Binary file added cdk/typescript/elasticache-resource/.DS_Store
Binary file not shown.
8 changes: 8 additions & 0 deletions cdk/typescript/elasticache-resource/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
*.js
!jest.config.js
*.d.ts
node_modules

# CDK asset staging directory
.cdk.staging
cdk.out
6 changes: 6 additions & 0 deletions cdk/typescript/elasticache-resource/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*.ts
!*.d.ts

# CDK asset staging directory
.cdk.staging
cdk.out
14 changes: 14 additions & 0 deletions cdk/typescript/elasticache-resource/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Welcome to your CDK TypeScript project

This is a blank project for CDK development with TypeScript.

The `cdk.json` file tells the CDK Toolkit how to execute your app.

## Useful commands

* `npm run build` compile typescript to js
* `npm run watch` watch for changes and compile
* `npm run test` perform the jest unit tests
* `npx cdk deploy` deploy this stack to your default AWS account/region
* `npx cdk diff` compare deployed stack with current state
* `npx cdk synth` emits the synthesized CloudFormation template
Loading