# Automating with AWS Lambda

## About

Commander is a powerful tool that can solve many issues and provide valuable information about your Keeper Security environment. In addition to using Commander on a local desktop or server, Commander can be run in a cloud environment such as AWS for performing scheduled or on-demand requirements.

In this example, we will demonstrate how to use Commander with AWS Lambda to run user and usage reports on a scheduled basis.

## Prerequisites

* Commander installed on a local machine for one-time device setup
  * See the [Installation and Setup page](/keeperpam/commander-cli/commander-installation-setup.md) for download details
* A dedicated Keeper user account with a Master Password login method, used exclusively by this Lambda (SSO login and MFA will not work without human interaction)
* Access to AWS with permissions to create Lambda functions, Lambda layers, and SSM Parameter Store parameters, along with access to AWS CloudShell

## One-Time Device Setup

Before Lambda can authenticate, you must complete device approval once on a local machine. Keeper requires all devices to be approved before password authentication can succeed — Lambda has no interactive shell to complete this step, so it must use a pre-approved device identity.

### Steps

1. On your local machine, login to Commander with the dedicated Lambda account:

```shell-session
$ keeper shell
```

2. Complete the device approval process (email link, push notification, 2FA, or admin approval depending on your enterprise settings)
3. After successful login, locate the `device_token` in your config file:

```shell-session
$ cat ~/.keeper/config.json | grep device_token
```

{% hint style="warning" %}
Your config file format may vary depending on how Commander was installed. The CLI typically stores `device_token` at the top level, but SDK-based installations may use a nested structure (`devices[].device_token`). Open the file and locate the token manually if the grep command does not return a result.
{% endhint %}

4. Store the following four values as Lambda environment variables (or SSM parameters for production — see below):
   * `KEEPER_DEVICE_TOKEN` — the pre-approved device identity from step 3
   * `KEEPER_USER` — the account email address
   * `KEEPER_PASSWORD` — the master password
   * `KEEPER_SERVER` — the region endpoint (e.g., `keepersecurity.com` for US, `keepersecurity.eu` for EU)

{% hint style="info" %}
**What you do NOT need to store:**

* `private_key` — Commander generates one automatically during password login. If you enable persistent login for warm-container optimization, the private\_key is created and stored in `/tmp` as part of that setup.
* `clone_code` — regenerated automatically on every password login. Only used for persistent login session resumption, which is handled automatically in `/tmp` if enabled.
  {% endhint %}

## Steps

### Create a Lambda Layer With AWS CloudShell

#### Setup

Commander needs to be packaged on a machine that matches what it will run on in AWS Lambda. To do this, we can create the Commander package in CloudShell.

AWS Lambda supports Python 3.10 or 3.11 for this workflow (Python 3.9 and earlier are no longer supported by AWS Lambda). Make sure your CloudShell environment is using one of these versions to build your Lambda Layer by checking the installed Python interpreter:

```shell-session
$ python3 --version
Python 3.11.6
```

If the Python version available in CloudShell does not match a runtime supported by AWS Lambda, install Python 3.10 or 3.11 prior to proceeding.

#### Building the Layer Content

For the next part of the process, we provide a convenient shell script for you to run from within your CloudShell environment, which will create the zip file that contains the `keepercommander` package needed for our Lambda Layer.

This script is intended to simplify and streamline much of the layer-content packaging process, both by encapsulating the various command calls that are standard for the process, and by abstracting away some build-process quirks specific to the `keepercommander` package and its dependencies. As such, ***we highly recommend using this approach over a more generic one, as it is much less likely to be error-prone***.

<details>

<summary>View Script</summary>

{% code title="package\_layer\_content.sh" fullWidth="true" %}

```bash
#!/usr/bin/env bash

#   To create a `keepercommander` dependency layer for your AWS Lambda function :
#   1. Upload this script to any folder in your CloudShell environment.
#   2. (Optional) Upload your project's `requirements.txt` file  to the same folder.
#   3. In that folder, run
#             source ./package_layer_content.sh
#   4. There should now be a file named `commander-layer.zip` that can be uploaded
#     to your S3 bucket, where it can then be used to create a new Lambda layer

MAX_LIB_SIZE=262144000
LAYER_FILENAME='commander-layer.zip'
LAYER_PATH=$(pwd)/$LAYER_FILENAME
LIB_DIR='python'
VENV='commander-venv'
OTHER_DEPS='requirements.txt'

# Clean up previous artifacts
test -f $LAYER_FILENAME && rm $LAYER_FILENAME
test -d $LIB_DIR && rm -rf $LIB_DIR
test -d $VENV && rm -rf $VENV

# Create package folder to zip
mkdir $LIB_DIR

# Create and run virtual environment
python3 -m venv $VENV
source ./$VENV/bin/activate

# Install dependencies and package
python3 -m pip install cryptography --platform manylinux2014_x86_64 --only-binary=:all: -t $LIB_DIR
python3 -m pip install keepercommander -t $LIB_DIR

if test -f $OTHER_DEPS; then
  python3 -m pip install -r $OTHER_DEPS -t $LIB_DIR
fi

deactivate

# Check uncompressed library size
LIB_SIZE=$(du -sb $LIB_DIR | cut -f 1)
LIB_SIZE_MB=$(du -sm $LIB_DIR | cut -f 1)

if [ "$LIB_SIZE" -ge $MAX_LIB_SIZE ]; then
  echo "*****************************************************************************************************************"
  echo 'Operation was aborted'
  echo "The resulting layer has too many dependencies and its size ($LIB_SIZE_MB MB) exceeds the maximum allowed (~262 MB)."
  echo 'Try breaking up your dependencies into smaller groups and package them as separate layers.'
  echo "*****************************************************************************************************************"
else
  zip -r $LAYER_FILENAME $LIB_DIR
  echo "***************************************************************************"
  echo "***************************************************************************"
  echo 'Lambda layer file has been created'
  printf "To download, copy the following file path: %s\n%s\n$LAYER_PATH%s\n%s\n"
  echo 'and click on "Actions" in the upper-right corner of your CloudShell console'
  echo "***************************************************************************"
fi

# Clean-up
rm -rf $LIB_DIR
rm -rf $VENV

```

{% endcode %}

</details>

To use the script provided above, perform the following steps after downloading the file:

1. Upload the script to any folder (preferably an empty one) in your CloudShell environment
   * (Optional) If your project has a `requirements.txt` file containing a list of its dependencies, you can upload it to the same folder to include those dependencies in the resulting layer in addition to the `keepercommander` package.
2. In that same folder, run the following command in the terminal:

```shell-session
source ./package_layer_content.sh
```

3. You should now have a zip file (`commander-layer.zip`) in your current folder, which represents the content of your Lambda Layer.

{% hint style="info" %}
There is a size limit on packaged Lambda layer content (even if stored in S3). So if you try to include additional dependencies by providing the `requirements.txt` file for the script above, and it results in the total content size exceeding this limit, the resulting zip file will be unusable. Hence, no layer content will be output when the script detects this scenario, and a helpful message will be shown to the user instead.

A relatively simple solution is to break up your dependencies into smaller groups to be packaged into corresponding separate layers. You can remove some (or all) dependencies from `requirements.txt` and run the script again. Any dependencies excluded from the resulting package can then be packaged separately into another layer using the standard packaging process.
{% endhint %}

#### Creating / Updating a Layer from the Content Zip File

Because the resulting zip file is going to be bigger than 50MB (the maximum allowed to be uploaded directly to a Lambda Layer), we'll have to first upload it to an AWS S3 Bucket, and then link the resulting S3 item to our Lambda Layer.

There are multiple ways to complete the remaining steps just mentioned, and if you prefer a GUI-based route, using the AWS Console is a perfectly valid option at this point. But since we're already in our CloudShell environment, using its built-in AWS CLI command-line tool seems like the simplest and most direct way forward, so that is the method we'll show here.

1. First, we need to upload our zip file to AWS S3. If you didn't previously create a S3 bucket for this task, you can do so by running the following command in CloudShell:

```shell-session
$ aws s3 mb <bucket-name>
```

where `<bucket-name>` is required to be a globally unique name.

2. Upload the newly-packaged zip file from CloudShell to your S3 bucket

<pre class="language-shell-session"><code class="lang-shell-session"><strong>$ aws s3 cp ./commander-layer.zip 's3://&#x3C;bucket-name>'
</strong></code></pre>

3. Publish the Lambda layer with the uploaded content

```shell-session
$ aws lambda publish-layer-version --layer-name <layer-name> \
--description <layer-description> \
--content "S3Bucket=<bucket-name>,S3Key=commander-layer.zip" \
--compatible-runtimes python3.11

```

### Create a Lambda

In AWS Lambda, use the Lambda editor to write a Python function.

The `lambda_handler` function is triggered by Lambda when it is processed.

See a complete example of a Commander Lambda function below:

{% code fullWidth="false" %}

```python
#  _  __
# | |/ /___ ___ _ __  ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
#              |_|
#
# Keeper Commander
# Copyright 2024 Keeper Security Inc.
# Contact: ops@keepersecurity.com

import os
import json

# Without mounted volumes, Lambda can only write to /tmp. 
os.environ['HOME'] = '/tmp'
os.environ['TMPDIR'] = '/tmp'
os.environ['TEMP'] = '/tmp'

from keepercommander import api
from keepercommander.__main__ import get_params_from_config

keeper_tmp = '/tmp/.keeper'
os.makedirs(keeper_tmp, exist_ok=True)

# ------------------------------------------------------
# Keeper initialization function
# ------------------------------------------------------
def get_params():
    # Read credentials from environment variables
    user = os.environ.get('KEEPER_USER')
    password = os.environ.get('KEEPER_PASSWORD')
    server = os.environ.get('KEEPER_SERVER', 'keepersecurity.com')
    device_token = os.environ.get('KEEPER_DEVICE_TOKEN')

    # Write config.json with the pre-approved device_token
    config_path = keeper_tmp + '/config.json'
    with open(config_path, 'w') as f:
        json.dump({
            'user': user,
            'server': server,
            'device_token': device_token
        }, f)

    # Load params from the config we just wrote
    params = get_params_from_config(config_path)
    params.password = password
    return params

# ------------------------------------------------------
# Keeper JSON report function
# ------------------------------------------------------
def get_keeper_report(params, kwargs):
    from keepercommander.commands.aram import AuditReportCommand
    from json import loads
    
    report_class = AuditReportCommand()
    report = report_class.execute(params, **kwargs)
    return loads(report)
    
# ------------------------------------------------------
# Keeper CLI function
# ------------------------------------------------------
def run_keeper_cli(params, command):
    from keepercommander import cli
    
    cli.do_command(params, command)
    
# ------------------------------------------------------
# Lambda handler
# ------------------------------------------------------
def lambda_handler(event, context):
    # Initialize Keeper Commander params with pre-approved device token
    params = get_params()

    # Keeper login (uses the pre-approved device_token) and sync
    api.login(params)
    api.sync_down(params)
    # Enterprise sync (for enterprise commands)
    api.query_enterprise(params)

    # Approve any OTHER pending devices in the enterprise
    run_keeper_cli(
        params, 
        'device-approve -a'
    )
    
    run_keeper_cli(
        params, 
        'action-report --target locked --apply-action delete --dry-run'
    )

    return get_keeper_report(
        params,
        {
            'report_type':'raw', 
            'format':'json',
            'limit':100,
            'event_type':['login']
        }
    )
```

{% endcode %}

The program is made up of several parts:

#### The `lambda_handler()` function

This function is called when the lambda is triggered, all other functions should be called from this one.

#### The `get_params()` function

This function reads the pre-approved device token and credentials from environment variables, writes a `config.json` with the device identity, and returns a params object ready for `api.login()`. The `device_token` is the critical piece — it represents the device identity that was approved during the one-time setup on your local machine.

{% hint style="info" %}
**Why the device\_token matters:**

Keeper requires device approval before password authentication can succeed. Lambda has no interactive shell to complete device approval, so it must use a `device_token` that was pre-approved on another machine.

Multiple Lambda containers can share the same `device_token` and authenticate concurrently with password — each container writes the same device identity to its local `/tmp/.keeper/config.json` and logs in independently. The `clone_code` gets regenerated on each password login, but this does not matter since we are not using persistent login.
{% endhint %}

#### Commander Functions

Once logged in and synced up, you can run functions and create classes from the Commander SDK. The program above includes two functions - `get_keeper_report()`, which returns a JSON report (equivalent to `audit-report` command), and `run_keeper_cli()`, which simply executes CLI commands (without returning data in Python).

#### Storing Keeper credentials

The example above reads four values from Lambda environment variables:

| Variable              | Description                                          |
| --------------------- | ---------------------------------------------------- |
| `KEEPER_DEVICE_TOKEN` | The pre-approved device identity from one-time setup |
| `KEEPER_USER`         | Account email address                                |
| `KEEPER_PASSWORD`     | Master password                                      |
| `KEEPER_SERVER`       | Region endpoint (defaults to `keepersecurity.com`)   |

This is the simplest approach and requires no additional AWS setup. However, environment variables are visible to anyone with `lambda:GetFunctionConfiguration` permission and may appear in CloudWatch logs if logged. For production deployments, use SSM Parameter Store instead (see next section).

#### Production: Using SSM Parameter Store

For production deployments, store credentials in AWS SSM Parameter Store as `SecureString` parameters. This keeps credentials out of your Lambda configuration and CloudWatch logs, uses KMS for encryption at rest, and lets you scope read access with IAM policies.

Create the following parameters in SSM (these are example paths — customize as needed):

* `/keeper/lambda/device_token`
* `/keeper/lambda/user`
* `/keeper/lambda/password`
* `/keeper/lambda/server`

Then replace the `get_params()` function in your Lambda code with this SSM-based version:

```python
import os
import json
import boto3

os.environ['HOME'] = '/tmp'
os.environ['TMPDIR'] = '/tmp'
os.environ['TEMP'] = '/tmp'

from keepercommander import api
from keepercommander.__main__ import get_params_from_config

keeper_tmp = '/tmp/.keeper'
os.makedirs(keeper_tmp, exist_ok=True)

# Create SSM client once at module level
ssm_client = boto3.client('ssm')

def get_ssm_parameter(name):
    response = ssm_client.get_parameter(Name=name, WithDecryption=True)
    return response['Parameter']['Value']

def get_params():
    user = get_ssm_parameter('/keeper/lambda/user')
    password = get_ssm_parameter('/keeper/lambda/password')
    server = get_ssm_parameter('/keeper/lambda/server')
    device_token = get_ssm_parameter('/keeper/lambda/device_token')

    config_path = keeper_tmp + '/config.json'
    with open(config_path, 'w') as f:
        json.dump({'user': user, 'server': server, 'device_token': device_token}, f)

    params = get_params_from_config(config_path)
    params.password = password
    return params
```

Grant the Lambda execution role only the IAM permission it needs (`ssm:GetParameter` scoped by resource ARN), and do not log the retrieved credentials.

SSM standard parameters are free; SecureString uses KMS which has its own free tier (20,000 requests/month) — effectively no cost for typical Lambda workloads. For enterprise deployments that need built-in rotation, fine-grained audit, or cross-account access, use **AWS Secrets Manager** instead (adds a per-secret cost).

#### A note on persistent login

Commander supports persistent login to skip password entry on subsequent logins. However, **persistent login is not viable for multi-container Lambda deployments**.

Per the Keeper documentation, persistent login is "not intended for dynamic multi-server environments." When any instance logs in with password using the same `device_token`, it regenerates the `clone_code` and invalidates persistent login sessions on all other instances sharing that device identity. The persisted session also lives only in the container's `/tmp` and is lost whenever AWS recycles the container.

For **single-container scheduled Lambdas** (e.g., a once-daily cron where the same warm container handles every invocation), persistent login may provide a minor latency optimization on warm invocations. See the [`this-device` command documentation](/keeperpam/commander-cli/command-reference/misc-commands.md#this-device-command) for setup instructions.

For most Lambda use cases, password-based authentication on every invocation (as shown in the example above) is the correct approach.

### Configure Lambda

#### Set Timeout

In the general configuration section of the Lambda configuration, it is recommended to change the timeout value. Some Commander functions take time, so if your script takes longer to complete than this number, the Lambda will automatically end without finishing.

You can set this to any number you are comfortable with. A value of 300 seconds (5 minutes) should be more than enough time for most processes.

#### Select Layer

In the Lambda editor, select the layer that you created above to include the Commander package in your Lambda build.

#### Create run Schedule

Create an EventCloud trigger to trigger the Lambda and set it to trigger at a cadence of your choice (for example once per day, or once every 30 days).

AWS can also be configured to trigger Lambda from a number of other sources including email and SMS triggers. See Amazon's documentation on invoking Lambda for more options:

{% embed url="<https://docs.aws.amazon.com/lambda/latest/dg/lambda-invocation.html>" %}

## Next Steps

We encourage you to experiment with other Commander functionality, Lambda invocation methods, and other AWS services (such as SNS for utilizing various methods for push notifications -- including SMS messages) to bring automated value to your Keeper processes.

For some examples of using the Commander SDK code, see the example scripts in the Commander GitHub repo:

{% embed url="<https://github.com/Keeper-Security/Commander/tree/master/examples>" %}

To learn more about Commander's various methods, see the Command Reference section.

{% content-ref url="/pages/-McBE9TLEWh7hS-tYX14" %}
[Command Reference](/keeperpam/commander-cli/command-reference.md)
{% endcontent-ref %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.keeper.io/keeperpam/commander-cli/commander-installation-setup/configuration/using-commander-with-aws-lambda.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
