class Fog::AWS::DynamoDB::Real

Public Class Methods

new(options={}) click to toggle source

Initialize connection to DynamoDB

Notes

options parameter must include values for :aws_access_key_id and :aws_secret_access_key in order to create a connection

Examples

ddb = DynamoDB.new(
  :aws_access_key_id => your_aws_access_key_id,
  :aws_secret_access_key => your_aws_secret_access_key
)

Parameters

  • options<~Hash> - config arguments for connection. Defaults to {}.

Returns

  • DynamoDB object with connection to aws

# File lib/fog/aws/dynamodb.rb, line 77
def initialize(options={})
  @use_iam_profile = options[:use_iam_profile]
  #TODO check dynamodb stuff

  setup_credentials(options)
  
  @connection_options     = options[:connection_options] || {}
  
  options[:region] ||= 'us-east-1'
  @host = options[:host] || "dynamodb.#{options[:region]}.amazonaws.com"
  @path       = options[:path]        || '/'
  @persistent = options[:persistent]  || false
  @port       = options[:port]        || '80' #443
  @scheme     = options[:scheme]      || 'http' #'https'
  @connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}#{@path}", @persistent, @connection_options)
end

Public Instance Methods

batch_get_item(request_items) click to toggle source

Get DynamoDB items

Parameters

  • 'request_items'<~Hash>:

    • 'table_name'<~Hash>:

      • 'Keys'<~Array>: array of keys

        • 'HashKeyElement'<~Hash>: info for primary key

          • 'AttributeType'<~String> - type of attribute

          • 'AttributeName'<~String> - name of attribute

        • 'RangeKeyElement'<~Hash>: optional, info for range key

          • 'AttributeType'<~String> - type of attribute

          • 'AttributeName'<~String> - name of attribute

      • 'AttributesToGet'<~Array> - optional attributes to return, defaults to all

Returns

  • response<~Excon::Response>:

    • body<~Hash>:

      • 'Responses'<~Hash>:

        • 'table_name'<~Hash>:

          • 'Items'<~Array> - Matching items

          • 'ConsumedCapacityUnits'<~Float> - Capacity units used in read

      • 'UnprocessedKeys':<~Hash> - tables and keys in excess of per request limit, pass this to subsequent batch get for pseudo-pagination

# File lib/fog/aws/requests/dynamodb/batch_get_item.rb, line 28
def batch_get_item(request_items)
  body = {
    'RequestItems' => request_items
  }

  request(
    :body       => Fog::JSON.encode(body),
    :headers    => {'x-amz-target' => 'DynamoDB_20111205.BatchGetItem'},
    :idempotent => true
  )
end
batch_put_item(request_items) click to toggle source
# File lib/fog/aws/requests/dynamodb/batch_write_item.rb, line 6
def batch_put_item(request_items)
  Fog::Logger.deprecation("batch_put_item is deprecated, use batch_write_item instead")
  batch_write_item(request_items)
end
batch_write_item(request_items) click to toggle source

request_items has form: {“table_name”=>

 [{"PutRequest"=>
   {"Item"=>
     {"hash_key"=>{"N"=>"99"},
      "range_key"=>{"N"=>"99"},
      "attribute"=>{"S"=>"hi"}
      }}}, ... ]}
For more information:
http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/API_BatchWriteItems.html
# File lib/fog/aws/requests/dynamodb/batch_write_item.rb, line 21
def batch_write_item(request_items)
  body = {
    'RequestItems' => request_items
  }

  request(
    :body       => Fog::JSON.encode(body),
    :headers    => {'x-amz-target' => 'DynamoDB_20111205.BatchWriteItem'}
  )
end
create_table(table_name, key_schema, provisioned_throughput) click to toggle source

Create DynamoDB table

Parameters

  • 'table_name'<~String> - name of table to create

  • 'key_schema'<~Hash>:

    • 'HashKeyElement'<~Hash>: info for primary key

      • 'AttributeName'<~String> - name of attribute

      • 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set

    • 'RangeKeyElement'<~Hash>: optional, info for range key

      • 'AttributeName'<~String> - name of attribute

      • 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set

  • 'provisioned_throughput'<~Hash>:

    • 'ReadCapacityUnits'<~Integer> - read capacity for table, in 5..10000

    • 'WriteCapacityUnits'<~Integer> - write capacity for table, in 5..10000

Returns

  • response<~Excon::Response>:

    • body<~Hash>:

      • 'TableDescription'<~Hash>

        • 'CreationDateTime'<~Float> - Unix epoch time of table creation

        • 'KeySchema'<~Hash> - schema for table

          • 'HashKeyElement'<~Hash>: info for primary key

            • 'AttributeName'<~String> - name of attribute

            • 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set

          • 'RangeKeyElement'<~Hash>: optional, info for range key

            • 'AttributeName'<~String> - name of attribute

            • 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set

        • 'ProvisionedThroughput'<~Hash>:

          • 'ReadCapacityUnits'<~Integer> - read capacity for table, in 5..10000

          • 'WriteCapacityUnits'<~Integer> - write capacity for table, in 5..10000

        • 'TableName'<~String> - name of table

        • 'TableStatus'<~String> - status of table

# File lib/fog/aws/requests/dynamodb/create_table.rb, line 38
def create_table(table_name, key_schema, provisioned_throughput)
  body = {
    'KeySchema'             => key_schema,
    'ProvisionedThroughput' => provisioned_throughput,
    'TableName'             => table_name
  }

  request(
    :body       => Fog::JSON.encode(body),
    :headers    => {'x-amz-target' => 'DynamoDB_20111205.CreateTable'},
    :idempotent => true
  )
end
delete_item(table_name, key, options = {}) click to toggle source

Delete DynamoDB item

Parameters

  • 'table_name'<~String> - name of table for item

  • 'key'<~Hash>:

    • 'HashKeyElement'<~Hash>: info for primary key

      • 'AttributeName'<~String> - name of attribute

      • 'AttributeType'<~String> - type of attribute

    • 'RangeKeyElement'<~Hash>: optional, info for range key

      • 'AttributeName'<~String> - name of attribute

      • 'AttributeType'<~String> - type of attribute

  • 'options'<~Hash>:

    • 'Expected'<~Hash>: data to check against

      • 'AttributeName'<~String> - name of attribute

      • 'Value'<~Hash> - a value to check for the value of

      or

      • 'Exists'<~Boolean> - set as false to only allow update if attribute doesn't exist

    • 'ReturnValues'<~String> - data to return in %w{ALL_NEW ALL_OLD NONE UPDATED_NEW UPDATED_OLD}, defaults to NONE

Returns

# File lib/fog/aws/requests/dynamodb/delete_item.rb, line 29
def delete_item(table_name, key, options = {})
  body = {
    'Key'               => key,
    'TableName'         => table_name
  }.merge(options)

  request(
    :body       => Fog::JSON.encode(body),
    :headers    => {'x-amz-target' => 'DynamoDB_20111205.DeleteItem'},
    :idempotent => true
  )
end
delete_table(table_name) click to toggle source

Delete DynamoDB table

Parameters

  • 'table_name'<~String> - name of table to delete

Returns

  • response<~Excon::Response>:

    • body<~Hash>:

      • 'TableDescription'<~Hash>

        • 'KeySchema'<~Hash> - schema for table

          • 'HashKeyElement'<~Hash>: info for primary key

            • 'AttributeName'<~String> - name of attribute

            • 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set

          • 'RangeKeyElement'<~Hash>: optional, info for range key

            • 'AttributeName'<~String> - name of attribute

            • 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set

        • 'ProvisionedThroughput'<~Hash>:

          • 'ReadCapacityUnits'<~Integer> - read capacity for table, in 5..10000

          • 'WriteCapacityUnits'<~Integer> - write capacity for table, in 5..10000

        • 'TableName'<~String> - name of table

        • 'TableStatus'<~String> - status of table

# File lib/fog/aws/requests/dynamodb/delete_table.rb, line 27
def delete_table(table_name)
  body = {
    'TableName' => table_name
  }

  request(
    :body       => Fog::JSON.encode(body),
    :headers    => {'x-amz-target' => 'DynamoDB_20111205.DeleteTable'},
    :idempotent => true
  )
end
describe_table(table_name) click to toggle source

Describe DynamoDB table

Parameters

  • 'table_name'<~String> - name of table to describe

Returns

  • response<~Excon::Response>:

    • body<~Hash>:

      • 'Table'<~Hash>

        • 'CreationDateTime'<~Float> - Unix epoch time of table creation

        • 'KeySchema'<~Hash> - schema for table

          • 'HashKeyElement'<~Hash>: info for primary key

            • 'AttributeName'<~String> - name of attribute

            • 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set

          • 'RangeKeyElement'<~Hash>: optional, info for range key

            • 'AttributeName'<~String> - name of attribute

            • 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set

        • 'ProvisionedThroughput'<~Hash>:

          • 'ReadCapacityUnits'<~Integer> - read capacity for table, in 5..10000

          • 'WriteCapacityUnits'<~Integer> - write capacity for table, in 5..10000

        • 'TableName'<~String> - name of table

        • 'TableSizeBytes'<~Integer> - size of table in bytes

        • 'TableStatus'<~String> - status of table

# File lib/fog/aws/requests/dynamodb/describe_table.rb, line 29
def describe_table(table_name)
  body = {
    'TableName' => table_name
  }

  request(
    :body       => Fog::JSON.encode(body),
    :headers    => {'x-amz-target' => 'DynamoDB_20111205.DescribeTable'},
    :idempotent => true
  )
end
get_item(table_name, key, options = {}) click to toggle source

Get DynamoDB item

Parameters

  • 'table_name'<~String> - name of table for item

  • 'key'<~Hash>:

    • 'HashKeyElement'<~Hash>: info for primary key

      • 'AttributeType'<~String> - type of attribute

      • 'AttributeName'<~String> - name of attribute

    • 'RangeKeyElement'<~Hash>: optional, info for range key

      • 'AttributeType'<~String> - type of attribute

      • 'AttributeName'<~String> - name of attribute

  • 'options'<~Hash>:

    • 'AttributesToGet'<~Array>: list of array names to return, defaults to returning all

    • 'ConsistentRead'<~Boolean>: whether to wait for updates, defaults to false

Returns

  • response<~Excon::Response>:

    • body<~Hash>:

      • 'ConsumedCapacityUnits'<~Float> - Capacity units used in read

      • 'Item':<~Hash>:

        • 'AttributeName'<~Hash>: in form of {“type”:value}

# File lib/fog/aws/requests/dynamodb/get_item.rb, line 27
def get_item(table_name, key, options = {})
  body = {
    'Key'               => key,
    'TableName'         => table_name
  }.merge(options)

  request(
    :body       => Fog::JSON.encode(body),
    :headers    => {'x-amz-target' => 'DynamoDB_20111205.GetItem'},
    :idempotent => true
  )
end
list_tables(options = {}) click to toggle source

List DynamoDB tables

Parameters

  • 'options'<~Hash> - options, defaults to {}

    • 'ExclusiveStartTableName'<~String> - name of table to begin listing with

    • 'Limit'<~Integer> - limit number of tables to return

Returns

  • response<~Excon::Response>:

    • body<~Hash>:

      • 'LastEvaluatedTableName'<~String> - last table name, for pagination

      • 'TableNames'<~Array> - table names

# File lib/fog/aws/requests/dynamodb/list_tables.rb, line 18
def list_tables(options = {})
  request(
    :body       => Fog::JSON.encode(options),
    :headers    => {'x-amz-target' => 'DynamoDB_20111205.ListTables'},
    :idempotent => true
  )
end
put_item(table_name, item, options = {}) click to toggle source

Update DynamoDB item

Parameters

  • 'table_name'<~String> - name of table for item

  • 'item'<~Hash>: data to update, must include primary key

    • 'AttributeName'<~String> - Attribute to update

      • 'Value'<~Hash> - formated as {type => value}

      • 'Action'<~String> - action to take if expects matches, in %w{ADD DELETE PUT}, defaults to PUT

  • 'options'<~Hash>:

    • 'Expected'<~Hash>: data to check against

      • 'AttributeName'<~String> - name of attribute

      • 'Value'<~Hash> - a value to check for the value of

      or

      • 'Exists'<~Boolean> - set as false to only allow update if attribute doesn't exist

    • 'ReturnValues'<~String> - data to return in %w{ALL_NEW ALL_OLD NONE UPDATED_NEW UPDATED_OLD}, defaults to NONE

Returns

# File lib/fog/aws/requests/dynamodb/put_item.rb, line 26
def put_item(table_name, item, options = {})
  body = {
    'Item'      => item,
    'TableName' => table_name
  }.merge(options)

  request(
    :body       => Fog::JSON.encode(body),
    :headers    => {'x-amz-target' => 'DynamoDB_20111205.PutItem'}
  )
end
query(table_name, hash_key, options = {}) click to toggle source

Query DynamoDB items

Parameters

  • 'table_name'<~String> - name of table to query

  • 'hash_key'<~Hash> - hash key to query

  • options<~Hash>:

    • 'AttributesToGet'<~Array> - Array of attributes to get for each item, defaults to all

    • 'ConsistentRead'<~Boolean> - Whether to wait for consistency, defaults to false

    • 'Count'<~Boolean> - If true, returns only a count of such items rather than items themselves, defaults to false

    • 'Limit'<~Integer> - limit of total items to return

    • 'RangeKeyCondition'<~Hash>: value to compare against range key

      • 'AttributeValueList'<~Hash>: one or more values to compare against

      • 'ComparisonOperator'<~String>: comparison operator to use with attribute value list, in %w{BETWEEN BEGINS_WITH EQ LE LT GE GT}

    • 'ScanIndexForward'<~Boolean>: Whether to scan from start or end of index, defaults to start

    • 'ExclusiveStartKey'<~Hash>: Key to start listing from, can be taken from LastEvaluatedKey in response

Returns

  • response<~Excon::Response>:

    • body<~Hash>:

      • 'ConsumedCapacityUnits'<~Integer> - number of capacity units used for query

      • 'Count'<~Integer> - number of items in response

      • 'Items'<~Array> - array of items returned

      • 'LastEvaluatedKey'<~Hash> - last key scanned, can be passed to ExclusiveStartKey for pagination

# File lib/fog/aws/requests/dynamodb/query.rb, line 29
def query(table_name, hash_key, options = {})
  body = {
    'TableName'     => table_name,
    'HashKeyValue'  => hash_key
  }.merge(options)

  request(
    :body     => Fog::JSON.encode(body),
    :headers  => {'x-amz-target' => 'DynamoDB_20111205.Query'}
  )
end
scan(table_name, options = {}) click to toggle source

Scan DynamoDB items

Parameters

  • 'table_name'<~String> - name of table to query

  • options<~Hash>:

    • 'AttributesToGet'<~Array> - Array of attributes to get for each item, defaults to all

    • 'ConsistentRead'<~Boolean> - Whether to wait for consistency, defaults to false

    • 'Count'<~Boolean> - If true, returns only a count of such items rather than items themselves, defaults to false

    • 'Limit'<~Integer> - limit of total items to return

    • 'ScanFilter'<~Hash>: value to compare against

      • attribute_name<~Hash>:

        • 'AttributeValueList'<~Hash>: one or more values to compare against

        • 'ComparisonOperator'<~String>: comparison operator to use with attribute value list, in %w{BETWEEN BEGINS_WITH EQ LE LT GE GT}

    • 'ScanIndexForward'<~Boolean>: Whether to scan from start or end of index, defaults to start

    • 'ExclusiveStartKey'<~Hash>: Key to start listing from, can be taken from LastEvaluatedKey in response

Returns

  • response<~Excon::Response>:

    • body<~Hash>:

      • 'ConsumedCapacityUnits'<~Integer> - number of capacity units used for scan

      • 'Count'<~Integer> - number of items in response

      • 'Items'<~Array> - array of items returned

      • 'LastEvaluatedKey'<~Hash> - last key scanned, can be passed to ExclusiveStartKey for pagination

      • 'ScannedCount'<~Integer> - number of items scanned before applying filters

# File lib/fog/aws/requests/dynamodb/scan.rb, line 30
def scan(table_name, options = {})
  body = {
    'TableName'     => table_name
  }.merge(options)

  request(
    :body     => Fog::JSON.encode(body),
    :headers  => {'x-amz-target' => 'DynamoDB_20111205.Scan'},
    :idempotent => true
  )
end
update_item(table_name, key, attribute_updates, options = {}) click to toggle source

Update DynamoDB item

Parameters

  • 'table_name'<~String> - name of table for item

  • 'key'<~Hash>:

    • 'HashKeyElement'<~Hash>: info for primary key

      • 'AttributeName'<~String> - name of attribute

      • 'AttributeType'<~String> - type of attribute

    • 'RangeKeyElement'<~Hash>: optional, info for range key

      • 'AttributeName'<~String> - name of attribute

      • 'AttributeType'<~String> - type of attribute

  • 'attribute_updates'<~Hash>:

    • 'AttributeName'<~String> - Attribute to update

      • 'Value'<~Hash> - formated as {type => value}

      • 'Action'<~String> - action to take if expects matches, in %w{ADD DELETE PUT}, defaults to PUT

  • 'options'<~Hash>:

    • 'Expected'<~Hash>: data to check against

      • 'AttributeName'<~String> - name of attribute

      • 'Value'<~Hash> - a value to check for the value of

      or

      • 'Exists'<~Boolean> - set as false to only allow update if attribute doesn't exist

    • 'ReturnValues'<~String> - data to return in %w{ALL_NEW ALL_OLD NONE UPDATED_NEW UPDATED_OLD}, defaults to NONE

Returns

# File lib/fog/aws/requests/dynamodb/update_item.rb, line 33
def update_item(table_name, key, attribute_updates, options = {})
  body = {
    'AttributeUpdates'  => attribute_updates,
    'Key'               => key,
    'TableName'         => table_name
  }.merge(options)

  request(
    :body     => Fog::JSON.encode(body),
    :headers  => {'x-amz-target' => 'DynamoDB_20111205.UpdateItem'}
  )
end
update_table(table_name, provisioned_throughput) click to toggle source

Update DynamoDB table throughput

Parameters

  • 'table_name'<~String> - name of table to describe

  • 'provisioned_throughput'<~Hash>:

    • 'ReadCapacityUnits'<~Integer> - read capacity for table, in 5..10000

    • 'WriteCapacityUnits'<~Integer> - write capacity for table, in 5..10000

Returns

  • response<~Excon::Response>:

    • body<~Hash>:

      • 'Table'<~Hash>

        • 'KeySchema'<~Hash> - schema for table

          • 'HashKeyElement'<~Hash>: info for primary key

            • 'AttributeName'<~String> - name of attribute

            • 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set

          • 'RangeKeyElement'<~Hash>: optional, info for range key

            • 'AttributeName'<~String> - name of attribute

            • 'AttributeType'<~String> - type of attribute, in %w{N NS S SS} for number, number set, string, string set

        • 'ProvisionedThroughput'<~Hash>:

          • 'ReadCapacityUnits'<~Integer> - read capacity for table, in 5..10000

          • 'WriteCapacityUnits'<~Integer> - write capacity for table, in 5..10000

        • 'TableName'<~String> - name of table

        • 'TableStatus'<~String> - status of table

# File lib/fog/aws/requests/dynamodb/update_table.rb, line 30
def update_table(table_name, provisioned_throughput)
  body = {
    'ProvisionedThroughput' => provisioned_throughput,
    'TableName'             => table_name
  }

  request(
    :body       => Fog::JSON.encode(body),
    :headers    => {'x-amz-target' => 'DynamoDB_20111205.UpdateTable'},
    :idempotent => true
  )
end

Private Instance Methods

reload() click to toggle source
# File lib/fog/aws/dynamodb.rb, line 116
def reload
  @connection.reset
end
request(params) click to toggle source
# File lib/fog/aws/dynamodb.rb, line 120
def request(params)
  refresh_credentials_if_expired
  idempotent = params.delete(:idempotent)

  headers = {
    'Content-Type'          => 'application/x-amz-json-1.0',
    'x-amz-date'            => Fog::Time.now.to_date_header,
    'x-amz-security-token'  => @aws_session_token
  }.merge(params[:headers])

  headers['x-amzn-authorization']  = signed_authorization_header(params, headers)

  response = @connection.request({
    :body       => params[:body],
    :expects    => 200,
    :headers    => headers,
    :host       => @host,
    :idempotent => idempotent,
    :method     => 'POST',
  })

  unless response.body.empty?
    response.body = Fog::JSON.decode(response.body)
  end

  response
end
setup_credentials(options) click to toggle source
# File lib/fog/aws/dynamodb.rb, line 96
def setup_credentials(options)
  if options[:aws_session_token]
    @aws_access_key_id      = options[:aws_access_key_id]
    @aws_secret_access_key  = options[:aws_secret_access_key]
    @aws_session_token      = options[:aws_session_token]
    @aws_credentials_expire_at = options[:aws_credentials_expire_at]
  else
    sts = Fog::AWS::STS.new(
      :aws_access_key_id      => options[:aws_access_key_id],
      :aws_secret_access_key  => options[:aws_secret_access_key]
    )
    session_data = sts.get_session_token.body

    @aws_access_key_id      = session_data['AccessKeyId']
    @aws_secret_access_key  = session_data['SecretAccessKey']
    @aws_session_token      = session_data['SessionToken']
  end
  @hmac       = Fog::HMAC.new('sha256', @aws_secret_access_key)
end
signed_authorization_header(params, headers) click to toggle source
# File lib/fog/aws/dynamodb.rb, line 148
def signed_authorization_header(params, headers)
  string_to_sign = "POST\n/\n\nhost:#{@host}:#{@port}\n"

  amz_headers, canonical_amz_headers = {}, ''
  for key, value in headers
    if key[0..5] == 'x-amz-'
      amz_headers[key] = value
    end
  end
  amz_headers = amz_headers.sort {|x, y| x[0] <=> y[0]}
  for key, value in amz_headers
    canonical_amz_headers << "#{key}:#{value}\n"
  end
  string_to_sign << canonical_amz_headers
  string_to_sign << "\n"
  string_to_sign << (params[:body] || '')

  string_to_sign = OpenSSL::Digest::SHA256.digest(string_to_sign)

  signed_string = @hmac.sign(string_to_sign)
  signature = Base64.encode64(signed_string).chomp!

  "AWS3 AWSAccessKeyId=#{@aws_access_key_id},Algorithm=HmacSHA256,Signature=#{signature}"
end