def inject_to(self, t):
        attribute_definitions = [
            dynamodb.AttributeDefinition(AttributeName=self.hash_key[0],
                                         AttributeType=self.hash_key[1])
        ]

        key_schema = [
            dynamodb.KeySchema(AttributeName=self.hash_key[0], KeyType="HASH")
        ]

        if self.range_key is not None:
            attribute_definitions.append(
                dynamodb.AttributeDefinition(AttributeName=self.range_key[0],
                                             AttributeType=self.range_key[1]))
            key_schema.append(
                dynamodb.KeySchema(AttributeName=self.range_key[0],
                                   KeyType="RANGE"))

        table = t.add_resource(
            dynamodb.Table(
                self.label,
                AttributeDefinitions=attribute_definitions,
                KeySchema=key_schema,
                ProvisionedThroughput=self.get_provisioned_throughput(t)))

        self.configure_autoscaling(t, table)

        return t
Esempio n. 2
0
def words_table():
  return dynamodb.Table(
      'WordsTable',
      AttributeDefinitions=words_attrdefs(),
      GlobalSecondaryIndexes=words_gsis(),
      KeySchema=[
          dynamodb.KeySchema(AttributeName='user', KeyType='HASH'),
          dynamodb.KeySchema(AttributeName='word', KeyType='RANGE'),
      ],
      ProvisionedThroughput=dynamodb.ProvisionedThroughput(
          ReadCapacityUnits=1, WriteCapacityUnits=1))
Esempio n. 3
0
    def __init__(self, title, **kwargs):
        super().__init__(title, **kwargs)

        self.AttributeDefinitions = [
            ddb.AttributeDefinition(AttributeName='name', AttributeType='S'),
            ddb.AttributeDefinition(AttributeName='version', AttributeType='S')
        ]
        self.KeySchema = [
            ddb.KeySchema(AttributeName='name', KeyType='HASH'),
            ddb.KeySchema(AttributeName='version', KeyType='RANGE')
        ]
        self.ProvisionedThroughput = ddb.ProvisionedThroughput(
            ReadCapacityUnits=1, WriteCapacityUnits=1)
        self.TableName = Sub('credential-store-${EnvShort}')
Esempio n. 4
0
def define_key_schema(key_schema):
    key_schemas = []
    for schema in key_schema:
        key_schemas.append(
            dynamodb.KeySchema(
                AttributeName=schema["AttributeName"], KeyType=schema["KeyType"]
            )
        )
    return key_schemas
Esempio n. 5
0
 def cf_resources(cls):
     """produce CF template"""
     from troposphere import dynamodb
     return [
         dynamodb.Table(cls._TABLE_NAME,
                        TableName=cls._TABLE_NAME,
                        BillingMode='PAY_PER_REQUEST',
                        AttributeDefinitions=[
                            dynamodb.AttributeDefinition(AttributeName='id',
                                                         AttributeType='S'),
                            dynamodb.AttributeDefinition(
                                AttributeName='created_at',
                                AttributeType='S')
                        ],
                        KeySchema=[
                            dynamodb.KeySchema(AttributeName='id',
                                               KeyType='HASH'),
                            dynamodb.KeySchema(AttributeName='created_at',
                                               KeyType='RANGE')
                        ])
     ]
Esempio n. 6
0
def prep_schemata(config):
    schemata = []
    try:
        schemas = config["KeySchema"]
    except KeyError:
        raise KeyError(
            "The key schema is required for the creation of a DynamoDB table.")

    for schema in schemas:
        schemata.append(dynamodb.KeySchema(**schema))

    return schemata
Esempio n. 7
0
def words_gsis():
  return [
      dynamodb.GlobalSecondaryIndex(
          IndexName='user_showed_reminder',
          KeySchema=[
              dynamodb.KeySchema(AttributeName='user/showed', KeyType='HASH'),
              dynamodb.KeySchema(AttributeName='reminder', KeyType='RANGE'),
          ],
          Projection=dynamodb.Projection(ProjectionType='ALL'),
          ProvisionedThroughput=dynamodb.ProvisionedThroughput(
              ReadCapacityUnits=1, WriteCapacityUnits=1)),
      dynamodb.GlobalSecondaryIndex(
          IndexName='user_forgetful_reminder',
          KeySchema=[
              dynamodb.KeySchema(
                  AttributeName='user/forgetful', KeyType='HASH'),
              dynamodb.KeySchema(AttributeName='reminder', KeyType='RANGE'),
          ],
          Projection=dynamodb.Projection(ProjectionType='ALL'),
          ProvisionedThroughput=dynamodb.ProvisionedThroughput(
              ReadCapacityUnits=1, WriteCapacityUnits=1)),
  ]
Esempio n. 8
0
    def add_api_token_table(self):

        self._api_token_table = self.add_resource(
            dynamodb.Table(
                'ApiTokens',
                TableName=Sub('${AWS::StackName}ApiTokens'),
                AttributeDefinitions=[
                    dynamodb.AttributeDefinition(AttributeName='token',
                                                 AttributeType='S')
                ],
                BillingMode='PAY_PER_REQUEST',
                KeySchema=[
                    dynamodb.KeySchema(AttributeName='token', KeyType='HASH')
                ],
                SSESpecification=dynamodb.SSESpecification(SSEEnabled=True)))
Esempio n. 9
0
 def r_table(self):
     table_name = self.conf['table_name']
     table_key = self.conf['table_key']
     return dynamodb.Table('DynamoDbTable',
                           TableName=table_name,
                           BillingMode='PAY_PER_REQUEST',
                           AttributeDefinitions=[
                               dynamodb.AttributeDefinition(
                                   AttributeName=table_key,
                                   AttributeType='S'),
                           ],
                           KeySchema=[
                               dynamodb.KeySchema(AttributeName=table_key,
                                                  KeyType='HASH')
                           ])
Esempio n. 10
0
# ============================================================================
db = rds.DBInstance(
    'Postgres',
    DBInstanceClass='db.t2.micro',
    Engine='postgres',
    AllocatedStorage="5",
    DBName=Ref(db_name),
    MasterUsername=Ref(db_user),
    MasterUserPassword=Ref(db_password),
)

# ============================================================================
# Dynamodb
# ============================================================================
dynamo_db = dynamodb.Table(
    'DynamoDBLog',
    TableName='DynamoDBLog',
    AttributeDefinitions=[dynamodb.AttributeDefinition(
        AttributeName='request_id',
        AttributeType='S',
    )],
    KeySchema=[dynamodb.KeySchema(
        AttributeName='request_id',
        KeyType='HASH',
    )],
    ProvisionedThroughput=dynamodb.ProvisionedThroughput(
        ReadCapacityUnits=5,
        WriteCapacityUnits=5,
    )
)
Esempio n. 11
0
))

custom_resources.use_custom_resources_stack_name_parameter(template)

table1 = template.add_resource(dynamodb.Table(
    "Table1",
    BillingMode="PAY_PER_REQUEST",
    AttributeDefinitions=[
        dynamodb.AttributeDefinition(
            AttributeName="key",
            AttributeType="S",
        )
    ],
    KeySchema=[
        dynamodb.KeySchema(
            AttributeName="key",
            KeyType="HASH",
        )
    ],
))

template.add_output(Output(
    "Table1Name",
    Value=Ref(table1),
))

table2 = template.add_resource(dynamodb.Table(
    "Table2",
    BillingMode="PAY_PER_REQUEST",
    AttributeDefinitions=[
        dynamodb.AttributeDefinition(
            AttributeName="key",
Esempio n. 12
0
    def create_template(self):
        """Create template (main function called by Stacker)."""
        template = self.template
        variables = self.get_variables()
        self.template.add_version('2010-09-09')
        self.template.add_description('Terraform State Resources')

        # Conditions
        for i in ['BucketName', 'TableName']:
            template.add_condition(
                "%sOmitted" % i,
                Or(Equals(variables[i].ref, ''),
                   Equals(variables[i].ref, 'undefined')))

        # Resources
        terraformlocktable = template.add_resource(
            dynamodb.Table(
                'TerraformStateTable',
                AttributeDefinitions=[
                    dynamodb.AttributeDefinition(AttributeName='LockID',
                                                 AttributeType='S')
                ],
                KeySchema=[
                    dynamodb.KeySchema(AttributeName='LockID', KeyType='HASH')
                ],
                ProvisionedThroughput=dynamodb.ProvisionedThroughput(
                    ReadCapacityUnits=2, WriteCapacityUnits=2),
                TableName=If('TableNameOmitted', NoValue,
                             variables['TableName'].ref)))
        template.add_output(
            Output('%sName' % terraformlocktable.title,
                   Description='Name of DynamoDB table for Terraform state',
                   Value=terraformlocktable.ref()))

        terraformstatebucket = template.add_resource(
            s3.Bucket(
                'TerraformStateBucket',
                AccessControl=s3.Private,
                BucketName=If('BucketNameOmitted', NoValue,
                              variables['BucketName'].ref),
                LifecycleConfiguration=s3.LifecycleConfiguration(Rules=[
                    s3.LifecycleRule(NoncurrentVersionExpirationInDays=90,
                                     Status='Enabled')
                ]),
                VersioningConfiguration=s3.VersioningConfiguration(
                    Status='Enabled')))
        template.add_output(
            Output('%sName' % terraformstatebucket.title,
                   Description='Name of bucket storing Terraform state',
                   Value=terraformstatebucket.ref()))
        template.add_output(
            Output('%sArn' % terraformstatebucket.title,
                   Description='Arn of bucket storing Terraform state',
                   Value=terraformstatebucket.get_att('Arn')))

        managementpolicy = template.add_resource(
            iam.ManagedPolicy(
                'ManagementPolicy',
                Description='Managed policy for Terraform state management.',
                Path='/',
                PolicyDocument=PolicyDocument(
                    Version='2012-10-17',
                    Statement=[
                        # https://www.terraform.io/docs/backends/types/s3.html#s3-bucket-permissions
                        Statement(
                            Action=[awacs.s3.ListBucket],
                            Effect=Allow,
                            Resource=[terraformstatebucket.get_att('Arn')]),
                        Statement(
                            Action=[awacs.s3.GetObject, awacs.s3.PutObject],
                            Effect=Allow,
                            Resource=[
                                Join('', [
                                    terraformstatebucket.get_att('Arn'), '/*'
                                ])
                            ]),
                        Statement(Action=[
                            awacs.dynamodb.GetItem, awacs.dynamodb.PutItem,
                            awacs.dynamodb.DeleteItem
                        ],
                                  Effect=Allow,
                                  Resource=[terraformlocktable.get_att('Arn')])
                    ])))
        template.add_output(
            Output('PolicyArn',
                   Description='Managed policy Arn',
                   Value=managementpolicy.ref()))
Esempio n. 13
0
from troposphere import dynamodb

dynamodb_table = dynamodb.Table(
    "DynamoDBTable",
    AttributeDefinitions=[
        dynamodb.AttributeDefinition(AttributeName="uuid", AttributeType="S"),
        dynamodb.AttributeDefinition(
            AttributeName="lambda_name", AttributeType="S"
        ),
    ],
    KeySchema=[
        dynamodb.KeySchema(AttributeName="uuid", KeyType="HASH"),
        dynamodb.KeySchema(AttributeName="lambda_name", KeyType="RANGE"),
    ],
    ProvisionedThroughput=dynamodb.ProvisionedThroughput(
        ReadCapacityUnits=2, WriteCapacityUnits=2
    ),
)
Esempio n. 14
0
def executeapi_arn(api_resource, path):
    return Sub(str.join(':', [
        'arn', 'aws', 'execute-api', '${AWS::Region}', '${AWS::AccountId}',
        '${api}/' + path
    ]),
               api=Ref(api_resource))


template = Template()

devices_table = template.add_resource(
    dynamodb.Table(
        'DevicesTable',
        TableName='Devices',
        KeySchema=[
            dynamodb.KeySchema(AttributeName='key', KeyType='HASH'),
        ],
        AttributeDefinitions=[
            dynamodb.AttributeDefinition(AttributeName='key',
                                         AttributeType='S'),
        ],
        BillingMode='PAY_PER_REQUEST',
    ))

restapi = template.add_resource(
    apigateway.RestApi('DevicesApi',
                       Name='DevicesApi',
                       Description='Devices API.',
                       BinaryMediaTypes=['application/vnd.pasbox.octets']))

authorizer_lambda = authorizer.generate(template)