### Node.js Dockerfile Example Source: https://www.serverless.com/framework/docs/providers/aws/guide/agents Example Dockerfile for a Node.js agent. It sets up the Node.js environment, installs dependencies, copies code, and defines the entry point. ```dockerfile FROM node:20-slim WORKDIR /app COPY package*.json ./ RUN npm ci --omit=dev COPY . . CMD ["node", "index.js"] ``` -------------------------------- ### Python Dockerfile Example Source: https://www.serverless.com/framework/docs/providers/aws/guide/agents Example Dockerfile for a Python agent. It sets up the Python environment, installs dependencies from requirements.txt, copies code, and defines the entry point. ```dockerfile FROM python:3.12-slim WORKDIR /app COPY . . RUN pip install -r requirements.txt CMD ["python", "agent.py"] ``` -------------------------------- ### Install Serverless Webpack Plugin Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/plugin-install Installs the latest version of the serverless-webpack plugin. This is a common example for plugin installation. ```bash serverless plugin install --name serverless-webpack ``` -------------------------------- ### Install Serverless Framework Globally Source: https://www.serverless.com/framework/docs/getting-started Install the Serverless Framework globally using NPM. Ensure Node.js is installed first. ```bash npm i serverless -g ``` -------------------------------- ### Print Resolved Serverless.yml Configuration (Example) Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/print This example shows the output of 'sls print' with a sample serverless.yml file, demonstrating how variables like 'provider.stage' and 'custom.bucketName' are resolved. ```yaml service: my-service custom: bucketName: test provider: name: aws runtime: nodejs14.x functions: hello: handler: handler.hello resources: Resources: MyBucket: Type: AWS::S3::Bucket Properties: BucketName: ${self:custom.bucketName} ``` ```bash $ sls print service: my-service custom: bucketName: test provider: name: aws runtime: nodejs14.x stage: dev # <-- Resolved functions: hello: handler: handler.hello resources: Resources: MyBucket: Type: 'AWS::S3::Bucket' Properties: BucketName: test # <-- Resolved ``` -------------------------------- ### Example Serverless Framework Usage Output Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/usage This example shows the typical output after running the 'serverless usage' command, indicating the total instance credits used and the creation of the 'instances.csv' file. ```bash my-service $ serverless usage The serverlessinc org used 18 Instance Credits this month. A list of billable instances has been saved to instances.csv in the current directory. If you have any questions about your usage, please contact support@serverless.com. my-service $ ``` -------------------------------- ### Install Plugin via Serverless CLI Source: https://www.serverless.com/framework/docs/guides/plugins Use this command to install a plugin and automatically register it in your `serverless.yml` file. This is the recommended method for most users. ```bash serverless plugin install -n custom-serverless-plugin ``` -------------------------------- ### Fetch Agent Logs with Start Time Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/logs Fetch logs for an AgentCore Runtime agent starting from a specific time. This example fetches logs from the past hour. ```bash serverless logs -a myAgent --startTime 1h ``` -------------------------------- ### samconfig.toml Configuration Example Source: https://www.serverless.com/framework/docs/guides/sam Example of a samconfig.toml file, showing relevant properties for stack name, region, and template file. ```toml version = 0.1 [default.deploy.parameters] stack_name = "my-dev-stack" region = "us-east-1" template_file = "template.yml" # s3_bucket = "my-bucket" # parameter_overrides = "Environment=dev" ``` -------------------------------- ### Fetch Lambda Function Logs with Start Time Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/logs Fetch logs for a Lambda function starting from a specific time. This example fetches logs from the past 5 hours. ```bash serverless logs -f hello --startTime 5h ``` -------------------------------- ### Install a Serverless Plugin Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/plugin-install Installs the latest version of a specified plugin. The plugin name is required. ```bash serverless plugin install --name pluginName ``` -------------------------------- ### CommonJS esbuild Configuration with Plugin Source: https://www.serverless.com/framework/docs/providers/aws/guide/building Example of an esbuild configuration file using CommonJS syntax to include the `esbuild-plugin-env`. Ensure the plugin is installed. ```javascript const env = require('esbuild-plugin-env') module.exports = (serverless) => { return { external: ['@aws-sdk/client-s3'], plugins: [env()], } } ``` -------------------------------- ### Full Advanced Domain Configuration Example Source: https://www.serverless.com/framework/docs/providers/aws/guide/domains This example demonstrates comprehensive configuration of a custom domain with advanced settings including certificate ARN, Route53 record creation, endpoint types, and security policies. ```yaml provider: name: aws runtime: nodejs20.x domain: name: api.example.com basePath: v1 apiType: rest endpointType: regional certificateArn: arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012 createRoute53Record: true createRoute53IPv6Record: true hostedZoneId: Z1PA6795UKMFR9 securityPolicy: TLS_1_2 accessMode: strict enabled: true allowPathMatching: false preserveExternalPathMappings: false route53Params: TTL: 300 Comment: 'Custom domain for API' functions: hello: handler: src/hello.handler events: - http: path: /users method: get ``` -------------------------------- ### Install Serverless Framework CLI Source: https://www.serverless.com/framework/docs/guides/dashboard/cicd/running-in-your-own-cicd Install the Serverless Framework open-source CLI globally in your CI/CD environment. This is a prerequisite for performing deployments. ```bash npm install -g serverless ``` -------------------------------- ### Mock Integration with Custom Response Source: https://www.serverless.com/framework/docs/providers/aws/events/apigateway Set up a mock integration to simulate API responses without a backend. This example defines a simple mock response for a GET request to '/hello'. ```yaml functions: hello: handler: handler.hello events: - http: path: hello cors: true method: get integration: mock request: template: application/json: '{"statusCode": 200}' response: template: $input.path('$') statusCodes: 201: pattern: '' ``` -------------------------------- ### Run Script Before npm Install Source: https://www.serverless.com/framework/docs/guides/dashboard/cicd/custom-scripts Use the `preinstall` script in `package.json` to execute a command before npm installs dependencies. ```json { "name": "demo-serverless", "version": "1.0.0", "scripts": { "preinstall": "" } } ``` -------------------------------- ### AppSync Caching Configuration Source: https://www.serverless.com/framework/docs/providers/aws/guide/appsync/caching Quick start example for configuring AppSync caching with behavior, type, TTL, and encryption settings. ```yaml appSync: name: my-api caching: behavior: 'PER_RESOLVER_CACHING' type: 'SMALL' ttl: 3600 atRestEncryption: false transitEncryption: false ``` -------------------------------- ### Install Serverless SDK Package Source: https://www.serverless.com/framework/docs/guides/dashboard/monitoring/sdk/nodejs Install the core Serverless SDK package using npm or yarn. This is recommended for bundling the SDK with your handler to prevent unresolved references. ```bash npm install @serverless/sdk --save # or yarn add @serverless/sdk ``` -------------------------------- ### Run Script After npm Install Source: https://www.serverless.com/framework/docs/guides/dashboard/cicd/custom-scripts Use the `postinstall` script in `package.json` to execute a command after npm installs dependencies. ```json { "name": "demo-serverless", "version": "1.0.0", "scripts": { "postinstall": "" } } ``` -------------------------------- ### AWS Lambda Data Source Configuration Source: https://www.serverless.com/framework/docs/providers/aws/guide/appsync/dataSources Quick start example for configuring an AWS Lambda data source. Includes function timeout and handler settings. ```yaml appSync: dataSources: myFunction: type: 'AWS_LAMBDA' config: function: timeout: 30 handler: 'functions/myFunction.handler' ``` -------------------------------- ### ESM esbuild Configuration with Plugin Source: https://www.serverless.com/framework/docs/providers/aws/guide/building Example of an esbuild configuration file using ESM syntax to include the `esbuild-plugin-env`. Ensure `"type": "module"` is set in `package.json` and the plugin is installed. ```javascript /** * don't forget to set the "type": "module" property in `package.json` * and install the `esbuild-plugin-env` package */ import env from 'esbuild-plugin-env' export default (serverless) => { return { external: ['@aws-sdk/client-s3'], plugins: [env()], } } ``` -------------------------------- ### Install Plugin via NPM Source: https://www.serverless.com/framework/docs/guides/plugins Manually install a plugin using NPM. This method requires you to then register the plugin in your `serverless.yml`. ```bash npm install --save-dev custom-serverless-plugin ``` -------------------------------- ### Example Data File for Local Invocation Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/invoke-local An example JSON file structure for providing data to a local function invocation. ```json { "resource": "/", "path": "/", "httpMethod": "GET" // etc. // } ``` -------------------------------- ### Install Serverless SDK Package Source: https://www.serverless.com/framework/docs/guides/dashboard/monitoring/sdk/python Install the serverless-sdk package using pip. This is recommended to bundle the SDK with your handler to prevent unresolved references, especially when deploying manually or with certain infrastructure as code tools. ```bash pip install serverless-sdk ``` -------------------------------- ### Relational Database Data Source Configuration Source: https://www.serverless.com/framework/docs/providers/aws/guide/appsync/dataSources Quick start example for configuring a Relational Database data source. Requires database name, cluster identifier, and secret store ARN. ```yaml appSync: dataSources: myDatabase: type: 'RELATIONAL_DATABASE' config: databaseName: myDatabase dbClusterIdentifier: Ref: RDSCluster awsSecretStoreArn: Ref: RDSClusterSecret serviceRoleArn: !GetAtt RelationalDbServiceRole.Arn ``` -------------------------------- ### Install Requirements Manually Source: https://www.serverless.com/framework/docs/providers/aws/guide/python Use this command to manually create requirement files like `.requirements` and `unzip_requirements`. ```bash sls requirements install ``` -------------------------------- ### Monorepo Structure Example Source: https://www.serverless.com/framework/docs/guides/compose Illustrates a typical monorepo structure with multiple Serverless Framework services. ```yaml my-app/ service-a/ src/ ... serverless.yml service-b/ src/ ... serverless.yml ``` -------------------------------- ### Simple Domain Configuration Source: https://www.serverless.com/framework/docs/providers/aws/guide/domains Use this format for basic domain setups where only the domain name is required. ```yaml provider: domain: api.example.com ``` -------------------------------- ### Example Rollback Command Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/rollback-function This example demonstrates rolling back the function named 'my-function' to version '23'. First, list available function versions using `serverless deploy list functions`. ```bash serverless rollback function -f my-function --function-version 23 ``` -------------------------------- ### Install AWS SDK v3 npm Modules Source: https://www.serverless.com/framework/docs/tutorial Installs the necessary AWS SDK v3 modules for DynamoDB interaction. Run this command in your project's root directory. ```bash npm install @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb ``` -------------------------------- ### Serverless Logs Command Examples Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/logs Demonstrates various ways to use the serverless logs command, including fetching logs for functions and agents, tailing output, and filtering. ```bash # Lambda function logs serverless logs -f hello # Agent logs serverless logs -a myAgent # Optionally tail the logs with --tail or -t serverless logs -f hello -t serverless logs -a myAgent -t ``` -------------------------------- ### Navigate to Service Directory Source: https://www.serverless.com/framework/docs/getting-started Before deploying, ensure you are in the directory containing your `serverless.yml` file. ```bash cd [your-new-service-name] ``` -------------------------------- ### Curl Command to Test GET Endpoint Source: https://www.serverless.com/framework/docs/tutorial Example cURL command to test the newly deployed GET endpoint. Replace `[insert url here]` with the actual URL of your deployed endpoint. ```bash curl --url [insert url here]/customers ``` -------------------------------- ### Create a New App Source: https://www.serverless.com/framework/docs/getting-started When setting up a new service, you can choose to create a new app from a list of suggestions or skip this step. ```bash ❯ Create A New App ecommerce blog acmeinc Skip Adding An App ``` -------------------------------- ### Configure uv for Python Requirements Source: https://www.serverless.com/framework/docs/providers/aws/guide/python Enable uv for dependency management and installation. Ensure the uv CLI is available in the build environment. ```yaml custom: pythonRequirements: useUv: true # default installer: uv ``` -------------------------------- ### Fetch Lambda Function Logs from Epoch Time Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/logs Fetch logs for a Lambda function starting from a specific epoch timestamp. This example fetches logs starting at epoch '1469694264'. ```bash serverless logs -f hello --startTime 1469694264 ``` -------------------------------- ### NONE Data Source Configuration Source: https://www.serverless.com/framework/docs/providers/aws/guide/appsync/dataSources Example for configuring a NONE data source, typically used when no direct data source is needed. ```yaml appSync: dataSources: api: type: 'NONE' ``` -------------------------------- ### Complete Agent Runtime Configuration Source: https://www.serverless.com/framework/docs/providers/aws/guide/agents/runtime Example showing all configuration options for an agent runtime, including deployment, protocol, endpoints, networking, authentication, lifecycle, environment, headers, memory, gateway, and tags. ```yaml service: my-ai-service provider: name: aws region: us-east-1 ai: agents: myAgent: # Description description: Production AI agent with full configuration # Deployment (choose one approach) artifact: image: file: Dockerfile path: ./agent repository: my-agent-repo buildArgs: ENV: production # OR for code deployment: # handler: agent.py # runtime: python3.12 # Protocol protocol: HTTP # Endpoints (named access points for the runtime) endpoints: - name: production description: Tracks latest version - name: staging version: '1' description: Pinned to version 1 # Networking network: mode: PUBLIC # For VPC: # mode: VPC # subnets: [subnet-xxx] # securityGroups: [sg-xxx] # Authentication authorizer: type: CUSTOM_JWT jwt: discoveryUrl: https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxx/.well-known/openid-configuration allowedAudience: - my-client-id allowedClients: - my-client-id # Lifecycle lifecycle: idleRuntimeSessionTimeout: 900 maxLifetime: 3600 # Environment environment: MODEL_ID: us.anthropic.claude-sonnet-4-5-20250929-v1:0 LOG_LEVEL: INFO # Headers requestHeaders: allowlist: - X-Trace-Id # Memory - enables conversation persistence (see memory.md) # Automatically adds memory read/write permissions to the runtime role memory: myMemory # Gateway - connects tools to your agent (see gateway.md) # Automatically adds gateway invocation permissions to the runtime role gateway: myGateway # IAM Role role: statements: - Effect: Allow Action: s3:GetObject Resource: arn:aws:s3:::my-bucket/* # Metadata tags: Team: AI Environment: production ``` -------------------------------- ### Configure AWS SSO Automatically Source: https://www.serverless.com/framework/docs/guides/mcp/aws-integration Use this command to initiate the AWS CLI's guided setup for AWS SSO. ```bash aws configure sso ``` -------------------------------- ### HTTP Data Source Configuration Source: https://www.serverless.com/framework/docs/providers/aws/guide/appsync/dataSources Quick start example for configuring an HTTP data source. Specifies the endpoint URL for the external HTTP service. ```yaml appSync: dataSources: api: type: 'HTTP' config: endpoint: https://api.example.com ``` -------------------------------- ### DynamoDB Data Source Configuration Source: https://www.serverless.com/framework/docs/providers/aws/guide/appsync/dataSources Quick start example for configuring an Amazon DynamoDB data source. Specifies the table name and an optional description. ```yaml appSync: dataSources: myTableDs: type: AMAZON_DYNAMODB description: 'My table' config: tableName: my-table ``` -------------------------------- ### JavaScript Agent with Browser Tools Source: https://www.serverless.com/framework/docs/providers/aws/guide/agents/browser Example of setting up a JavaScript agent using PlaywrightBrowser for navigation, text extraction, and screenshots. Ensure you have the necessary dependencies installed. ```javascript import { BedrockAgentCoreApp } from 'bedrock-agentcore/runtime' import { PlaywrightBrowser } from 'bedrock-agentcore/browser/playwright' import { createAgent } from 'langchain' import { ChatBedrockConverse } from '@langchain/aws' import { tool } from '@langchain/core/tools' import { z } from 'zod' const browser = new PlaywrightBrowser({ region: 'us-east-1' }) // Define browser tools wrapping PlaywrightBrowser methods const navigate = tool( async ({ url }) => { await browser.navigate({ url, waitUntil: 'domcontentloaded' }) return `Navigated to ${url}` }, { name: 'navigate', description: 'Navigate to a URL in the browser.', schema: z.object({ url: z.string().describe('The URL to navigate to') }), }, ) const getText = tool( async ({ selector }) => { const text = await browser.getText({ selector }) return text || 'No text found' }, { name: 'get_text', description: 'Extract text content from elements.', schema: z.object({ selector: z.string().describe('CSS selector') }), }, ) const screenshot = tool( async () => { const data = await browser.screenshot() return `Screenshot captured (${data.length} bytes)` }, { name: 'screenshot', description: 'Take a screenshot of the current page.', schema: z.object({}), }, ) // Create agent with browser tools const model = new ChatBedrockConverse({ model: 'us.anthropic.claude-sonnet-4-20250514-v1:0', region: 'us-east-1', }) const agent = createAgent({ model, tools: [navigate, getText, screenshot], }) const app = new BedrockAgentCoreApp({ invocationHandler: { requestSchema: z.object({ prompt: z.string() }), async handler({ request }) { const result = await agent.invoke({ messages: [{ role: 'user', content: request.prompt }], }) return { response: result.messages.at(-1).content } }, }, }) app.run() ``` -------------------------------- ### Setting up a Python Virtual Environment Source: https://www.serverless.com/framework/docs/providers/aws/guide/agents/dev This snippet shows how to create and activate a Python virtual environment. It's recommended for code mode to manage dependencies and isolate the project environment. ```bash python3 -m venv venv source venv/bin/activate # Linux/macOS # or: venv\Scripts\activate # Windows pip install -r requirements.txt ``` -------------------------------- ### Create a New Serverless Project Source: https://www.serverless.com/framework/docs/examples-and-tutorials Run this command to create a new project based on built-in templates. You will be prompted to choose a template from a list. ```bash serverless ``` -------------------------------- ### OpenSearch Data Source Configuration Source: https://www.serverless.com/framework/docs/providers/aws/guide/appsync/dataSources Quick start example for configuring an Amazon OpenSearch Service data source. Requires the endpoint URL of the OpenSearch domain. ```yaml appSync: dataSources: search: type: 'AMAZON_OPENSEARCH_SERVICE' config: endpoint: https://abcdefgh.us-east-1.es.amazonaws.com ``` -------------------------------- ### Start Hybrid Development Mode Source: https://www.serverless.com/framework/docs/getting-started Use this command for rapid development by proxying events to your local machine while using live cloud functions. This command is intended for development or personal stages only. ```bash serverless dev ``` -------------------------------- ### Full Websocket Configuration Example Source: https://www.serverless.com/framework/docs/providers/aws/events/websocket A comprehensive Serverless YAML configuration defining handlers for `$connect`, `$disconnect`, `$default`, and a custom `foo` route, with custom API Gateway settings. ```yaml service: serverless-ws-test provider: name: aws runtime: nodejs14.x websocketsApiName: custom-websockets-api-name websocketsApiRouteSelectionExpression: $request.body.action # custom routes are selected by the value of the action property in the body websocketsDescription: Custom Serverless Websockets functions: connectionHandler: handler: handler.connectionHandler events: - websocket: route: $connect - websocket: route: $disconnect defaultHandler: handler: handler.defaultHandler events: - websocket: $default #simple event definition without extra route property customFooHandler: handler: handler.fooHandler events: - websocket: route: foo # will trigger if $request.body.action === "foo" ``` -------------------------------- ### Python Agent Code for AWS Bedrock AgentCore Source: https://www.serverless.com/framework/docs/providers/aws/guide/agents Example Python code for an AI agent using the bedrock-agentcore library. Requires agent setup and defines an entrypoint for agent invocation. ```python from bedrock_agentcore.runtime import BedrockAgentCoreApp # Your agent setup - use any framework (LangGraph, Strands Agents, CrewAI, etc.) agent = create_your_agent() app = BedrockAgentCoreApp() @app.entrypoint def agent_invocation(payload, context): # Your agent logic result = agent.invoke(payload.get("prompt")) return {"result": result} app.run() ``` -------------------------------- ### JavaScript Agent Code for AWS Bedrock AgentCore Source: https://www.serverless.com/framework/docs/providers/aws/guide/agents Example JavaScript code for an AI agent using the bedrock-agentcore library. Requires agent setup and defines an invocation handler with request schema validation. ```javascript import { BedrockAgentCoreApp } from 'bedrock-agentcore/runtime' import { z } from 'zod' // Your agent setup - use any framework (LangGraph, Strands Agents, CrewAI, etc.) const agent = createYourAgent() const app = new BedrockAgentCoreApp({ invocationHandler: { requestSchema: z.object({ prompt: z.string(), }), async process(request) { // Your agent logic const result = await agent.invoke(request.prompt) return result }, }, }) app.run() ``` -------------------------------- ### AppSync Custom Domain Configuration with Stage Parameters Source: https://www.serverless.com/framework/docs/providers/aws/guide/appsync/custom-domain Demonstrates how to configure different custom domains and certificate ARNs for various deployment stages (prod, staging, default) using Serverless Framework stage parameters. ```yaml params: prod: domain: api.example.com domainCert: arn:aws:acm:us-east-1:123456789012:certificate/7e14a3b2-f7a5-4da5-8150-4a03ede7158c staging: domain: qa.example.com domainCert: arn:aws:acm:us-east-1:123456789012:certificate/61d7d798-d656-4630-9ff9-d77a7d616dbe default: domain: ${sls:stage}.example.com domainCert: arn:aws:acm:us-east-1:123456789012:certificate/44211071-e102-4bf4-b7b0-06d0b78cd667 appSync: name: my-api domain: name: ${param:domain} certificateArn: ${param:domainCert} ``` -------------------------------- ### HTTP API Gateway Event with Path Parameters Source: https://www.serverless.com/framework/docs/providers/aws/guide/events Configures an HTTP API Gateway event to capture path parameters. This example shows how to define a GET endpoint that accepts a user ID as a path parameter. ```yaml functions: createUser: # Function name handler: handler.users # Reference to file handler.js & exported function 'users' events: # All events associated with this function - httpApi: 'GET /users/{id}' ``` -------------------------------- ### Example Serverless Info Output with Verbose Flag Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/info Illustrates the output when the --verbose flag is used, appending Stack Outputs to the standard information. ```text Service Information service: my-serverless-service stage: dev region: us-east-1 api keys: myKey: some123valid456api789key1011for1213api1415gateway endpoints: GET - https://dxaynpuzd4.execute-api.us-east-1.amazonaws.com/dev/users functions: my-serverless-service-dev-hello Stack Outputs CloudFrontUrl: d2d10e2tyk1pei.cloudfront.net ScreenshotBucket: dev-svdgraaf-screenshots ServiceEndpoint: https://12341jc801.execute-api.us-east-1.amazonaws.com/dev ServerlessDeploymentBucketName: lambda-screenshots-dev-serverlessdeploymentbucket-15b7pkc04f98a ``` -------------------------------- ### Example Data JSON Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/invoke An example JSON structure for event data. ```json { "resource": "/", "path": "/", "httpMethod": "GET" // etc. // } ``` -------------------------------- ### Select a Serverless Framework Service Template Source: https://www.serverless.com/framework/docs/getting-started Choose a template from the interactive prompt to scaffold your Serverless Framework service. Templates are available for various languages and use cases, such as Node.js or Python with HTTP APIs or scheduled tasks. ```bash Serverless ϟ Framework Welcome to Serverless Framework V.4 Create a new project by selecting a Template to generate scaffolding for a specific use-case. ? Select A Template: … ❯ AWS / Node.js / Starter AWS / Node.js / HTTP API AWS / Node.js / Scheduled Task AWS / Node.js / SQS Worker AWS / Node.js / Express API AWS / Node.js / Express API with DynamoDB AWS / Python / Starter AWS / Python / HTTP API AWS / Python / Scheduled Task AWS / Python / SQS Worker AWS / Python / Flask API AWS / Python / Flask API with DynamoDB (Scroll for more) ``` -------------------------------- ### Basic Package Command Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/package Packages your service using default stage ('dev') and region ('us-east-1'). The output is placed in the default '.serverless' directory. ```bash serverless package ``` -------------------------------- ### Serverless Deploy from Pre-packaged Directory Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/deploy Deploy a pre-packaged artifact, skipping the packaging step. Specify the path to your package directory. ```bash serverless deploy --package /path/to/package/directory ``` -------------------------------- ### Configure Build Step for Deployment Source: https://www.serverless.com/framework/docs/guides/dashboard/cicd/running-in-your-own-cicd In your CI/CD pipeline, run these commands on each deployment. First, install project dependencies and plugins, then execute the serverless deploy command. ```bash npm install # installs all plugins and packages serverless deploy # deploys your service ``` -------------------------------- ### Install Specific Version of Serverless Webpack Plugin Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/plugin-install Installs a specific version of the serverless-webpack plugin. Use the '@' symbol to denote the version. ```bash serverless plugin install --name serverless-webpack@3.0.0-rc.2 ``` -------------------------------- ### Example Serverless Info Output in JSON Format Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/info Demonstrates the JSON output of the serverless info command, providing structured data for service details and CloudFormation stack outputs. ```json { "info": { "functions": [ { "name": "hello", "deployedName": "my-serverless-service-dev-hello" } ], "layers": [], "endpoints": [ "httpApi: https://mnpgyjhfqj.execute-api.us-east-1.amazonaws.com" ], "service": "my-serverless-service", "stage": "dev", "region": "us-east-1", "stack": "my-serverless-service-dev", "resourceCount": 4, "apiKeys": [] }, "outputs": [ { "OutputKey": "HelloLambdaFunctionQualifiedArn", "OutputValue": "arn:aws:lambda:us-east-1:012345678901:function:my-serverless-service-dev-hello:26", "Description": "Current Lambda function version", "ExportName": "sls-my-serverless-service-dev-hello-HelloLambdaFunctionQualifiedArn" }, { "OutputKey": "ServerlessDeploymentBucketName", "OutputValue": "serverless-framework-deployments-us-east-1-d7b2bf38-2784", "ExportName": "sls-my-serverless-service-dev-ServerlessDeploymentBucketName" }, { "OutputKey": "HttpApiId", "OutputValue": "mnpgyjhfqj", "Description": "Id of the HTTP API", "ExportName": "sls-my-serverless-service-dev-HttpApiId" }, { "OutputKey": "HttpApiUrl", "OutputValue": "https://mnpgyjhfqj.execute-api.us-east-1.amazonaws.com", "Description": "URL of the HTTP API", "ExportName": "sls-my-serverless-service-dev-HttpApiUrl" } ] } ``` -------------------------------- ### Dry Run Output Example Source: https://www.serverless.com/framework/docs/providers/aws/guide/prune Example output from a dry run, showing which versions are selected for deletion and confirming that no actions were performed. ```text Prune: myFunction:4 selected for deletion. Prune: myFunction:3 selected for deletion. Prune: Dry-run enabled, no pruning actions will be performed. ``` -------------------------------- ### Define a Simple Websocket Connect Event Source: https://www.serverless.com/framework/docs/providers/aws/events/websocket Sets up a basic websocket handler for the `$connect` route. ```yaml functions: connectHandler: handler: handler.connectHandler events: - websocket: $connect ``` -------------------------------- ### Configure GET Endpoint in serverless.yml Source: https://www.serverless.com/framework/docs/tutorial Defines the Lambda function `getCustomers` and configures an HTTP API endpoint at `/customers` for the GET method. ```yaml getCustomers: handler: getCustomers.getCustomers events: - httpApi: path: /customers method: get ``` -------------------------------- ### Sign In to Serverless Framework CLI Source: https://www.serverless.com/framework/docs/getting-started Run this command to log in to your Serverless Framework account via the CLI. This will open a browser for authentication. ```bash serverless login ``` -------------------------------- ### Basic Browser Integration Source: https://www.serverless.com/framework/docs/providers/aws/guide/agents/browser Initialize AgentCoreBrowser and create an agent with browsing capability. Use this for general web research tasks. ```python from strands import Agent from strands_tools.browser import AgentCoreBrowser # Initialize browser (uses AWS-managed default) browser_tool = AgentCoreBrowser(region="us-east-1") # Create agent with browser capability agent = Agent( tools=[browser_tool.browser], model="us.anthropic.claude-sonnet-4-20250514-v1:0", system_prompt="""You are a research assistant that can browse the web. When asked about current information, use the browser to find answers.""" ) # Use the agent result = agent("What are the latest AWS announcements?") ``` -------------------------------- ### Vault Secret Structure Example Source: https://www.serverless.com/framework/docs/guides/variables/hashicorp/vault This is an example of the expected JSON structure for a secret stored in HashiCorp Vault, which allows for nested key access. ```json { "credentials": { "password": "abc123" } } ``` -------------------------------- ### Start MCP Server with SSE Transport Source: https://www.serverless.com/framework/docs/guides/mcp/setup Manually start the MCP server with SSE transport enabled. This command is used for SSE connections. ```bash serverless mcp --transport sse ``` -------------------------------- ### Agent Configuration with Gateway (Custom Tools) Source: https://www.serverless.com/framework/docs/providers/aws/guide/agents Set up custom tools and gateways for your agent. Define tool schemas, associate functions, and reference the gateway by name in the agent's configuration. ```yaml ai: tools: calculator: function: calculatorFunction toolSchema: - name: calculate description: Perform calculations inputSchema: type: object properties: expression: type: string required: - expression gateways: default: tools: - calculator agents: myAgent: gateway: default # Reference gateway by name ``` -------------------------------- ### TypeScript Resolver Code Example Source: https://www.serverless.com/framework/docs/providers/aws/guide/appsync/resolvers Example of a TypeScript request and response function for an AWS AppSync resolver. It uses '@aws-appsync/utils' for context and DynamoDB operations. ```typescript // getUser.ts import { Context, util } from '@aws-appsync/utils' export function request(ctx: Context) { const { args: { id }, } = ctx return { operation: 'GetItem', key: util.dynamodb.toMapValues({ id }), } } export function response(ctx: Context) { return ctx.result } ``` -------------------------------- ### Lambda@Edge Handler Function Example Source: https://www.serverless.com/framework/docs/providers/aws/events/cloudfront An example Node.js handler function for Lambda@Edge that adds a custom timestamp header to the CloudFront response. ```javascript // index.handler 'use strict' module.exports.handler = (event, context, callback) => { const response = event.Records[0].cf.response const headers = response.headers headers['x-serverless-time'] = [ { key: 'x-serverless-time', value: Date.now().toString() }, ] return callback(null, response) } ``` -------------------------------- ### Structured Log Example Source: https://www.serverless.com/framework/docs/guides/dashboard/monitoring/sdk/python Example of a structured log output for errors and warnings. This format is human-readable and parsable by tools like CloudWatch Log Insights. ```json { "source": "serverlessSdk", "type": "ERROR_TYPE_CAUGHT_USER", "message": "User not found", "stackTrace": "...", "tags": { "userId": "eb661c69405c" } } ``` -------------------------------- ### Example Lambda Integration Event Structure Source: https://www.serverless.com/framework/docs/providers/aws/events/apigateway This is an example of the event structure for a non-default `LAMBDA` integration method. Refer to this structure when using the `LAMBDA` integration method. ```json { "body": {}, "method": "GET", "principalId": "", "stage": "dev", "cognitoPoolClaims": { "sub": "" }, "enhancedAuthContext": {}, "headers": { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-GB,en-US;q=0.8,en;q=0.6,zh-CN;q=0.4", "CloudFront-Forwarded-Proto": "https", "CloudFront-Is-Desktop-Viewer": "true", "CloudFront-Is-Mobile-Viewer": "false", "CloudFront-Is-SmartTV-Viewer": "false", "CloudFront-Is-Tablet-Viewer": "false", "CloudFront-Viewer-Country": "GB", "Host": "ec5ycylws8.execute-api.us-east-1.amazonaws.com", "upgrade-insecure-requests": "1", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Via": "2.0 f165ce34daf8c0da182681179e863c24.cloudfront.net (CloudFront)", "X-Amz-Cf-Id": "l06CAg2QsrALeQcLAUSxGXbm8lgMoMIhR2AjKa4AiKuaVnnGsOFy5g==", "X-Amzn-Trace-Id": "Root=1-5970ef20-3e249c0321b2eef14aa513ae", "X-Forwarded-For": "94.117.120.169, 116.132.62.73", "X-Forwarded-Port": "443", "X-Forwarded-Proto": "https" }, "query": {}, "path": {}, "identity": { "cognitoIdentityPoolId": "", "accountId": "", "cognitoIdentityId": "", "caller": "", "apiKey": "", "sourceIp": "94.197.120.169", "accessKey": "", "cognitoAuthenticationType": "", "cognitoAuthenticationProvider": "", "userArn": "", "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "user": "" }, "stageVariables": {}, "requestPath": "/request/path" } ``` -------------------------------- ### Display Serverless Framework Instance Credit Usage Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/usage Run this command to view your organization's current month's instance credit usage. It also generates an 'instances.csv' file with a list of billable instances. ```bash serverless usage ``` -------------------------------- ### MSK Event with Batching and Starting Position Source: https://www.serverless.com/framework/docs/providers/aws/events/msk Configures an MSK event source for a Lambda function with custom batch size, maximum batching window, and starting position. ```yaml functions: compute: handler: handler.compute events: - msk: arn: arn:aws:kafka:region:XXXXXX:cluster/MyCluster/xxxx-xxxxx-xxxx topic: mytopic batchSize: 1000 maximumBatchingWindow: 30 startingPosition: LATEST ``` -------------------------------- ### Lambda Function Configuration Example Source: https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml Illustrates a comprehensive set of configuration options for an AWS Lambda function, covering logging, tenancy, VPC, Lambda URLs, packaging, layers, tracing, conditional deployment, destinations, and file system mounting. ```yaml # The System Log Level to be used, This can only be set if `logFormat` is set to `JSON` systemLogLevel: INFO # The LogGroup that will be used by default. If this is set the Framework will not create LogGroups for any functions logGroup: /aws/lambda/global-log-group # The CloudWatch Logs log group class for this function (default: standard). # Valid values: standard, infrequent_access. Matched case-insensitively. # Overrides the provider-level value. Cannot be combined with a custom # logs.logGroup name. logGroupClass: infrequent_access # Enable AWS Lambda tenant isolation mode for this function tenancy: mode: per_tenant tags: # Function specific tags foo: bar # VPC settings for this function # If you use VPC then both subproperties (securityGroupIds and subnetIds) are required # Can be set to '~' to disable the use of a VPC vpc: securityGroupIds: - securityGroupId1 - securityGroupId2 subnetIds: - subnetId1 - subnetId2 # Lambda URL definition for this function, optional # Can be defined as `true` which will create URL without authorizer and cors settings url: authorizer: 'aws_iam' # Authorizer used for calls to Lambda URL cors: # CORS configuration for Lambda URL, can also be defined as `true` with default CORS configuration allowedOrigins: - * allowedHeaders: - Authorization allowedMethods: - GET allowCredentials: true exposedResponseHeaders: - SomeHeader maxAge: 3600 # Packaging rules specific to this function package: # Directories and files to include in the deployed package patterns: - src/** - handler.js - '!\.git/**' - '!\.travis.yml' # Explicitly set the package artifact to deploy (overrides native packaging behavior) artifact: path/to/my-artifact.zip # Package this function as an individual artifact (default: false) individually: true # ARN of Lambda layers to use layers: - arn:aws:lambda:region:XXXXXX:layer:LayerName:Y # Overrides the provider setting. Can be 'Active' or 'PassThrough' tracing: Active # Conditionally deploy the function condition: SomeCondition # CloudFormation 'DependsOn' option dependsOn: - MyThing - MyOtherThing # Lambda destination settings destinations: # Function name or ARN (or reference) of target (EventBridge/SQS/SNS topic) onSuccess: functionName # Function name or ARN (or reference) of target (EventBridge/SQS/SNS topic) onFailure: arn:xxx:target onFailure: type: sns arn: Ref: SomeTopicName # Mount a file system (EFS or S3 Files) fileSystemConfig: # ARN of EFS or S3 Files Access Point arn: arn:aws:elasticfilesystem:us-east-1:11111111:access-point/fsap-a1a1a1 # Path under which the file system will be mounted and accessible in Lambda localMountPath: /mnt/example # File system type - auto-detected from ARN, required for CF references with S3 Files # type: efs | s3files # Maximum retry attempts when an asynchronous invocation fails (between 0 and 2; default: 2) maximumRetryAttempts: 1 # Maximum event age in seconds when invoking asynchronously (between 60 and 21600) maximumEventAge: 7200 ``` -------------------------------- ### Example Serverless Info Output Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/info Shows the typical output of the serverless info command, detailing service, stage, region, API keys, endpoints, and functions. ```text Service Information service: my-serverless-service stage: dev region: us-east-1 api keys: myKey: some123valid456api789key1011for1213api1415gateway endpoints: GET - https://dxaynpuzd4.execute-api.us-east-1.amazonaws.com/dev/users functions: my-serverless-service-dev-hello ``` -------------------------------- ### Install OS Dependencies with Dockerfile Source: https://www.serverless.com/framework/docs/providers/aws/guide/python Use a custom Dockerfile to install OS dependencies required by Python packages during the build process. This is useful when packages need specific libraries to compile. ```docker FROM public.ecr.aws/sam/build-python3.9 # Install your dependencies RUN yum -y install mysql-devel ``` ```yaml custom: pythonRequirements: dockerFile: Dockerfile ``` -------------------------------- ### Using Custom S3 Bucket for State Management Source: https://www.serverless.com/framework/docs/guides/state Example serverless-compose.yml demonstrating how to configure a custom S3 bucket for state storage using resolvers. The specified bucket must be versioned. ```yaml state: my-s3-state-resolver stages: default: resolvers: my-aws-account: type: aws my-s3-state-resolver: type: s3 bucketName: my-custom-state-bucket services: service-a: path: service-a service-b: path: service-b params: queueUrl: ${service-a.queueUrl} ``` -------------------------------- ### Install Private Git Repositories with Docker Source: https://www.serverless.com/framework/docs/providers/aws/guide/python Enable installation of requirements from private Git repositories using Docker. This option mounts your SSH keys into the Docker container. Add this to your serverless.yml. ```yaml custom: pythonRequirements: dockerizePip: true dockerSsh: true ``` -------------------------------- ### Install AWS Lambda SDK Package Source: https://www.serverless.com/framework/docs/guides/dashboard/monitoring/sdk/nodejs Install the `@serverless/aws-lambda-sdk` package locally when using a bundler. This package replaces the need for the core `@serverless/sdk` package and enables auto-instrumentation for AWS-specific APIs and Express.js. ```bash npm install @serverless/aws-lambda-sdk --save # or yarn add @serverless/aws-lambda-sdk ``` -------------------------------- ### Name Your Serverless Framework Service Source: https://www.serverless.com/framework/docs/getting-started Provide a name for your Serverless Framework service during the interactive setup. Service names should use lowercase letters, numbers, and hyphens, and be kept short as they are incorporated into cloud resource names. ```bash ? Name Your Service: › ``` -------------------------------- ### Serverless.yml Variable Syntax Source: https://www.serverless.com/framework/docs/guides/variables Demonstrates the basic syntax for using variables in serverless.yml, including referencing provider values and providing default values. ```yaml yamlKeyXYZ: ${provider:resolver:key} otherYamlKey: ${provider:resolver:key, defaultValue} ``` -------------------------------- ### Print Specific Provider Name Source: https://www.serverless.com/framework/docs/providers/aws/cli-reference/print Use the '--path' option to print a specific value from the configuration. This example prints only the provider's name in text format. ```bash sls print --path provider.name --format text ``` -------------------------------- ### Get a Specific Output via CLI Source: https://www.serverless.com/framework/docs/guides/dashboard/output-variables Retrieve a specific output value using the `sls output get` command, which requires the `--name ` flag. Optional flags can specify the organization, application, service, stage, or region. ```bash sls output get --name [--org ] [--app ] [--service ] [--stage ] [--region region] ``` -------------------------------- ### docs Source: https://www.serverless.com/framework/docs/guides/mcp/tools Access comprehensive documentation for Serverless Framework (sf) and Serverless Container Framework (scf). It requires the product and optionally accepts an array of document paths. ```APIDOC ## docs ### Description Access comprehensive, always up-to-date documentation for Serverless Framework (sf) and Serverless Container Framework (scf) including code examples and usage patterns. ### Inputs - **product** (string): Product to get documentation for. Must be one of: sf, scf. - **paths** (string[], optional): Array of document paths to retrieve multiple documents in a single request. Paths are relative to the product base directory. If not provided, lists all available documents. ### Returns Documentation content or directory listing, including markdown content of requested documents, tree-like structure of available documentation, suggestions for alternative paths when requested documents don't exist. ```