AWS Services

Integrating Nomad Media with AWS Lambda and SQS.

AWS Services

Send Message to SQS from Lambda

This guide shows how to create a Lambda function that sends a message to an AWS SQS queue, in both JavaScript and Python.

Prerequisites

  • An AWS account with permissions to create SQS queues, Lambda functions, and IAM policies/roles.

Step 1: Create an SQS Queue

Go to the Amazon SQS homepage and click Create Queue. Choose your queue type (Standard or FIFO) and give it a name. Scroll to the bottom and click Create queue. Copy the queue ARN and URL — you’ll need them below.

Step 2: Create the Lambda Function

Go to the Lambda homepage and click Create function.

JavaScript (Node.js 20.x):

import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs';

const SQS_CLIENT = new SQSClient({ region: 'us-west-2' });
const SQS_URL = process.env.SQS_URL;

const handler = async (event) => {
    try {
        const PARAMS = {
            MessageBody: 'Hello World',
            QueueUrl: SQS_URL
        };

        const COMMAND = new SendMessageCommand(PARAMS);
        const RESULT = await SQS_CLIENT.send(COMMAND);

        return {
            statusCode: 200,
            body: `messageId: ${RESULT.MessageId}`
        };
    } catch (error) {
        console.error('Error:', error);
        return {
            statusCode: 500,
            body: JSON.stringify(`Error sending message to SQS: ${error.message}`),
        };
    }
};

export { handler };

Python (Python 3.12):

import boto3
import os

sqs = boto3.client('sqs', region_name='us-west-2')
sqs_url = os.environ['SQS_URL']

def lambda_handler(event, context):
    try:
        params = {
            'MessageBody': 'Hello World',
            'QueueUrl': sqs_url
        }

        response = sqs.send_message(**params)

        return {
            'statusCode': 200,
            'body': f"MessageId: {response['MessageId']}"
        }
    except Exception as e:
        print(f"Error: {e}")
        return {
            'statusCode': 500,
            'body': f"Error sending message to SQS: {str(e)}"
        }

Click Deploy to save the code.

Step 3: Create an SQS IAM Policy

  1. Go to IAM → PoliciesCreate policy
  2. Select SQS as the service
  3. Under Actions allowed, select SendMessage (under Write)
  4. Under Resources, select Specific and add the ARN of the SQS queue you created
  5. Click Next, give the policy a name, and click Create policy

Step 4: Create an IAM Role for the Lambda

  1. Go to IAM → RolesCreate role
  2. Select AWS service as the trusted entity type, then select Lambda as the use case
  3. Attach the SQS policy you just created
  4. Give the role a name and click Create role

Step 5: Attach the Role to the Lambda

  1. In your Lambda, go to ConfigurationGeneral configurationEdit
  2. Set the Timeout to 1 minute
  3. Under Execution role, select Use an existing role and choose the role you created
  4. Click Save

Step 6: Add the SQS URL as an Environment Variable

  1. In your Lambda, go to ConfigurationEnvironment variablesEdit
  2. Add a new variable: Key = SQS_URL, Value = the URL of your SQS queue
  3. Click Save

Step 7: Test

Go to the Code tab and click Test. Create a test event with any name and click Save, then Test again. On success, the response shows statusCode: 200 and a messageId. Go to your SQS queue, click Send and receive messages, then Poll for messages to verify the message was received.


Using the Nomad Media SDK in AWS Lambda

This guide shows how to set up a Lambda function that uses the Nomad Media SDK (@nomad-media/full for JavaScript, nomad-media-pip for Python) to sync content — using AWS Secrets Manager for credentials.

JavaScript (Node.js 20.x)

Prerequisites

Review the SDK JavaScript documentation for SDK setup.

Step 1: Store Credentials in Secrets Manager

  1. Go to Secrets Manager → Store a new secret
  2. Select Other type of secret
  3. Enter your Nomad Media username (user) and password (password) as key/value pairs
  4. Give the secret a name and store it
  5. Copy the Secret ARN

Step 2: Create an IAM Policy for Secrets Access

  1. Go to IAM → PoliciesCreate policy
  2. Select Secrets Manager as the service
  3. Under Actions allowed, select GetSecretValue (under Read)
  4. Under Resources, select Specific and add the ARN of your secret
  5. Create the policy with a name

Step 3: Create an IAM Role with the Policy

  1. Go to IAM → RolesCreate role
  2. Select AWS service / Lambda
  3. Attach the Secrets Manager policy
  4. Create the role with a name

Step 4: Create the Lambda with the Role

  1. Go to Lambda → Create function
  2. Select Node.js 20.x as the runtime
  3. Under Change default execution role, select Use an existing role and choose the role you created
  4. Click Create function

Step 5: Install and Upload the SDK Package

In a local directory:

npm install @nomad-media/full --save
npm install fs --save

Zip the directory and upload it to the Lambda via Upload from.zip file. Move the three files from the zip subfolder to the top-level directory in the Lambda code editor.

Step 6: Initialize Secrets and SDK

import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
import { fromEnv } from "@aws-sdk/credential-provider-env";
import NomadMediaSDK from "@nomad-media/full";

const SECRET_NAME = "my-secret";
const REGION_NAME = "us-west-2";

const SECRETS_MANAGER = new SecretsManagerClient({
    region: REGION_NAME,
    credentials: fromEnv(),
});

async function getSecret() {
    const command = new GetSecretValueCommand({ SecretId: SECRET_NAME });
    try {
        const data = await SECRETS_MANAGER.send(command);
        return JSON.parse(data.SecretString);
    } catch (error) {
        console.error(error);
    }
}

const SECRETS = await getSecret();

const config = {
    username: SECRETS.user,
    password: SECRETS.password,
    serviceApiUrl: "YOUR_SERVICE_API_URL",
    apiType: "admin",
    debugMode: false
};

const NomadSDK = new NomadMediaSDK(config);

Note: For SECRET_NAME, do not include the alphanumeric suffix after the name.

Step 7: Use the SDK in Your Lambda

Wrap your sync logic so the Lambda handler calls the sync function. In the Configuration tab, increase the Timeout as needed (syncing large datasets takes longer than the default 3 seconds).

Example: Movie Database Sync

import NomadMediaSDK from "@nomad-media/full";
import fs from 'fs';

const GENRE_CONTENT_DEFINITION_ID = "dbbace1f-ddb1-462b-9cae-c9be7d5990ac";
const MOVIE_CONTENT_DEFINITION_ID = "eb710e28-7c44-492e-91f9-8acd0cd9331c";

// ... (full sync sample available in samples-javascript repo)

async function sync() {
    const MOVIES = await get_movies();
    const JSON_MOVIES = JSON.parse(fs.readFileSync('movie.json', 'utf8'));

    for (let index = 0; index < JSON_MOVIES.length; index++) {
        const MOVIE = MOVIES.find(m => m.identifiers?.movieId === JSON_MOVIES[index].id) || null;
        await check_movie(index, MOVIE, JSON_MOVIES[index], JSON_MOVIES.length);
    }
}

Note: Replace the content definition ID constants with values from your environment. A full runnable sample is in the samples-javascript repository.

Python (Python 3.12)

Step 1: Store Credentials in Secrets Manager

Same as JavaScript — store user and password as key/value pairs in a Secrets Manager secret.

Step 2: Create IAM Policy, Role, and Lambda

Same as JavaScript — create a Secrets Manager GetSecretValue policy, attach it to a Lambda execution role, create a Python 3.12 Lambda with that role.

Step 3: Create a Lambda Layer for the SDK

  1. Go to Lambda → LayersCreate layer
  2. Upload the nomad_media_sdk_pip zip file (available in the samples-python repo)
  3. Select Python 3.12 as the compatible runtime
  4. Create the layer

In your Lambda function, go to Code → scroll to LayersAdd a layerCustom layers → select the layer you created.

Step 4: Initialize Secrets and SDK

import boto3
import json

secret_name = "my-secret"
region_name = "us-west-2"

session = boto3.session.Session()
client = session.client(service_name="secretsmanager", region_name=region_name)

get_secret_value_response = client.get_secret_value(SecretId=secret_name)
secret = json.loads(get_secret_value_response["SecretString"])

config = {
    "username": secret["user"],
    "password": secret["password"],
    "serviceApiUrl": "YOUR_SERVICE_API_URL",
    "apiType": "admin",
    "debugMode": False
}

Note: A full runnable Python sync sample is in the samples-python repository.