aws

module:aws

Description:
  • AWS API interface, uses API directly for each service, JSON is returned as is but XML repsonses are converted using fast-xml-parser into objects.

    Supports local AWS SDK credentials files and sessions

    When AWS environment is detected the module:app.env will be filled automatically.

Source:
Example
# aws login

# bin/bksh -aws-sdk-profile default

> aws.queryS3("", "/", (err, rc) => {
    console.log(rc?.ListAllMyBucketsResult?.Buckets)
})

Members

(static) args :Array.<ConfigOptions>

Source:
Default Value:
  • [
      {
        "name": "key",
        "descr": "AWS access key"
      },
      {
        "name": "secret",
        "descr": "AWS access secret"
      },
      {
        "name": "token",
        "descr": "AWS security token"
      },
      {
        "name": "region",
        "descr": "AWS region",
        "pass": 1
      },
      {
        "name": "zone",
        "descr": "AWS availability zone"
      },
      {
        "name": "meta",
        "type": "bool",
        "descr": "Retrieve instance metadata, 0 to disable"
      },
      {
        "name": "sdk-profile",
        "descr": "AWS SDK profile to use when reading credentials file"
      },
      {
        "name": "sns-app-arn",
        "descr": "SNS Platform application ARN to be used for push notifications"
      },
      {
        "name": "key-name",
        "descr": "AWS instance keypair name for remote job instances or other AWS commands"
      },
      {
        "name": "target-group",
        "descr": "AWS ELB target group to be registered with on start up or other AWS commands"
      },
      {
        "name": "elastic-ip",
        "descr": "AWS Elastic IP to be associated on start"
      },
      {
        "name": "host-name",
        "type": "list",
        "descr": "List of hosts to update in Route54 zone with the current private IP address, hosts must be in FQDN format, supports @..@ app.env placeholders"
      },
      {
        "name": "iam-profile",
        "descr": "IAM instance profile name for instances or commands"
      },
      {
        "name": "image-id",
        "descr": "AWS image id to be used for instances or commands"
      },
      {
        "name": "subnet-id",
        "descr": "AWS subnet id to be used for instances or commands"
      },
      {
        "name": "vpc-id",
        "descr": "AWS VPC id to be used for instances or commands"
      },
      {
        "name": "group-id",
        "array": 1,
        "descr": "AWS security group(s) to be used for instances or commands"
      },
      {
        "name": "public-ip",
        "type": "bool",
        "descr": "AWS public IP option for instances or commands"
      },
      {
        "name": "ecs-cluster",
        "descr": "AWS ECS cluster to use as default"
      },
      {
        "name": "instance-type",
        "descr": "AWS instance type to launch on demand"
      },
      {
        "name": "metadata-options",
        "type": "list",
        "descr": "Default instance metadata options"
      },
      {
        "name": "account-id",
        "descr": "AWS account id if not running on an instance"
      },
      {
        "name": "eni-id",
        "type": "list",
        "descr": "AWS Elastic Network Interfaces to attach on start, format is: eni[:index],eni..."
      },
      {
        "name": "config-parameters",
        "descr": "Prefix for AWS Systems Manager parameters to load and parse as config before initializing the database pools",
        "example": "/bkjs/config/"
      },
      {
        "name": "config-secrets",
        "type": "list",
        "descr": "AWS Secrets Manager filters to load and parse as config before initializing the database pools, supports @..@ app.env placeholders in filters",
        "example": "production,production-@tag@,production-@role@"
      },
      {
        "name": "config-s3-file",
        "descr": "S3 url for config file to download on start, may include @placeholders@ to refer properties from app.env"
      },
      {
        "name": "config-s3-interval",
        "type": "int",
        "descr": "Load S3 config file every specified interval in minites"
      }
    ]

Methods

(async, static) aqueryEC2(action, obj, optionsopt) → {Promise.<object>}

Description:
Source:
Parameters:
Name Type Attributes Description
action string

EC2 API action

obj object

API-specific request parameters

options object <optional>

request options

Returns:
Type Description
Promise.<object>
  • { err, data, request }

(async, static) aqueryECS(action, obj, optionsopt) → {Promise.<object>}

Description:
Source:
Parameters:
Name Type Attributes Description
action string

ECS API action

obj object

API-specific request parameters

options object <optional>

request options

Returns:
Type Description
Promise.<object>
  • { err, data, request }

(async, static) aqueryEndpoint() → {Promise(object)}

Description:
Source:
Returns:
Type Description
Promise(object)
  • { err, data, request }

(async, static) aqueryIAM(action, obj, optionsopt) → {Promise.<object>}

Description:
Source:
Parameters:
Name Type Attributes Description
action string

IAM API action

obj object

API-specific request parameters

options object <optional>

request options

Returns:
Type Description
Promise.<object>
  • { err, data, request }

(async, static) aqueryS3() → {object}

Description:
Source:
Returns:
Type Description
object
  • result as an object { ok, err, status, data, obj, request } compatible with module:lib.afetch

(async, static) aquerySQS(action, obj, optionsopt) → {Promise.<object>}

Description:
Source:
Parameters:
Name Type Attributes Description
action string

SQS API action

obj object

API-specific request parameters

options object <optional>

request options

Returns:
Type Description
Promise.<object>
  • { err, data, request }

(async, static) aquerySTS(action, obj, optionsopt) → {Promise.<object>}

Description:
Source:
Parameters:
Name Type Attributes Description
action string

STS API action

obj object

API-specific request parameters

options object <optional>

request options

Returns:
Type Description
Promise.<object>
  • { err, data, request }

(async, static) aqueryService() → {Promise(object)}

Description:
Source:
Returns:
Type Description
Promise(object)
  • { err, data, request }

(async, static) aqueryService(callback, action, obj, optionsopt) → {Promise(object)}

Description:
  • Generic async wrapper around sync queryXXXX methods during runtime, wrap inside a Promise

Source:
Parameters:
Name Type Attributes Description
callback function()

sync method to wrap inside a Promise, it runs in aws module context

action string

API specific action

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryEndpoint or module:aws.queryService (region, retryCount, retryTimeout, endpoint...)

Returns:
Type Description
Promise(object)
  • { err, data, request }
Example
// Not all query methods have their async version so this is a runtime solution
await aws.aqueryMethod(aws.queryECR, "DescribeImages");

await aws.aqueryMethod(aws.querySecrets, "GetSecretValue", { secretId: "my/secret" });

(static) batchGetSecretValue(optionsopt, callback)

Description:
  • Return a batch of secret values from AWS Secrets Manager (handles pagination).

Source:
Parameters:
Name Type Attributes Description
options object <optional>
Properties
Name Type Attributes Description
filters Array.<string> | Array.<object> <optional>

filters, each a string or { key, values } object

ids Array.<string> <optional>

specific secret ids to retrieve

callback function()

(err, list)

(static) bedrockConverse(model, query, optionsopt, callback)

Description:
  • Send converse request to Bedrock

Source:
Parameters:
Name Type Attributes Description
model string
query object

native Bedrock API request body

Properties
Name Type Attributes Description
prompt string <optional>

a user prompt to send

system string <optional>

system prompt

maxTokens number <optional>

max token limit

temperature number <optional>

randomness level

options object <optional>
Properties
Name Type Attributes Description
region string <optional>
callback function()

(static) bedrockInvoke(model, body, optionsopt, callback)

Description:
  • Send invoke request to Bedrock, see https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html

Source:
Parameters:
Name Type Attributes Description
model string
body object

Invoke API inferenece body

options object <optional>
Properties
Name Type Attributes Description
region string <optional>
headers object <optional>
callback function()

(static) configure(options, callback)

Description:
  • Module initialization hook. Detects the AWS environment, retrieves EC2/ECS instance metadata and credentials, reads local SDK credentials for the configured profile and loads remote config (S3/SSM/Secrets Manager).

Source:
Parameters:
Name Type Description
options object
callback function()

(static) configureJob()

Description:
  • Process AWS alarms and state notifications, if such a job is pulled from SQS queue it is handled here and never get to the jobs. SNS alarms or EventBridge events must use a SQS qeue as the target.

Source:

(static) configureServer(options, callback)

Description:
  • Primary server startup hook, only runs on an AWS instance. Updates Route53 host records, associates the configured Elastic IP, attaches configured ENIs and registers the instance with the configured ELB target group.

Source:
Parameters:
Name Type Description
options object
callback function()

(static) cwGetMetricData(options, callback)

Description:
  • Return collected metric statistics for one or more metrics/expressions.

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Attributes Default Description
start_time number <optional>

starting timestamp

end_time number <optional>

ending timestamp

period number <optional>
60

aggregation period in seconds, if < 0 it is set dynamically for the range

age number <optional>

ms to go back if start_time is not given (default 30 secs)

namespace string <optional>
AWS/EC2

default namespace for all metrics

desc boolean <optional>

return data in descending order

timeout number <optional>

stop paginating after this many ms

zeros boolean <optional>

include series whose values sum to zero

metrics Array.<object>

metrics to retrieve, each item: { name, stat, dimensions:{key:val}, [id], [namespace], [label], [hidden], [expression] }

callback function()

(err, rc) where rc is { start, end, period, data:[{ id, label, timestamps:[], data:[] }], errors:[] }

Example
aws.cwGetMetricData({ age: 300000, metrics: [{ name: "NetworkOut", label: "Traffic", stat: "Average", dimensions: { InstanceId: "i-1234567" } } ] }, lib.log)

(static) cwListMetrics(optionsopt, callback)

Description:
  • Return the list of CloudWatch metrics matching the query.

Source:
Parameters:
Name Type Attributes Description
options object <optional>
Properties
Name Type Attributes Description
name string <optional>

a metric name to filter by

namespace string <optional>

limit by namespace, e.g. AWS/EC2, AWS/DynamoDB, AWS/ELB, AWS/RDS, AWS/SQS...

dimensions object <optional>

dimensions filter as name:value

callback function()

(err, rows) where rows is a list of metric descriptors

(static) cwPutLogEvents(options, callback)

Description:
  • Store events in CloudWatch Logs.

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Attributes Default Description
name string

log group name, required

stream string

log stream name, required

events Array.<string> | Array.<object>

list of strings or objects { timestamp, message }, required

tm_pos number <optional>
0

position in the message where the timestamp starts (used to auto-derive timestamp)

tm_sep string <optional>
' '

separator after the timestamp

callback function()

(static) cwPutMetricAlarm(options, callback)

Description:
  • Creates or updates an alarm and associates it with the specified Amazon CloudWatch metric.

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Attributes Default Description
name string <optional>

alarm name, if not specified metric name and dimensions are used to generate one

metric string <optional>
CPUUtilization

metric name

namespace string <optional>
AWS/EC2

AWS namespace

op string <optional>
>=

comparison operator, one of >= | <= | > | < or the native names GreaterThanOrEqualToThreshold | GreaterThanThreshold | LessThanThreshold | LessThanOrEqualToThreshold

statistic string <optional>
Average

one of SampleCount | Average | Sum | Minimum | Maximum

period number <optional>
60

collection period in seconds

evaluationPeriods number <optional>
15

number of periods over which data is compared to the threshold

threshold number <optional>
90

value the statistic is compared against

ok string | Array.<string> <optional>

ARN(s) to notify on OK state

alarm string | Array.<string> <optional>

ARN(s) to notify on ALARM state

insufficient_data string | Array.<string> <optional>

ARN(s) to notify on INSUFFICIENT_DATA state

dimensions object <optional>

dimensions for the alarm's metric as name:value

callback function()

(static) cwPutMetricData(namespace, data, optionsopt, callback)

Description:
  • Publishes metric data points to Amazon CloudWatch, batching up to 20 metrics per request.

Source:
Parameters:
Name Type Attributes Description
namespace string

custom namespace, cannot start with AWS

data object

an object with metric data keyed by metric name, each value may be:

  • a number/string: the metric value
  • { value: Number, dimension1: name1, ... }: value plus dimensions
  • { value: [min, max, sum, sampleCount], dimension1: ... }: statistic set plus dimensions
options object <optional>
Properties
Name Type Attributes Description
storageResolution number <optional>

1 to use 1 second high resolution

timestamp number <optional>

ms timestamp to use instead of the current time

callback function()

(static) cwlFilterLogEvents(options, callback)

Description:
  • Lists log events from the specified log group, optionally filtered by pattern, time range and stream.

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Attributes Default Description
name string

log group name, required

count number <optional>
10000

how many events to retrieve per batch

limit number <optional>

total number of events to return

filter string <optional>

CloudWatch Logs filter pattern

stime number <optional>

start time in ms

etime number <optional>

end time in ms

prefix string <optional>

log stream name prefix pattern

names Array.<string> <optional>

list of log streams to filter

token string <optional>

pagination token to start with

delay number <optional>

delay in ms between batches

timeout number <optional>

how long to keep reading/waiting, ms

callback function()

(err, data) where data is { events:[], ... }

(static) ddbBatchExecuteStatement(items, optionsopt, callback)

Description:
  • Run a batch of independent PartiQL statements against DynamoDB.

Source:
Parameters:
Name Type Attributes Description
items Array.<string> | Array.<object>

statements as strings or { text, params, consistent } objects

options object <optional>
callback function()

(err, rc) where each rc.Responses[].Item is converted

(static) ddbBatchGetItem(items, optionsopt, callback)

Description:
  • Retrieve multiple items across tables in one BatchGetItem request.

Source:
Parameters:
Name Type Attributes Description
items object

map of table name to { keys: [key,...], [select], [consistent] }

options object <optional>

any capitalized native property is passed through

callback function()

(err, rc) where rc.Responses is keyed by the logical table names

Example
aws.ddbBatchGetItem({ users: { keys: [{ id: 1, name: "john" }], select: ['name','id'], consistent: true } })

(static) ddbBatchWriteItem(items, optionsopt, callback)

Description:
  • Put and/or delete multiple items across tables in one BatchWriteItem request.

Source:
Parameters:
Name Type Attributes Description
items object

map of table name to a list of operations, each { put|add: item } or { del: keys }

options object <optional>

any capitalized native property is passed through

callback function()
Example
aws.ddbBatchWriteItem({ table: [ { put: { id: 1, name: "tt" } }, { del: { id: 2 } } ] })

(static) ddbCreateTable(options)

Description:
  • Create a table

Source:
Parameters:
Name Type Description
options object

may contain any valid native property if it starts with capital letter and the following:

Properties
Name Type Attributes Description
waitTimeout number <optional>

number of milliseconds to wait for ACTIVE status

waitDelay number <optional>

how often to pool for table status, default is 250ms

attrs Array.<string> | object <optional>

can be an array in native DDB JSON format or an object with name:type properties, type is one of S, N, NN, NS, BS, if not provided attributes from keys will be added with type S

keys Array.<string> <optional>

is an array of column ids used for the primary key or a string with the hash key. if omitted, the first attribute will be used for the primary key

local object <optional>

an object with each property for a local secondary index name, special properties are: projection, readCapacity, writeCapacity, other properties are key schema, first is HASH, second is RANGE

global object <optional>

an object for global secondary indexes, same format as for local indexes

readCapacity number <optional>

read capacity units for provisioned throughput

writeCapacity number <optional>

write capacity units

onDemand boolean <optional>

billing mode, auto provision capacity and pay per request, if no read/write capacity is configured on-demand is the default

stream boolean <optional>

enable stream support

Example
aws.ddbCreateTable('users',
                   {
                       keys: ["id", "name"],
                       attrs: { id: 'S', name: 'S' },
                       local: {
                           mtime: {
                               mtime: "N",
                               projection: "ALL",
                           }
                       },
                       global: {
                           name: {
                              name: 'N',
                              projection: ['name','gender'],
                              readCapacity: 5,
                           }
                       },
                       stream: "NEW_IMAGE",
                       readCapacity: 10,
                       writeCapacity: 10
});

(static) ddbDeleteItem(name, keys, optionsopt, callback)

Description:
  • Delete an item from a table.

Source:
Parameters:
Name Type Attributes Description
name string

table name

keys object

primary key attributes name:value (hash/range)

options object <optional>

any capitalized native property is passed through, plus:

Properties
Name Type Attributes Description
query object <optional>

condition columns as in module:aws.ddbPutItem

expr string <optional>

raw ConditionExpression

values object <optional>

ExpressionAttributeValues map

names object <optional>

ExpressionAttributeNames map

returning * <optional>

any value returns the old item (ALL_OLD)

callback function()

(err, rc) where rc.Item is the converted returned attributes

Example
ddbDeleteItem("users", { id: 1, name: "john" }, {})

(static) ddbDeleteTable(name, optionsopt, callback)

Description:
  • Delete a table. By default the callback fires only after the table is fully deleted.

Source:
Parameters:
Name Type Attributes Description
name string

table name

options object <optional>
Properties
Name Type Attributes Description
nowait boolean <optional>

return immediately instead of waiting for deletion

waitTimeout number <optional>

how long to wait in ms for deletion

callback function()

(static) ddbDescribeTable(name, optionsopt, callback)

Description:
  • Return a table's definition and parameters.

Source:
Parameters:
Name Type Attributes Description
name string

table name

options object <optional>
callback function()

(err, rc) where rc.Table holds AttributeDefinitions, KeySchema, etc.

(static) ddbDescribeTimeToLive(name, optionsopt, callback)

Description:
  • Return the status of the Time-To-Live attribute for a table.

Source:
Parameters:
Name Type Attributes Description
name string

table name

options object <optional>
callback function()

(err, rc)

(static) ddbExecuteStatement(text, optionsopt, callback)

Description:
  • Run a single PartiQL statement against DynamoDB.

Source:
Parameters:
Name Type Attributes Description
text string

the PartiQL statement

options object <optional>
Properties
Name Type Attributes Description
consistent boolean <optional>

use a strongly consistent read

start string <optional>

pagination token (NextToken)

params Array.<object> <optional>

positional parameters for the statement

callback function()

(err, rc) where rc.Items is the converted result set

(static) ddbExecuteTransaction(items, optionsopt, callback)

Description:
  • Run multiple PartiQL statements in a single DynamoDB transaction.

Source:
Parameters:
Name Type Attributes Description
items Array.<string> | Array.<object>

statements as strings or { text, params } objects

options object <optional>
Properties
Name Type Attributes Description
start string <optional>

idempotency token (ClientRequestToken)

callback function()

(err, rc) where rc.Responses is the converted result

(static) ddbExportTableToPointInTime(query, optionsopt, callback)

Description:
  • Export a DynamoDB table to S3, as a full or incremental point-in-time export.

Source:
Parameters:
Name Type Attributes Description
query object
Properties
Name Type Attributes Description
table string

table name (mapped via ddbTableMap) or full table ARN

bucket string

destination S3 bucket

prefix string <optional>

S3 key prefix

incr boolean <optional>

perform an incremental export instead of a full export

stime number | string <optional>

incremental export start time

etime number | string <optional>

incremental export end time

new boolean <optional>

for incremental exports use NEW_IMAGE only (default NEW_AND_OLD_IMAGES)

options object <optional>
Properties
Name Type Attributes Description
token string <optional>

client idempotency token

callback function()

(static) ddbGetItem(name, keys, optionsopt, callback)

Description:
  • Retrieve one item by primary key.

Source:
Parameters:
Name Type Attributes Description
name string

table name

keys object

primary key attributes name:value

options object <optional>

any capitalized native property is passed through, plus:

Properties
Name Type Attributes Description
select string | Array.<string> <optional>

columns to return (default all)

projection string <optional>

raw ProjectionExpression

consistent boolean <optional>

use a strongly consistent read

names object <optional>

ExpressionAttributeNames map

callback function()

(err, rc) where rc.Item is the converted item or null

Example
ddbGetItem("users", { id: 1, name: "john" }, { select: 'id,name' })

(static) ddbListTables(optionsopt, callback)

Description:
  • Return the list of tables (handles pagination).

Source:
Parameters:
Name Type Attributes Description
options object <optional>
callback function()

(err, rc) where rc is { TableNames: [name, ...] }

(static) ddbPutItem(name, item, optionsopt, callback)

Description:
  • Put (create or replace) an item; value types are inferred from the native JS types.

Source:
Parameters:
Name Type Attributes Description
name string

table name

item object

the item to store

options object <optional>

any capitalized native property is passed through, plus:

Properties
Name Type Attributes Description
query object <optional>

condition columns; value null means the attribute must not exist, any other value is compared for equality

expr string <optional>

raw ConditionExpression

values object <optional>

ExpressionAttributeValues map

names object <optional>

ExpressionAttributeNames map

returning * <optional>

any value returns the old item (ALL_OLD)

callback function()

(err, rc) where rc.Item is the converted returned attributes

Example
ddbPutItem("users", { id: 1, name: "john", mtime: 11233434 }, { query: { name: null } })

(static) ddbQueryTable(name, condition, optionsopt, callback)

Description:
  • Query a table and return all matching items.

Source:
Parameters:
Name Type Attributes Description
name string

table name

condition object | string

name:value pairs (EQ by default) or a raw KeyConditionExpression string

options object <optional>

any capitalized native property is passed through, plus: - start - starting primary key for pagination (string/number hash or {hash, range} object) - consistent - use a strongly consistent read - select - list of attributes to return - total - return only the count of matching records - count - limit the number of records - desc - descending order - sort - index name to query (indexes named after their key column) - ops - per-attribute comparison operators when other than EQ - keys - list of primary key columns, if there are other properties in the condition then they will be put into FilterExpression instead of KeyConditionExpression. If keys are absent, all properties in the condition are treated as primary keys. - projection - projection expression - values - an object with values map to be used for in the update and/or condition expressions, to be used for ExpressionAttributeValues parameters - names - an object with a map to be used for attribute names in condition and update expressions, to be used for ExpressionAttributeNames parameter - expr - filtering expression

callback function()

(err, rc) where rc.Items is the converted result set

Example
aws.ddbQueryTable("users", { id: 1, name: "john" }, { select: 'id,name', ops: { name: 'gt' } })
aws.ddbQueryTable("users", { id: 1, name: "john", status: "ok" }, { keys: ["id"], select: 'id,name', ops: { name: 'gt' } })
aws.ddbQueryTable("users", { id: 1 }, { expr: "status=:s", values: { s: "status" } })

(static) ddbRetryOnError() → {boolean}

Description:
  • DynamoDB retry predicate, called in the context of a request; retries on throttling/internal errors.

Source:
Returns:
Type Description
boolean

true if the request should be retried

(static) ddbScanTable(name, condition, optionsopt, callback)

Description:
  • Scan a table and return all matching items.

Source:
Parameters:
Name Type Attributes Description
name string

table name

condition object | string

name:value pairs or a raw FilterExpression string

options object <optional>

any capitalized native property is passed through, plus:

Properties
Name Type Attributes Description
start object | string | number <optional>

starting primary key for pagination

ops object <optional>

per-attribute comparison operators when other than EQ

projection string <optional>

raw ProjectionExpression

select string | Array.<string> <optional>

attributes to return

sort string <optional>

index name to scan

consistent boolean <optional>

use a strongly consistent read

count number <optional>

limit the number of records

total boolean <optional>

return only the count of matching records

values object <optional>

ExpressionAttributeValues map

names object <optional>

ExpressionAttributeNames map

callback function()

(err, rc) where rc.Items is the converted result set

Example
aws.ddbScanTable("users", { id: 1, name: 'a' }, { ops: { name: 'gt' }})
         aws.ddbScanTable("users", "id=:id AND name=:name", { values: { id: 1, name: 'a' } });

(static) ddbSigner()

Description:
  • DynamoDB request signer, called in the context of an HTTP request to apply Signature V4 headers.

Source:

(static) ddbTable(name) → {string}

Description:
  • Resolve a logical table name to its real name using aws.ddbTableMap.

Source:
Parameters:
Name Type Description
name string

logical table name

Returns:
Type Description
string

mapped table name or the name itself

(static) ddbTransactWriteItems(items, optionsopt, callback)

Description:
  • Perform multiple write operations in one transaction; any failure rolls everything back.

Source:
Parameters:
Name Type Attributes Description
items Array.<object>

list of operations, each { op, table, keys, query, options } where op is one of put/add, update/incr, del, check; query/keys/options follow the corresponding ddb item methods

options object <optional>

any capitalized native property is passed through

callback function()
Example
aws.ddbTransactWriteItems([
           { op: "put", table: "table-name", query: { id: 1, name: "tt" } },
           { op: "del", table: "table-name", query: { id: 2 } },
           { op: "update", table: "table-name", keys: { id: 1 }, query: { name: "test" }, options: { query: { status: "ok" } } },
           { op: "check", table: "table-name", query: { id: 1 }, options: { query: { status: "ok" } } }
         ])

(static) ddbUpdateItem(name, keys, item, optionsopt, callback)

Description:
  • Update an item.

Source:
Parameters:
Name Type Attributes Description
name string

table name

keys object

primary key attributes name:value

item object | string

attributes to update (number/string/array = set/add, null/empty = delete) or a raw UpdateExpression string

options object <optional>

any capitalized native property is passed through, plus:

Properties
Name Type Attributes Description
ops object <optional>

per-attribute operators: set, remove, unset, delete, incr, add, append, prepend, not_exists

query object <optional>

condition columns (null = attribute absent), operator taken from options.ops

expr string <optional>

raw ConditionExpression

values object <optional>

ExpressionAttributeValues map

names object <optional>

ExpressionAttributeNames map

returning string <optional>

*/new=ALL_NEW, old=ALL_OLD, updated=UPDATED_NEW, old_updated=UPDATED_OLD

callback function()

(err, rc) where rc.Item is the converted returned attributes

Example
ddbUpdateItem("users", { id: 1, name: "john" }, { gender: 'male', icons: '1.png' }, { ops: { icons: 'add' }, query: { id: 1 }, returning: "*" })

(static) ddbUpdateTable(options, callback)

Description:
  • Update tables provisioned throughput settings, options is used instead of table name so this call can be used directly in the cron jobs to adjust provisionined throughput on demand.

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Attributes Description
name string

table name

readCapacity number <optional>

and writeCapacity - new povisioned throughtput settings, both must be specified

stream null | string <optional>

null to disable or one of the NEW_IMAGE | OLD_IMAGE | NEW_AND_OLD_IMAGES | KEYS_ONLY

add object <optional>

an object with indexes to create { hash, range, projections, readCapacity, writeCapacity }

del object <optional>

delete a global secondary index by name, a string or a list with multiple indexes

update object <optional>

an object with indexes to update

waitTimeout number <optional>

how long to wait in ms until the table is active again

onDemand boolean <optional>

true to switch to pat per request mode, false to switch to provisioning mode

callback function()
Examples
aws.ddbUpdateTable({ name: "users", add: { name_id: { name: "S", id: 'N', readCapacity: 20, writeCapacity: 20, projection: ["mtime","email"] } })
aws.ddbUpdateTable({ name: "users", add: { name: { name: "S", readCapacity: 20, writeCapacity: 20, projection: "ALL" } })
aws.ddbUpdateTable({ name: "users", del: "name" })
aws.ddbUpdateTable({ name: "users", update: { name: { readCapacity: 10, writeCapacity: 10 } })
of crontab job in etc/crontab:

[
  { "cron": "0 0 1 * * *", "job": { "aws.ddbUpdateTable": { "name": "bk_user", "readCapacity": 1000, "writeCapacity": 1000 } } },
  { "cron": "0 0 6 * * *", "job": { "aws.ddbUpdateTable": { "name": "bk_user", "readCapacity": 2000, "writeCapacity": 2000 } } }
]

(static) ddbUpdateTimeToLive(options, callback)

Description:
  • Enable or disable the Time-To-Live attribute for a table.

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Description
name string

table name

attribute string

the TTL attribute name

enabled boolean

enable or disable TTL

callback function()

(static) ddbWaitForTable(name, item, options, callback)

Description:
  • Wait until a table leaves the given waitStatus state or the timeout expires. If waitTimeout is not set the callback fires immediately.

Source:
Parameters:
Name Type Description
name string

table name

item object

the response item from the originating create/update/delete call

options object
Properties
Name Type Attributes Default Description
waitStatus string <optional>

status to keep waiting while equal to (e.g. CREATING, UPDATING, DELETING)

waitTimeout number <optional>

how long to wait in ms

waitDelay number <optional>
1000

how often in ms to poll for status

callback function()

(err, item)

(static) ec2AfterRunInstances(options, callback)

Description:
  • Perform post-launch tasks for instances started by module:aws.ec2RunInstances: wait for the running state, assign Name/tags, register with ELB target groups, associate an Elastic IP and create CloudWatch alarms.

Source:
Parameters:
Name Type Description
options object

the info context produced by module:aws.ec2RunInstances

callback function()

(static) ec2AssociateAddress(instanceId, elasticIp, optionsopt, callback)

Description:
  • Associate an Elastic IP with an instance, reassociating if the EIP is already taken.

Source:
Parameters:
Name Type Attributes Description
instanceId string

the instance id

elasticIp string

the Elastic IP public address

options object <optional>
Properties
Name Type Attributes Description
subnetId string <optional>

required for VPC instances; the allocation id is looked up automatically

AllocationId string <optional>

use a known allocation id and skip the lookup

callback function()

(static) ec2AttachNetworkInterface(eniId, instance, optionsopt, callback)

Description:
  • Attach the given ENIs to an instance (detaching first if already attached elsewhere).

Source:
Parameters:
Name Type Attributes Description
eniId Array.<string>

list of ENI ids, each optionally as eni-id:index where index is the device index

instance object

target instance object (must contain instanceId and subnetId)

options object <optional>
callback function()

(static) ec2CreateImage(optionsopt, callback)

Description:
  • Create an EBS-backed AMI from the given instance or the current running instance.

Source:
Parameters:
Name Type Attributes Description
options object <optional>
Properties
Name Type Attributes Description
instanceId string <optional>

source instance id, defaults to the current instance when on AWS

name string <optional>

image name, defaults to the app version

prefix string <optional>

prefix prepended to the image name

descr string <optional>

image description

reboot boolean <optional>

allow reboot during image creation (default is no reboot)

noreboot boolean <optional>

explicitly disable reboot

callback function()

(static) ec2CreateTags(id, name, optionsopt, callback)

Description:
  • Create tags for a resource.

Source:
Parameters:
Name Type Attributes Description
id string

resource id, e.g. instance id

name string | Array.<string> | object

a string (sets the Name tag), an array of [key, value, ...] pairs, or an object of key:value tags

options object <optional>
Properties
Name Type Attributes Description
tags object <optional>

additional tags as key:value

callback function()
Example
aws.ec2CreateTags("i-1234", "My Instance", { tags: { tag2: "val2", tag3: "val3" } })
aws.ec2CreateTags("i-1234", { tag2: "val2", tag3: "val3" })
aws.ec2CreateTags("i-1234", [ "tag2", "val2", "tag3", "val3" ])

(static) ec2DeregisterImage(ami_id, optionsopt, callback)

Description:
  • Deregister an AMI by id, optionally deleting its snapshots.

Source:
Parameters:
Name Type Attributes Description
ami_id string

the AMI id

options object <optional>
Properties
Name Type Attributes Description
snapshots boolean <optional>

also delete all EBS snapshots associated with the image

callback function()

(static) ec2DescribeInstances(optionsopt, callback)

Description:
  • Describe instances according to the query filters, returns a list of instances.

Source:
Parameters:
Name Type Attributes Description
options object <optional>
Properties
Name Type Attributes Description
vpcId string <optional>

VPC to get instances from

instanceId string | Array.<string> <optional>

restrict to specific instance id(s)

tagName string | Array.<string> <optional>

filter by Name tag value(s)

tagKey string | Array.<string> <optional>

filter by tag key(s)

groupName string | Array.<string> <optional>

filter by security group name(s)

stateName string | Array.<string> <optional>

filter by instance state(s)

filters object <optional>

additional raw EC2 filters as name:value(s)

callback function()

(err, list, nextToken)

(static) ec2DescribeSecurityGroups(optionsopt, callback)

Description:
  • Describe EC2 security groups and return the list to the callback.

Source:
Parameters:
Name Type Attributes Description
options object <optional>
Properties
Name Type Attributes Description
vpcId string <optional>

limit to a VPC, defaults to aws.vpcId

name string | Array.<string> <optional>

filter by group name(s)

filter RegExp <optional>

regexp to further filter groups by name

callback function()

(err, groups)

(static) ec2DescribeSubnets(optionsopt, callback)

Description:
  • Describe VPC subnets and return the list to the callback.

Source:
Parameters:
Name Type Attributes Description
options object <optional>
Properties
Name Type Attributes Description
vpcId string <optional>

limit to a VPC, defaults to aws.vpcId

zone string <optional>

filter by availability zone

subnetId string | Array.<string> <optional>

specific subnet id(s)

filter RegExp <optional>

regexp to filter subnets by Name tag

callback function()

(err, subnets)

(static) ec2PrepareInstance(obj) → {object}

Description:
  • Normalize a raw EC2 instance object: flatten tagSet into tags, extract the name from the Name tag and the availabilityZone from placement. Returns the same object.

Source:
Parameters:
Name Type Description
obj object

raw instance object from an EC2 response

Returns:
Type Description
object

the augmented instance object

(static) ec2RunInstances(options, callback)

Description:
  • Run AWS EC2 instances. Supports all native EC2 parameters when passed capitalized in options, plus the simplified options below. The callback receives (err, rc, info) where info describes the launched instances and post-launch tasks.

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Attributes Default Description
min number <optional>
1

minimum number of instances to run

max number <optional>
1

maximum number of instances to run

count number <optional>

shortcut to set both min and max

imageId string <optional>

AMI id, defaults to aws.imageId or options.ImageId

instanceType string <optional>

instance type, defaults to aws.instanceType or t4g.micro

keyName string <optional>

key pair name, defaults to aws.keyName

data string <optional>

user data in clear text

file string <optional>

path to a file whose contents are used as user data (read synchronously)

terminate boolean <optional>

set shutdown behaviour to terminate

stop boolean <optional>

set shutdown behaviour to stop

noTerminate boolean <optional>

enable API termination protection

groupId string | Array.<string> <optional>

one or more security group ids

ip string <optional>

static private IP address to assign

publicIp boolean <optional>

associate a public IP address

subnetId string <optional>

subnet id, defaults to aws.subnetId

availabilityZone string <optional>

availability zone, defaults to aws.zone

iamProfile string <optional>

IAM instance profile, defaults to aws.iamProfile

name string <optional>

Name tag, any %i is replaced with the instance index

tags object <optional>

additional tags as key:value

targetGroup string | Array.<string> <optional>

ELB target group(s) to join after startup

elasticIp string <optional>

Elastic IP to associate after startup

alarms Array.<object> <optional>

CloudWatch alarms to create, each item is options for module:aws.cwPutMetricAlarm

device object <optional>

BlockDeviceMapping spec: { name, size, type, iops, keep, virtual }

metadata string | Array.<string> <optional>

instance metadata options: disabled, hops, tokens, tags

launchTemplate string <optional>

launch template name (latest version); most other options are ignored

noWait boolean <optional>

return immediately without running post-launch tasks

waitRunning boolean <optional>

wait until the instance is in running state

waitTimeout number <optional>

how long to wait in ms for the instance to be runnable

waitDelay number <optional>

how often in ms to poll for status while waiting

callback function()

(err, rc, info)

(static) ec2WaitForInstance(instanceId, status, optionsopt, callback)

Description:
  • Poll an instance status until it matches the expected value or the timeout expires.

Source:
Parameters:
Name Type Attributes Description
instanceId string

the instance id

status string

desired state: pending | running | shutting-down | terminated | stopping | stopped

options object <optional>
Properties
Name Type Attributes Default Description
waitTimeout number <optional>
300000

how long to wait in ms before giving up

waitDelay number <optional>
10000

delay in ms between polls

callback function()

(err, instance)

(static) ecsDescribeTasks(options, callback)

Description:
Source:
Parameters:
Name Type Description
options object
Properties
Name Type Attributes Description
cluster string <optional>

cluster name, defaults to aws.ecsCluster

tasks string | Array.<string>

task id(s) or ARN(s) to describe

callback function()

(err, rc)

(static) ecsPrepareTask(task) → {object}

Description:
  • Normalize a raw ECS task object: extracts id, name, arch, family, private IP and subnet from the task's containers, attachments and attributes. Returns the same object.

Source:
Parameters:
Name Type Description
task object

raw task object from an ECS response

Returns:
Type Description
object

the augmented task object

(static) ecsRunTask(options, callback)

Description:
  • Run an ECS task, supports native ECS request properties plus the simplified options below.

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Attributes Default Description
task string

task definition family or ARN

count number <optional>
1

number of tasks to run

cluster string <optional>

cluster name, defaults to aws.ecsCluster

launchType string <optional>

EC2 or FARGATE

provider string <optional>

capacity provider name (shortcut for capacityProviderStrategy)

group string <optional>

task group

publicIp boolean <optional>

assign a public IP (awsvpc networking)

groupId string | Array.<string> <optional>

security group id(s), defaults to aws.groupId

subnetId string | Array.<string> <optional>

subnet id(s), defaults to aws.subnetId

cpu number <optional>

task/container CPU override

memory number <optional>

task/container memory override

disk number <optional>

ephemeral storage size in GiB

role string <optional>

task role ARN

execRole string <optional>

execution role ARN

container string <optional>

container name to apply overrides to

env object <optional>

environment variables as name:value for the container

files Array.<string> <optional>

S3 URLs of environment files for the container

tags object <optional>

task tags

callback function()

(static) ecsTaskProtection(optionsopt, callback)

Description:
  • Enable or disable ECS task scale-in protection for the current task, using the ECS agent endpoint. No-op when not running inside ECS.

Source:
Parameters:
Name Type Attributes Description
options object <optional>
Properties
Name Type Attributes Description
minutes number <optional>

0 enables protection for the given minutes, <=0 disables it, omit to just query state

callback function()

(static) elb2DeregisterInstances(target, instance, optionsopt, callback)

Description:
  • Deregister instance(s) from an ELBv2 target group.

Source:
Parameters:
Name Type Attributes Description
target string

target group ARN

instance string | Array.<string>

one id or a list of instance ids/IP addresses

options object <optional>
callback function()

(static) elb2RegisterInstances(target, instance, optionsopt, callback)

Description:
  • Register instance(s) with an ELBv2 target group.

Source:
Parameters:
Name Type Attributes Description
target string

target group ARN

instance string | Array.<string>

one id/IP or a list of instance ids or IP addresses

options object <optional>
callback function()

(static) fetch(url, options, callback)

Description:
  • Internal wrapper around module:lib.fetch that applies per-service default retry settings.

Source:
Parameters:
Name Type Description
url string

request URL

options object

fetch options (endpoint, action, retryCount...)

callback function()

(err, request)

(static) fromDynamoDB(value, levelopt) → {*}

Description:
  • Convert a DynamoDB attribute-value object back into a plain JavaScript value.

Source:
Parameters:
Name Type Attributes Description
value object

DynamoDB formatted value or item

level number <optional>

internal recursion level

Returns:
Type Description
*

the native JavaScript value

(static) getInstanceCredentials(pathopt, callbackopt)

Description:
  • Retrieve temporary credentials from the EC2/ECS instance profile, store them on aws (key/secret/token) and schedule automatic refresh before expiration.

Source:
Parameters:
Name Type Attributes Description
path string <optional>

explicit credentials metadata path/URL, otherwise derived from the IAM profile

callback function() <optional>

(static) getInstanceDetails(optionsopt, callbackopt)

Description:
Source:
Parameters:
Name Type Attributes Description
options object <optional>
callback function() <optional>

(err, instance)

(static) getInstanceInfo(optionsopt, callbackopt)

Description:
  • Detect the AWS environment and populate module:app.env and aws with instance/task identity, region, credentials, key pair and tags from EC2/ECS metadata.

Source:
Parameters:
Name Type Attributes Description
options object <optional>
callback function() <optional>

(static) getInstanceMeta(path, optionsopt, callback)

Description:
  • Retrieve EC2 instance metadata from the given metadata path (or full URL). Uses IMDSv2 token if available.

Source:
Parameters:
Name Type Attributes Description
path string

metadata path, e.g. /latest/meta-data/instance-id, or a full URL

options object <optional>

options merged into the fetch request (httpTimeout, retryCount, noparse...)

callback function()

(err, data) where data is the metadata value or "" if not found

(static) getInstanceMetaToken(callbackopt)

Description:
  • Retrieve an IMDSv2 session token and cache it in aws.metaToken, scheduling automatic refresh.

Source:
Parameters:
Name Type Attributes Description
callback function() <optional>

(err, token)

(static) getSecretValue(name, optionsopt, callback)

Description:
  • Get a secret value from AWS Secrets Manager.

Source:
Parameters:
Name Type Attributes Description
name string

secret id or ARN

options object <optional>
Properties
Name Type Attributes Description
versionId string <optional>

specific version id to retrieve

VersionStage string <optional>

staging label of the version to retrieve

callback function()

(static) getServiceCredentials(obj, options) → {object}

Description:
  • Copy region/endpoint/credentials properties from options into the target object.

Source:
Parameters:
Name Type Description
obj object

destination object

options object

source options

Returns:
Type Description
object

the destination object

(static) getServiceEndpoint(req, options)

Description:
  • Specific endpoint url if it is different from the common endpoint.region.amazonaws.com

Source:
Parameters:
Name Type Description
req object

service request descriptor

Properties
Name Type Attributes Description
region string

must be set for correct resolution

path string <optional>

wil be used if not empty instead of any other endpoint paths

options object
Properties
Name Type Attributes Description
endpoint string <optional>

full endpoint url to use instead of defaults AWS endpoint

endpoint_protocol string <optional>

endpoint protocol, takes precedence over full url proto

endpoint_host string <optional>

endpoint host, takes precedence over full url host

endpoint_path string <optional>

endpoint path, takes precedence over full url path

(static) getServiceOptions(req, options) → {object}

Description:
  • Build a module:lib.fetch options object by merging service request fields and user options.

Source:
Parameters:
Name Type Description
req object

service request descriptor

options object

user options

Returns:
Type Description
object

the fetch options

(static) getServiceRegion(service, region) → {string}

Description:
  • Return a region supported by the service, falling back to the first supported region if needed.

Source:
Parameters:
Name Type Description
service string

service endpoint name

region string

desired region

Returns:
Type Description
string

the region to use

(static) getTaskDetails(optionsopt, callbackopt)

Description:
  • If running inside ECS, pull the task metadata and populate aws.task and module:app.env (task, service, container, ip...). No-op otherwise.

Source:
Parameters:
Name Type Attributes Description
options object <optional>
callback function() <optional>

(err, task)

(static) lambdaEventsProxySQS(event, callbackopt) → {undefined}

Description:
  • Wrap Lambda SQS handler to use with Events, each event is wrapped into SQS Event record and passed to the real Lambda handler.

    The function context this must point to real Lambda handler or an object with .handler method:

    • function - the Lambda handler method to call
    • object
      • .handler - actual Lambda handler
      • .context - lambda context to be merged with Lambda handler default context, this is deep merge
Source:
Parameters:
Name Type Attributes Description
event object

SQS Event with records

callback function() <optional>

callback to return back to events processor, use err.status >= 600 to keep the event in the queue for retry, err.status >= 400 to drop

Returns:
Type Description
undefined
Examples

Assume there is a Lambda package and we want to run it locally via backendjs Events system instead of testing inside AWS. Save a script `test-lambda.js`

const { app, db, lib, events } = require("backendjs");
const handler = require("lambda-package");

app.start({ worker: true }, async () => {
    await db.acreateTables();

    // Publish events into the queue first
    const file = process.argv.find(x => x.endsWith(".json"));
    if (file) {
        lib.forEachLineSync(file, { json: true }, (event) => {
            events.putEvent("test", event);
        });
        await lib.sleep(1000);
    }

    // Now we are ready to process these events with lambda

    events.subscribe("", aws.lambdaEventsProxySQS, handler);

    // To provide custom context call it this way

    // events.subscribe("", aws.lambdaEventsProxySQS, { handler, context: { clientContext: { user_id: "12345" } } } });
});

save minimal bkjs.conf to use local Sqlite queue

db-pool=sqlite
db-sqlite-pool=var/test
queue-default=db://
events-routing=default:.*

Now to test events start it from command line, pass a file with events to publish, one event per line in JSON oformat

node test-lambda.js events.json

(static) lambdaInvoke(name, body, obj, optionsopt, callback)

Description:
  • AWS Lambda Invoke API request.

Source:
Parameters:
Name Type Attributes Description
name string

Lambda function name, Function name – my-function (name-only), my-function:v1 (with alias). Function ARN – arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN – 123456789012:function:my-function.

body object

function payload

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryService

Properties
Name Type Attributes Description
qualifier string <optional>

Specify a version or alias to invoke a published version of the function. Length Constraints: Minimum length of 1. Maximum length of 128. Pattern: $(LATEST(.PUBLISHED)?)|[a-zA-Z0-9-_$]+

invocationType string <optional>

Event for async, RequestResponse or DryRun

logType string <optional>

Set to Tail to include the execution log in the response. Applies to synchronously invoked functions only.

clientContext string <optional>

Up to 3,583 bytes of base64-encoded data about the invoking client to pass to the function in the context object. Lambda passes the ClientContext object to your function for synchronous invocations only.

durableExecutionName string <optional>

A unique name for the durable execution.

tenantId string <optional>

The identifier of the tenant in a multi-tenant Lambda function.

callback function()

(err, data, request) The data object will contains the following properties:

  • payload - response payload object
  • functionError - error from the function
  • logResult - last 4K of output
  • executedVersion
  • durableExecutionArn
Example
# aws.lambdaInvoke("myFunction", { data: 1234 }, { logType: "Tail" }, lib.log)

{
   payload: { ... }
   logResult: "....",
   executedVersion: "$LATEST",
   durableExecutionName: "...."
}

(static) lambdaProxyAPIGateway(context, callbackopt) → {undefined}

Description:
  • Wrap Lambda API Gateway handler to use with api module, each request is wrapped into API request context and passed to the real Lambda handler. By default payload V2 version is used.

    The function context this must point to real Lambda handler or an object with .handler method:

    • function - the Lambda handler method to call
    • object
      • .handler - actual Lambda handler
      • .context - API Gateway Event V1 or V2 context to be merged with default event, this is deep merge
      • .version - 1 or 2 to choose which payload event version to merge with and pass to the handler, 2 is default
Source:
Parameters:
Name Type Attributes Description
context RequestContext

API request context object

callback function() <optional>

callback to return back to events processor, use err.status >= 600 to keep the event in the queue for retry, err.status >= 400 to drop

Returns:
Type Description
undefined
Examples

save minimal bkjs.conf to use local Sqlite queue

middleware-body-enable = true

Assume there is a Lambda package and we want to run it locally via backendjs API router instead of testing inside AWS. Save a script `test-lambda.js`

const { app, api, lib } = require("backendjs");
const handler = require("lambda-package");

app.start({ api: true }, async () => {

    api.app.get("/lambda/*", aws.lambdaProxyAPIGateway.bind(handler));

    // Use V1 event payload context
    api.app.get("/lambda/*", aws.lambdaProxyAPIGateway.bind({ handler, verson: 1 }));

    // or with custom static context

    // const requestContext = { authorizer: { lambda: { userId: 1 };

    // api.app.get("/lambda/*", aws.lambdaProxyAPIGateway.bind({ handler, context: { requestContext }} }));

    // or with custom dynamic context

    // api.app.get("/lambda/*", (context, next) => {
    //    const requestContext = { authorizer: { lambda: { userId: context.user?.id } }};
    //
    //    aws.lambdaProxyAPIGateway.call({ handler, context: { requestContext }), next);
    // });
});

Now to test events start it from command line

node test-lambda.js

(static) listCertificates(options, callback)

Description:
  • Return a list of ACM certificates (handles pagination).

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Attributes Description
status string | Array.<string> <optional>

filter by status: PENDING_VALIDATION | ISSUED | INACTIVE | EXPIRED | VALIDATION_TIMED_OUT | REVOKED | FAILED

callback function()

(err, list)

(static) parseError(req) → {Error|undefined}

Description:
  • Extract an Error object from a parsed AWS response, honouring req.ignore_error.

Source:
Parameters:
Name Type Description
req object

the request object with parsed obj, status, data

Returns:
Type Description
Error | undefined

the error, or undefined if ignored

(static) parseXMLResponse()

Description:
  • Parse AWS response and try to extract error code and message, convert XML into an object.

Source:

(static) queryACM(action, obj, optionsopt, callback)

Description:
  • AWS Certificate Manager (ACM) API request.

Source:
Parameters:
Name Type Attributes Description
action string

ACM API action, e.g. ListCertificates, DescribeCertificate

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryService

callback function()

(err, data, request)

(static) queryAS(action, obj, optionsopt, callback)

Description:
  • AWS Auto Scaling API request.

Source:
Parameters:
Name Type Attributes Description
action string

Auto Scaling API action, e.g. DescribeAutoScalingGroups

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryEndpoint

callback function()

(err, data, request)

(static) queryCFN(action, obj, options, callback)

Description:
  • Makes a request to AWS CloudFormation API.

Source:
Parameters:
Name Type Description
action string

The CloudFormation API action to perform (e.g., DescribeStacks, CreateStack).

obj Object

API-specific parameters as an object.

options Object

Optional configuration object

Properties
Name Type Attributes Description
region string <optional>

AWS region (e.g., "us-east-1").

retryTimeout number <optional>

Request timeout in milliseconds.

retryCount number <optional>

Max request retries

callback function()

Callback function with: signature (err, data) where:

  • err: Error object if request fails.
  • data: Response object from AWS.
Example
```js
aws.queryCFN(
  'CreateStack',
  {StackName: 'MyStack', Body: stackTemplate}, // obj
  {region: 'us-west-2'},                     // options
  (err, result) => { ... }                  // callback
)

(static) queryCW(action, obj, optionsopt, callback)

Description:
  • AWS CloudWatch (metrics/alarms) API request.

Source:
Parameters:
Name Type Attributes Description
action string

CloudWatch API action, e.g. PutMetricData, GetMetricData

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryEndpoint

callback function()

(err, data, request)

(static) queryCWL(action, obj, optionsopt, callback)

Description:
  • AWS CloudWatch Logs API request.

Source:
Parameters:
Name Type Attributes Description
action string

CloudWatch Logs API action, e.g. FilterLogEvents, PutLogEvents

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryService

callback function()

(err, data, request)

(static) queryComprehend(action, obj, optionsopt, callback)

Description:
  • AWS Comprehend (NLP) API request.

Source:
Parameters:
Name Type Attributes Description
action string

Comprehend API action, e.g. DetectSentiment, DetectEntities

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryService

callback function()

(err, data, request)

(static) queryDDB(action, obj, optionsopt, callback)

Description:
  • Low-level DynamoDB API request with DynamoDB-specific retry/backoff handling.

Source:
Parameters:
Name Type Attributes Description
action string

DynamoDB API action, e.g. PutItem, Query, Scan

obj object

native DynamoDB request body

options object <optional>

request options; capitalized options are passed through as native parameters

callback function()

(err, obj)

(static) queryEC2(action, obj, optionsopt, callback)

Description:
  • AWS EC2 API request.

Source:
Parameters:
Name Type Attributes Description
action string

EC2 API action, e.g. RunInstances, DescribeInstances

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryEndpoint

callback function()

(err, data, request)

(static) queryECR(action, obj, optionsopt, callback)

Description:
  • AWS Elastic Container Registry (ECR) API request.

Source:
Parameters:
Name Type Attributes Description
action string

ECR API action, e.g. GetAuthorizationToken, DescribeImages

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryService

callback function()

(err, data, request)

(static) queryECS(action, obj, optionsopt, callback)

Description:
  • AWS ECS (Elastic Container Service) API request.

Source:
Parameters:
Name Type Attributes Description
action string

ECS API action, e.g. RunTask, DescribeTasks

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryService

callback function()

(err, data, request)

(static) queryELB2(action, obj, optionsopt, callback)

Description:
  • AWS Elastic Load Balancing v2 (ALB/NLB) API request.

Source:
Parameters:
Name Type Attributes Description
action string

ELBv2 API action, e.g. RegisterTargets, DescribeTargetGroups

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryEndpoint

callback function()

(err, data, request)

(static) queryElastiCache(action, obj, optionsopt, callback)

Description:
  • AWS ElastiCache API request.

Source:
Parameters:
Name Type Attributes Description
action string

ElastiCache API action, e.g. DescribeCacheClusters

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryEndpoint

callback function()

(err, data, request)

(static) queryEndpoint(endpoint, version, action, obj, options, callback)

Description:
  • AWS generic query interface

Source:
Parameters:
Name Type Description
endpoint string

AWS service endpoint (e.g. 'ec2', 'email')

version string

Service version (e.g. 2011-01-02)

action string

API-specific action to perform (e.g., DescribeStacks, CreateStack).

obj Object

API-specific parameters as an object.

options Object

Optional configuration object, all capitalized options are passed as is and take priority because they are in native format

Properties
Name Type Attributes Description
region string <optional>

AWS region (e.g., "us-east-1").

endpoint string <optional>

custom endpoint for local env or alternatives

retryTimeout number <optional>

Request timeout in milliseconds.

retryCount number <optional>

Max request retries

callback function()

Callback function with: signature (err, data, request) where:

  • err: Error object if request fails.
  • data: Response object from AWS.
  • request: Full fetch Request object

(static) queryEvents(action, obj, optionsopt, callback)

Description:
  • AWS EventBridge (CloudWatch Events) API request.

Source:
Parameters:
Name Type Attributes Description
action string

EventBridge API action, e.g. PutEvents, PutRule

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryService

callback function()

(err, data, request)

(static) queryIAM(action, obj, optionsopt, callback)

Description:
Source:
Parameters:
Name Type Attributes Description
action string

IAM API action, e.g. ListUsers, CreateRole

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryEndpoint (region, retryCount, retryTimeout, endpoint...)

callback function()

(err, data, request)

(static) queryRdsData(action, postdata, optionsopt, callback)

Description:
  • AWS Secrets Manager API request.

Source:
Parameters:
Name Type Attributes Description
action string

RDS Data API action, e.g. Execute

postdata object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryService

callback function()

(err, data, request)

(static) queryRekognition(action, obj, optionsopt, callback)

Description:
  • AWS Rekognition (image/video analysis) API request.

Source:
Parameters:
Name Type Attributes Description
action string

Rekognition API action, e.g. DetectLabels, DetectFaces

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryService

callback function()

(err, data, request)

(static) queryRoute53(method, path, postdata, optionsopt, callback)

Description:
  • Make a request to the Route53 REST API.

Source:
Parameters:
Name Type Attributes Description
method string

HTTP method, e.g. GET, POST

path string

request path appended to the Route53 API base URL

postdata string

XML request body

options object <optional>

request options

callback function()

(err, data, request)

(static) queryRoute53Domains(action, obj, optionsopt, callback)

Description:
  • AWS Route53 Domains API request.

Source:
Parameters:
Name Type Attributes Description
action string

Route53 Domains API action, e.g. ListDomains, RegisterDomain

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryService

callback function()

(err, data, request)

(static) queryS3(bucket, path, optionsopt, callback)

Description:
  • Make a low-level signed S3 request.

Source:
Parameters:
Name Type Attributes Description
bucket string

S3 bucket name

path string

object key/path within the bucket

options object <optional>
Properties
Name Type Attributes Description
method string <optional>

HTTP method

query object <optional>

query parameters for the URL

postdata string | Buffer <optional>

data to send with POST/PUT

postfile string <optional>

path of a file to upload

expires number <optional>

absolute time when the request expires

headers object <optional>

HTTP headers to send

file string <optional>

file name to save the downloaded contents to

callback function()

(err, request)

(static) querySES(action, obj, optionsopt, callback)

Description:
  • AWS SES (Simple Email Service) API request.

Source:
Parameters:
Name Type Attributes Description
action string

SES API action, e.g. SendEmail, SendRawEmail

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryEndpoint

callback function()

(err, data, request)

(static) querySNS(action, obj, optionsopt, callback)

Description:
  • AWS SNS (Simple Notification Service) API request.

Source:
Parameters:
Name Type Attributes Description
action string

SNS API action, e.g. Publish, CreateTopic

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryEndpoint

callback function()

(err, data, request)

(static) querySQS(action, obj, optionsopt, callback)

Description:
  • AWS SQS (Simple Queue Service) API request.

Source:
Parameters:
Name Type Attributes Description
action string

SQS API action, e.g. SendMessage, ReceiveMessage

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryEndpoint

callback function()

(err, data, request)

(static) querySSM(action, obj, optionsopt, callback)

Description:
  • AWS Systems Manager (SSM) API request.

Source:
Parameters:
Name Type Attributes Description
action string

SSM API action, e.g. GetParameter, SendCommand

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryService

callback function()

(err, data, request)

(static) querySTS(action, obj, optionsopt, callback)

Description:
  • AWS STS (Security Token Service) API request.

Source:
Parameters:
Name Type Attributes Description
action string

STS API action, e.g. AssumeRole, GetCallerIdentity

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryEndpoint

callback function()

(err, data, request)

(static) querySecrets(action, obj, optionsopt, callback)

Description:
  • AWS Secrets Manager API request.

Source:
Parameters:
Name Type Attributes Description
action string

Secrets Manager API action, e.g. GetSecretValue, ListSecrets

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryService

callback function()

(err, data, request)

(static) queryService(req, obj, optionsopt, callback)

Description:
  • Executes an AWS service query for the specified action

Source:
Parameters:
Name Type Attributes Description
req object
Properties
Name Type Attributes Description
endpoint string

AWS service endpoint (e.g., 'asm', 'ecr', ...)

service string <optional>

AWS service to use in the Signature, default is to use endpoint, (e.g. "ses")

target string <optional>

Namespace for the AWS service API (e.g., 'AmazonSSM', 'CertificateManager'), this is sent in the X-Amz-Target header

action string <optional>

AWS API action to perform (e.g., 'PutItem', 'GetItem')

path string <optional>

custom path to use in the request url

native boolean <optional>

capitalized properties from options will be set in the obj, original object is not changed

json string <optional>

amz-json version, default is 1.1, old services use 1.0

obj Object

Request body object containing action parameters

options Object <optional>

Optional configuration options, (retryTimeout, retryCount, etc., see module:lib.fetch)

Properties
Name Type Attributes Description
region string <optional>

AWS region, overrides library/default region

endpoint string <optional>

custom endpoint for local env or alternatives

callback function()

Callback function with signature: (err, obj, request) where

  • err contains the error (if any)
  • obj {Object} Parsed API response object
  • request - full request object from lib.fetch
Example
aws.queryService({
    endpoint: "ecs",
    target: "AmazonEC2ContainerServiceV20141113",
    action: 'DescribeTasks' },
   { cluster: 'MyCluster' }, (err, response) => { ... });

(static) queryTranscribe(action, obj, optionsopt, callback)

Description:
  • AWS Transcribe (speech-to-text) API request.

Source:
Parameters:
Name Type Attributes Description
action string

Transcribe API action, e.g. StartTranscriptionJob

obj object

API-specific request parameters

options object <optional>

request options passed to module:aws.queryService

callback function()

(err, data, request)

(static) rdsDataExecute(options, callback)

Description:
  • Runs a SQL statement against a database.

Source:
Parameters:
Name Type Description
options object

native RDS Data API properties

Properties
Name Type Attributes Description
resourceArn string

database cluster

sql string

SQL statement

database string <optional>

database name

secretArn string <optional>

The ARN of the secret that enables access to the DB cluster. Enter the database user name and password for the credentials in the secret.

transactionId string <optional>

The identifier of a transaction that was started by using the BeginTransaction operation

parameters Array.<object> <optional>

The parameters for the SQL statement as a list of objects { name, value: { [stringValue|longValue|doubleValue|booleanValue|isNull|arrayValue[stringValues|longValues|doubleValues]] } [, typeHint] }

includeResultMetadata boolean <optional>

A value that indicates whether to include metadata in the results.

convertResult boolean <optional>

if true convert records into native Javascript array of objects with properties being column names

callback function()
Examples
aws.rdsDataExecute({
    database: "mydb",
    resourceArn: "arn:aws:rds:us-east-1:123456789012:cluster:mydbcluster",
    secretArn: "arn:aws:secretsmanager:us-east-1:123456789012:secret:mysecret",
    sql: "insert into mytable values (:id, :val)",
    parameters: [{ name: "id", value: { longValue: 1 } },
                 { name: "val", value: { stringValue: "value1" } }]
}, lib.log)
aws.rdsDataExecute({
    database: "mydb",
    resourceArn: "arn:aws:rds:us-east-1:123456789012:cluster:mydbcluster",
    secretArn: "arn:aws:secretsmanager:us-east-1:123456789012:secret:mysecret",
    sql: "select * from mytable",
    convertResult: true,
}, lib.log)

(static) readConfig(callbackopt)

Description:
  • Read and apply configuration from an S3 bucket, AWS Secrets Manager and AWS Systems Manager Parameter Store, based on aws.configS3File, aws.configSecrets and aws.configParameters. When aws.configS3Interval is set the config is reloaded periodically.

Source:
Parameters:
Name Type Attributes Description
callback function() <optional>
Examples

Use config from S3 bucket, different for each run mode, running `-app-roles production` and `-app-roles dev` will use different config files

# local config pointing to S3 config bkjs-aws.conf when running in AWS env or bkjs-dev.conf otherwise
aws-config-s3-file = s3://mybucket/config/bkjs-@type|dev@.conf

# bkjs-production.conf: production config on S3
[roles=production]
db-dynamodb-pool = default
db-pool = dynamodb
app-log-level = info

# bkjs-dev.conf: development config on S3
[roles=dev]
db-dynamodb-pool = http://localhost:8181
db-pool = dynamodb
app-log-level = debug

Use secrets manager for api keys, different for dev and prod

# local config pointing to secrets manager
aws-config-secrets = bkjs-@runMode@

# store 2 secrets as

aws secretsmanager create-secret --name bkjs-production --secret-string "my-secret = 12345\nmy-api-key = 9887"

aws secretsmanager create-secret --name bkjs-dev --secret-string "my-secret = 0000\nmy-api-key = 00000"

To load config periodically setup the interval in the config, readConfig wil be called overriding existing config from all existingh sources

aws-config-s3-interval = 1800000

(static) readCredentials(profile, callback)

Description:
  • Read key and secret from the AWS SDK credentials or config file, if no profile is given in the config or command line only the default peofile will be loaded. Supports login sessions created via aws login.

Source:
Parameters:
Name Type Description
profile string
callback function()

(static) readCredentialsProfile(file, profile, callback)

Description:
  • Read all parameters from a file for a given profile

Source:
Parameters:
Name Type Description
file string
profile string
callback function()

(static) retryOnError() → {boolean}

Description:
  • Default retry predicate, called in the context of a request; retries on throttling/unavailable errors.

Source:
Returns:
Type Description
boolean

true if the request should be retried

(static) route53Change(names, optionsopt, callback)

Description:
  • Create or update DNS records in Route53.

Source:
Parameters:
Name Type Attributes Description
names string | object | Array.<object>

a host name to set to the current IP, or record object(s) in the form { name, value, type, ttl, zoneId, alias, hostedzone, healthCheck }

options object <optional>
Properties
Name Type Attributes Default Description
type string <optional>
A

default record type

ttl number <optional>
300

default TTL in seconds

op string <optional>
UPSERT

change action (UPSERT | CREATE | DELETE)

alias string <optional>

default alias DNS name

healthCheckId string <optional>

health check id to attach

quiet boolean <optional>

suppress errors (e.g. zone not found)

callback function()

(static) route53Create(options, callback)

Description:
  • Create a Route53 hosted zone.

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Description
name string

domain name for the new hosted zone

callback function()

(static) route53Get(options, callback)

Description:
  • Return a hosted zone by id or domain name.

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Attributes Description
zone string <optional>

hosted zone id

name string <optional>

domain name to look up the zone by

callback function()

(static) route53List(optionsopt, callback)

Description:
  • List all Route53 hosted zones (handles pagination).

Source:
Parameters:
Name Type Attributes Description
options object <optional>
callback function()

(err, zones)

(static) s3CopyFile(path, source, optionsopt, callback)

Description:
  • Copy an existing S3 object to a new location.

Source:
Parameters:
Name Type Attributes Description
path string

destination S3 URL/path

source string

source object as bucket/path (an s3:// prefix is removed)

options object <optional>
Properties
Name Type Attributes Description
acl string <optional>

canned ACL for the copy

contentType string <optional>

content type, defaults to the mime type of the path

callback function()

(err, request)

(static) s3GetFile(path, optionsopt, callback)

Description:
  • Retrieve a file from an S3 bucket; the root of the path is the bucket, an s3:// prefix is ignored.

Source:
Parameters:
Name Type Attributes Description
path string

S3 URL/path (e.g. s3://bucket/key)

options object <optional>

see module:aws.queryS3, e.g. file to save to disk

callback function()

(err, request)

(static) s3List(path, optionsopt, callback)

Description:
  • Retrieve a list of files from an S3 bucket, only objects under the given path are returned.

Source:
Parameters:
Name Type Attributes Description
path string

S3 URL/path, root is the bucket (e.g. s3://bucket/prefix or bucket/prefix)

options object <optional>
Properties
Name Type Attributes Description
query object <optional>

extra S3 list query parameters (e.g. delimiter)

callback function()

(err, rows, prefixes)

(static) s3ParseUrl(link) → {object}

Description:
  • Parse an S3 URL into its components.

Source:
Parameters:
Name Type Description
link string

an S3 URL/path, optionally with key:secret@ credentials and a query string

Returns:
Type Description
object

{ bucket, path, [key], [secret], [query] }

(static) s3Proxy(res, bucket, file, optionsopt, callbackopt)

Description:
  • Proxy (stream) an object from an S3 bucket into an existing HTTP response.

    Typically used to serve/download S3-hosted files through your app: it fetches file from bucket (optionally using request options like range/content-type/etc) and pipes the S3 response directly into res, preserving status/headers as appropriate.

Source:
Parameters:
Name Type Attributes Description
res http.ServerResponse

Node.js HTTP response object to write to. The S3 object data is streamed into it.

bucket string

S3 bucket name that contains the object.

file string

S3 object key (path inside the bucket).

options Object <optional>

Controls how the object is fetched and how the HTTP response is produced.

Properties
Name Type Attributes Description
headers Object <optional>

Extra headers to send to S3 (commonly used for Range).

attachment boolean <optional>

If true, sets Content-Disposition to attachment (usually derived from filename).

callback function(Error=): void <optional>

Called when proxying finishes or fails.

  • err is set on any S3/stream/response error.

(static) s3PutFile(path, file, optionsopt, callback)

Description:
  • Upload a file to an S3 bucket.

Source:
Parameters:
Name Type Attributes Description
path string

S3 URL/path (e.g. s3://bucket/key)

file string | Buffer

a Buffer with contents or a path to a local file

options object <optional>
Properties
Name Type Attributes Description
acl string <optional>

canned ACL, sets x-amz-acl

contentType string <optional>

object content type

callback function()

(err, request)

(static) sesSendEmail(to, subject, body, optionsopt, callback)

Description:
  • Send an email via SES.

Source:
Parameters:
Name Type Attributes Description
to string | Array.<string>

recipient(s) for the To: header

subject string

email subject

body string

email body (text or HTML)

options object <optional>
Properties
Name Type Attributes Default Description
from string <optional>

From: address, defaults to app.emailFrom or admin@<domain>

cc string | Array.<string> <optional>

Cc: recipients

bcc string | Array.<string> <optional>

Bcc: recipients

replyTo string | Array.<string> <optional>

Reply-To: addresses

returnPath string <optional>

address to send bounces to

charset string <optional>
UTF-8

charset for subject and body

html boolean <optional>

send the body as MIME HTML

config string <optional>

configuration set name

callback function()

(static) sesSendRawEmail(body, optionsopt)

Description:
  • SES V1 send raw email

Source:
Parameters:
Name Type Attributes Description
body string

base64 encoded raw mail envelope

options object <optional>
Properties
Name Type Attributes Description
to string <optional>

list of email addresses to use in RCPT TO

from string <optional>

an email to use in from header

config string <optional>

configuration set name

(static) sesSendRawEmail2(body, optionsopt)

Description:
  • SES V2 version Send raw email

Source:
Parameters:
Name Type Attributes Description
body string

base64 encoded raw mail envelope

options object <optional>
Properties
Name Type Attributes Description
to string <optional>

list of email addresses to use in RCPT TO

from string <optional>

an email to use in from header

config string <optional>

configuration set name

(static) signQuery(region, service, host, method, path, body, headers, credentialsopt, optionsopt) → {void}

Description:
  • Build AWS Signature Version 4 headers for a request.

    Populates/overwrites required signing headers in headers (e.g. host, x-amz-date, optional content-type, content-length, x-amz-security-token) and sets headers.Authorization. If options is provided, signing details are also written into it.

Source:
Parameters:
Name Type Attributes Description
region string

AWS region (e.g. us-east-1).

service string

AWS service name (e.g. s3, ec2, execute-api).

host string

Request host (e.g. s3.amazonaws.com or bucket.s3.us-east-1.amazonaws.com).

method string

HTTP method (e.g. GET, POST, PUT, DELETE).

path string

Request path, may include query string (e.g. /path or /path?a=1&b=2).

body string | Buffer | null

Request payload. If provided, will be hashed for signing and may set content-type/content-length if missing.

headers Object.<string, (string | number | boolean)>

Mutable headers object to sign; updated in-place.

credentials Object <optional>

AWS credentials to use; defaults to aws when not provided.

Properties
Name Type Attributes Description
key string

AWS access key id.

secret string

AWS secret access key.

token string <optional>

AWS session token (for temporary credentials); sets x-amz-security-token.

options Object <optional>

Optional output/input options.

Properties
Name Type Attributes Description
now Date <optional>

Overrides current time used for signing.

signedHeaders string <optional>

Output: semicolon-separated list of signed header names.

credential string <optional>

Output: credential scope string (<accessKeyId>/<scope>).

canonStr string <optional>

Output: canonical request string used for signing.

signature string <optional>

Output: computed signature hex string.

Returns:
Type Description
void

(static) signS3(methodopt, bucket, path, body, optionsopt) → {string}

Description:
  • Sign an S3 request and return the URL to send to the S3 server. options.headers is updated in place with all headers required for signing.

Source:
Parameters:
Name Type Attributes Default Description
method string <optional>
GET

HTTP method

bucket string

S3 bucket name

path string

object key/path within the bucket

body string | Buffer

request payload used for signing

options object <optional>
Properties
Name Type Attributes Description
region string <optional>

AWS region, defaults to aws.region or us-east-1

headers object <optional>

request headers, updated in place with signing headers

query object <optional>

query parameters to include in the signed URL

credentials object <optional>

credentials to sign with, defaults to aws

url boolean <optional>

if set, append the signing params to the URL (presigned URL)

expires number <optional>

expiration seconds for a presigned URL

postfile boolean <optional>

payload is a file, use UNSIGNED-PAYLOAD

Returns:
Type Description
string

the signed request URL

(static) signer()

Description:
  • Default request signer, called in the context of an HTTP request to apply Signature V4 headers.

Source:

(static) snsConfirmSubscription(arn, token, optionsopt, callback)

Description:
  • Confirm a subscription by validating the token sent to the endpoint by an earlier Subscribe action.

Source:
Parameters:
Name Type Attributes Description
arn string

the topic ARN

token string

confirmation token received at the endpoint

options object <optional>
callback function()

(err, subscriptionArn)

(static) snsCreatePlatformEndpoint(token, optionsopt, callback)

Description:
  • Create a platform endpoint for a device on a supported push service (GCM, APNS...).

Source:
Parameters:
Name Type Attributes Description
token string

device token from the notification service

options object <optional>
Properties
Name Type Attributes Description
appArn string <optional>

platform application ARN, defaults to aws.snsAppArn

data string <optional>

custom user data to associate with the endpoint

callback function()

(err, endpointArn)

(static) snsCreateTopic(name, optionsopt, callback)

Description:
  • Create an SNS topic.

Source:
Parameters:
Name Type Attributes Description
name string

topic name

options object <optional>
callback function()

(err, topicArn)

(static) snsDeleteEndpoint(arn, optionsopt, callback)

Description:
  • Delete a platform endpoint from Amazon SNS.

Source:
Parameters:
Name Type Attributes Description
arn string

the endpoint ARN

options object <optional>
callback function()

(static) snsDeleteTopic(arn, optionsopt, callback)

Description:
  • Delete an SNS topic.

Source:
Parameters:
Name Type Attributes Description
arn string

the topic ARN

options object <optional>
callback function()

(static) snsListTopics(optionsopt, callback)

Description:
  • List all SNS topic ARNs.

Source:
Parameters:
Name Type Attributes Description
options object <optional>
callback function()

(err, arns) where arns is a list of topic ARN strings

(static) snsPublish(arn, msg, optionsopt, callback)

Description:
  • Publish a message to a topic's subscribers or to a specific endpoint.

Source:
Parameters:
Name Type Attributes Description
arn string

target topic or endpoint ARN

msg string | object

message string, or an object sent as JSON message structure

options object <optional>
Properties
Name Type Attributes Description
subject string <optional>

optional subject when the target supports it

callback function()

(static) snsSetEndpointAttributes(arn, optionsopt, callback)

Description:
  • Set attributes for a platform endpoint.

Source:
Parameters:
Name Type Attributes Description
arn string

the endpoint ARN

options object <optional>
Properties
Name Type Attributes Description
token string <optional>

device token for the notification service

data string <optional>

custom user data to associate with the endpoint

enabled boolean <optional>

enable/disable notification delivery to this endpoint

callback function()

(static) snsSetSubscriptionAttributes(arn, optionsopt, callback)

Description:
  • Update subscription attributes, either a full delivery policy or granular retry/throttle fields.

Source:
Parameters:
Name Type Attributes Description
arn string

the subscription ARN

options object <optional>
Properties
Name Type Attributes Description
deliveryPolicy object <optional>

full delivery policy object

minDelayTarget number <optional>

retry policy min delay

maxDelayTarget number <optional>

retry policy max delay

numRetries number <optional>

number of retries

numMaxDelayRetries number <optional>

retries at max delay

backoffFunction string <optional>

one of linear | arithmetic | geometric | exponential

maxReceivesPerSecond number <optional>

throttle policy rate

callback function()

(static) snsSetTopicAttributes(arn, optionsopt, callback)

Description:
  • Update topic attributes. Provide one of the high-level attributes, or granular delivery policy fields.

Source:
Parameters:
Name Type Attributes Description
arn string

the topic ARN

options object <optional>
Properties
Name Type Attributes Description
name string <optional>

new display name

policy object <optional>

access policy object

deliveryPolicy object <optional>

full delivery policy object

protocol string <optional>

protocol the granular delivery policy applies to

minDelayTarget number <optional>

retry policy min delay

maxDelayTarget number <optional>

retry policy max delay

numRetries number <optional>

number of retries

numMaxDelayRetries number <optional>

retries at max delay

backoffFunction string <optional>

backoff function name

maxReceivesPerSecond number <optional>

throttle policy rate

disableSubscriptionOverrides boolean <optional>

disable subscription overrides

callback function()

(static) snsSubscribe(arn, endpoint, optionsopt, callback)

Description:
  • Subscribe an endpoint to a topic. If confirmation is required the returned ARN is null and a token is sent to the endpoint. The protocol is auto-detected from the endpoint when not given.

Source:
Parameters:
Name Type Attributes Description
arn string

the topic ARN

endpoint string

the endpoint (URL, ARN, email, phone number...)

options object <optional>
Properties
Name Type Attributes Description
protocol string <optional>

protocol: http/https/sqs/email/sms/application (auto-detected if omitted)

callback function()

(err, subscriptionArn)

(static) snsUnsubscribe(arn, optionsopt, callback)

Description:
  • Unsubscribe from a topic.

Source:
Parameters:
Name Type Attributes Description
arn string

the subscription ARN

options object <optional>
callback function()

(static) sqsReceiveMessage(url, optionsopt, callbackopt)

Description:
  • Receive message(s) from an SQS queue, the callback will receive a list of messages if no error.

Source:
Parameters:
Name Type Attributes Description
url string

queue URL

options object <optional>
Properties
Name Type Attributes Description
count number <optional>

how many messages to receive

timeout number <optional>

how long to wait, in milliseconds, this is for Long Poll

visibilityTimeout number <optional>

the duration (in milliseconds) that the received messages are hidden from subsequent retrieve requests

attemptId string <optional>

request attempt id for FIFO queues after being retrieved by a ReceiveMessage request.

callback function() <optional>

as (err, rows) with received items

(static) sqsSendMessage(url, body, optionsopt, callbackopt)

Description:
  • Send a message to the SQS queue. The options can specify the following:

Source:
Parameters:
Name Type Attributes Description
url string

queue URL

body string

body contents

options object <optional>
Properties
Name Type Attributes Description
delay number <optional>

how long to delay this message in milliseconds

groupId string <optional>

a group name for FIFO queues

deduplicationId string <optional>

deduplication id for FIFO queues

attrs object <optional>

an object with additional message attributes to send, use only string, numbers or binary values, all other types will be converted into strings

callback function() <optional>

(static) sqsSendMessageBatch(url, messages, callbackopt)

Description:
  • Send a batch of messages to the SQS queue. The options can specify the following:

Source:
Parameters:
Name Type Attributes Description
url string

queue URL

messages Array.<object>

messages to send

Properties
Name Type Attributes Description
body object

bodsy contents

delay number <optional>

how long to delay this message in milliseconds

groupId string <optional>

a group name for FIFO queues

deduplicationId string <optional>

deduplication id for FIFO queues

attrs object <optional>

an object with additional message attributes to send, use only string, numbers or binary values, all other types will be converted into strings

callback function() <optional>

(static) ssmGetParametersByPath(path, optionsopt, callback)

Description:
  • Retrieve information about one or more parameters under a specified level in a hierarchy from AWS System Manager

Source:
Parameters:
Name Type Attributes Description
path string

The hierarchy for the parameter. Hierarchies start with a forward slash (/). The hierarchy is the parameter name except the last part of the parameter. For the API call to succeed, the last part of the parameter name can't be in the path. A parameter name hierarchy can have a maximum of 15 levels. Here is an example of a hierarchy: /Finance/Prod/IAD/WinServ2016/license33

options object <optional>
Properties
Name Type Attributes Description
filters Array.<object> <optional>

{ Key: string, Option: string, Values: string[] }

  • Key can be Type, KeyId, and Label
  • Option can be Equal or BeginsWith, for Label only Equals
  • Values a list of strings to matche
callback function()

(static) ssmSendCommand(cmds, instances, optionsopt, callback)

Description:
  • Run a shell command on instances via SSM (AWS-RunShellScript document).

Source:
Parameters:
Name Type Attributes Description
cmds string | Array.<string>

one command or a list of commands to run

instances string | Array.<string>

one instance id or a list of instance ids

options object <optional>
callback function()

(static) ssmWaitForCommand(cmdId, instanceId, optionsopt, callback)

Description:
  • Poll an SSM command invocation until it finishes (leaves Pending/InProgress/Delayed) or times out.

Source:
Parameters:
Name Type Attributes Description
cmdId string

the SSM command id

instanceId string

the instance id

options object <optional>
Properties
Name Type Attributes Default Description
waitTimeout number <optional>
60000

how long to wait in ms

waitDelay number <optional>
1000

delay in ms between polls

callback function()

(err, output)

(static) stsAssumeRole(options, callback)

Description:
  • Assume an IAM role and return temporary credentials usable in other API calls.

Source:
Parameters:
Name Type Description
options object
Properties
Name Type Attributes Description
role string

the role ARN to assume

name string <optional>

role session name, defaults to app.id

callback function()

(err, obj) where obj.credentials is { key, secret, token, expiration }

(static) toDynamoDB(value, levelopt) → {object}

Description:
  • Convert a JavaScript value into DynamoDB attribute-value format ({ S }, { N }, { M }, { L }...).

Source:
Parameters:
Name Type Attributes Description
value *

the value to convert

level number <optional>

internal recursion level; when set, scalars/collections are wrapped in typed descriptors

Returns:
Type Description
object

the DynamoDB representation

(static) uriEscape(str) → {string}

Description:
  • URI-escape a string per AWS Signature V4 rules.

Source:
Parameters:
Name Type Description
str string

string to escape

Returns:
Type Description
string

the escaped string

(static) uriEscapePath(path) → {string}

Description:
  • URI-escape each segment of a path per AWS Signature V4 rules.

Source:
Parameters:
Name Type Description
path string

the path to escape

Returns:
Type Description
string

the escaped path