0Pricing
Serverless Backend with AWS Lambda & API Gateway · Урок

Развёртывание приложений SAM

Используйте SAM CLI для сборки, локального тестирования и развёртывания бессерверных приложений в AWS, управляя разными окружениями

«Развёртывание приложений SAM» — бесплатный урок Serverless Backend with AWS Lambda & API Gateway на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Serverless Backend with AWS Lambda & API Gateway, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Serverless Backend with AWS Lambda & API Gateway содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Introduction to SAM CLI

Welcome to deploying SAM applications! The AWS Serverless Application Model Command Line Interface (SAM CLI) is your best friend for building and managing serverless projects.

It extends AWS CloudFormation to simplify defining serverless resources. The SAM CLI provides commands to build, test, and deploy your serverless applications.

Building Your Application

Before deploying, your SAM application needs to be built. The sam build command takes your application code and dependencies, then prepares them for deployment.

  • It packages dependencies (e.g., Python libraries).
  • It transpiles code if needed (e.g., TypeScript to JavaScript).
  • It creates a deployable artifact in a .aws-sam/build directory.

Example Lambda Function

Let's look at a simple Python Lambda function and its template.yaml. The sam build command processes this to create deployable code.

After running sam build, the packaged code would be ready for local testing or deployment.

import json

def lambda_handler(event, context):
    """
    A simple Lambda handler.
    """
    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json"
        },
        "body": json.dumps({
            "message": "Hello from your SAM Lambda!"
        })
    }

Local Testing with `sam local invoke`

The SAM CLI allows you to test your Lambda functions locally without deploying them to AWS, saving time and costs. Use sam local invoke to simulate a Lambda invocation.

You can pass event data directly to your function, just like how AWS services (like API Gateway or S3) would trigger it.

Running a Lambda Locally

To test the Lambda function from the previous scene, you'd use sam local invoke with the logical ID of your function and an event file.

For example, sam local invoke MyHelloWorldFunction --event event.json would test a function named 'MyHelloWorldFunction' using the data in event.json.

{
  "httpMethod": "GET",
  "path": "/hello",
  "queryStringParameters": null,
  "headers": {
    "Accept": "*/*"
  },
  "body": null
}

Local API Testing with `sam local start-api`

If your SAM application includes an API Gateway, you can simulate the entire API locally using sam local start-api. This command starts a local web server that mimics API Gateway.

You can then send HTTP requests to http://127.0.0.1:3000 and test your API endpoints end-to-end, locally.

Preparing for Deployment: `sam deploy`

Once your application is built and tested locally, you're ready to deploy it to AWS. The sam deploy command is used for this.

It packages your application artifacts, uploads them to an S3 bucket, and then uses AWS CloudFormation to deploy your serverless resources.

Your First Guided Deployment

For your first deployment, using the --guided flag is highly recommended. It will walk you through setting up necessary parameters interactively.

  • Stack Name: Unique identifier for your CloudFormation stack.
  • AWS Region: Where to deploy your resources.
  • S3 Bucket: For storing deployment artifacts.
  • Capabilities: Acknowledging IAM resource creation.

Example: sam deploy --guided

Managing Multiple Environments

In real-world scenarios, you'll often have development, staging, and production environments. SAM CLI helps manage this by allowing you to specify different stack names and parameters.

  • Use distinct Stack Names (e.g., my-app-dev, my-app-prod).
  • Use --parameter-overrides to pass different values for environment-specific configurations (e.g., database names, API keys).

Quick Check

Which SAM CLI command is used to test your API Gateway endpoints locally?

Recap & Next Steps

Congratulations! You've learned the essential steps for building, testing, and deploying serverless applications using the SAM CLI.

  • sam build: Packages and prepares your application.
  • sam local invoke: Tests individual Lambda functions locally.
  • sam local start-api: Simulates API Gateway for local API testing.
  • sam deploy: Deploys your application to AWS CloudFormation.

Mastering these commands is key to efficient serverless development!

Часто задаваемые вопросы

Урок «Развёртывание приложений SAM» бесплатный?

Да — полный текст урока «Развёртывание приложений SAM» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Serverless Backend with AWS Lambda & API Gateway, подпишись на CoddyKit PRO. Курс Serverless Backend with AWS Lambda & API Gateway содержит 4 уроков всего.

Чему я научусь в уроке «Развёртывание приложений SAM»?

Используйте SAM CLI для сборки, локального тестирования и развёртывания бессерверных приложений в AWS, управляя разными окружениями Ты практикуешь Serverless Backend with AWS Lambda & API Gateway с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Serverless Backend with AWS Lambda & API Gateway?

Предыдущий опыт не требуется. Serverless Backend with AWS Lambda & API Gateway на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Развёртывание приложений SAM»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Serverless Backend with AWS Lambda & API Gateway?

Да. Каждый урок Serverless Backend with AWS Lambda & API Gateway включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Введение в AWS SAM
  2. Определение бессерверных ресурсов
  3. Развёртывание приложений SAM
  4. Локальное тестирование и отладка с помощью SAM CLI
← Назад к Serverless Backend with AWS Lambda & API Gateway