CLI 또는 SDK로 CreateFunction 사용

CLI 또는 SDK로 CreateFunction 사용 (Use CreateFunction with an AWS SDK or CLI)

다음 코드 예제는 CreateFunction을 사용해 Lambda 함수를 만드는 방법을 보여줍니다. Lambda 함수를 만들 때는 함수 코드가 포함된 배포 패키지, 실행 역할, 런타임, 핸들러를 지정해야 합니다.

출처: AWS Lambda 개발자 안내서

본문

CLI

AWS CLI

함수를 만들려면:

다음 create-function 예제는 로컬 .zip 배포 패키지에서 Lambda 함수를 만듭니다.

aws lambda create-function \
    --function-name my-function \
    --runtime nodejs24.x \
    --role arn:aws:iam::123456789012:role/lambda-role \
    --handler index.handler \
    --zip-file fileb://function.zip

코드가 Amazon S3 버킷에 있는 경우 --code 옵션으로 S3Bucket, S3Key, 선택적으로 S3ObjectVersion을 지정합니다.

aws lambda create-function \
    --function-name my-function \
    --runtime nodejs24.x \
    --role arn:aws:iam::123456789012:role/lambda-role \
    --handler index.handler \
    --code S3Bucket=amzn-s3-demo-bucket,S3Key=function.zip

API 세부 정보는 AWS CLI 명령 참조의 CreateFunction을 참조하세요.

Bash (AWS CLI with Bash script)

다음 예제는 Bash 스크립트로 Lambda 함수를 만듭니다. 스크립트는 함수 코드, IAM 역할, 배포 패키지를 생성하고 함수를 만듭니다.

#!/bin/bash

set -euo pipefail

# Create function code
cat > lambda_function.py <<'EOF'
def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': 'Hello from Lambda'
    }
EOF

# Create deployment package
zip function.zip lambda_function.py

# Create IAM role and trust policy
cat > trust-policy.json <<'EOF'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {"Service": "lambda.amazonaws.com"},
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF

ROLE_NAME="lambda-basic-role"
aws iam create-role --role-name "$ROLE_NAME" \
  --assume-role-policy-document file://trust-policy.json

aws iam attach-role-policy --role-name "$ROLE_NAME" \
  --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

ROLE_ARN="arn:aws:iam::$(aws sts get-caller-identity --query Account --output text):role/$ROLE_NAME"

# Create the function
aws lambda create-function \
  --function-name my-function \
  --runtime python3.11 \
  --role "$ROLE_ARN" \
  --handler lambda_function.lambda_handler \
  --zip-file fileb://function.zip \
  --timeout 30 \
  --memory-size 128

PowerShell

Tools for PowerShell V4:

예제 1: Lambda 함수를 만듭니다.

New-LMFunction -FunctionName "MylambdaFunction123" -Runtime "nodejs24.x" -Role "arn:aws:iam::123456789012:role/lambda-role" -Handler "index.handler" -ZipFile "C:\path\to\function.zip"

API 세부 정보는 AWS Tools for PowerShell Cmdlet Reference (V4)의 CreateFunction을 참조하세요.

Tools for PowerShell V5:

예제 1: Lambda 함수를 만듭니다.

New-LMFunction -FunctionName "MylambdaFunction123" -Runtime "nodejs24.x" -Role "arn:aws:iam::123456789012:role/lambda-role" -Handler "index.handler" -ZipFile "C:\path\to\function.zip"

API 세부 정보는 AWS Tools for PowerShell Cmdlet Reference (V5)의 CreateFunction을 참조하세요.

SDK for Java 2.x

다음 예제는 AWS SDK for Java 2.x로 Lambda 함수를 만드는 방법을 보여줍니다. 배포 패키지가 있는 Amazon S3 버킷과 키, 함수 이름, 런타임, 핸들러, 역할을 지정합니다.

import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest;
import software.amazon.awssdk.services.lambda.model.CreateFunctionResponse;
import software.amazon.awssdk.services.lambda.model.FunctionCode;
import software.amazon.awssdk.services.lambda.model.Runtime;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class CreateFunction {
    public static void main(String[] args) {
        Region region = Region.US_WEST_2;
        LambdaClient awsLambda = LambdaClient.builder().region(region).build();
        String functionName = "my-function";
        String filePath = "path/to/function.zip";
        String role = "arn:aws:iam::123456789012:role/lambda-role";
        createFunction(awsLambda, functionName, filePath, role);
        awsLambda.close();
    }

    public static void createFunction(LambdaClient awsLambda, String functionName,
                                      String filePath, String role) {
        try {
            SdkBytes fileToUpload = SdkBytes.fromInputStream(Files.newInputStream(Paths.get(filePath)));
            FunctionCode code = FunctionCode.builder().zipFile(fileToUpload).build();
            CreateFunctionRequest functionRequest = CreateFunctionRequest.builder()
                .functionName(functionName)
                .description("Created with the AWS SDK for Java")
                .code(code)
                .handler("index.handler")
                .runtime(Runtime.NODEJS24_X)
                .role(role)
                .build();
            CreateFunctionResponse response = awsLambda.createFunction(functionRequest);
            System.out.println(response.functionName());
        } catch (IOException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}

SDK for JavaScript (v3)

다음 예제는 AWS SDK for JavaScript v3로 Lambda 함수를 만드는 방법을 보여줍니다.

import { CreateFunctionCommand, LambdaClient } from "@aws-sdk/client-lambda";
import { readFileSync } from "fs";

const client = new LambdaClient({ region: "us-west-2" });

const functionCode = readFileSync("path/to/function.zip");

const params = {
  FunctionName: "my-function",
  Runtime: "nodejs24.x",
  Role: "arn:aws:iam::123456789012:role/lambda-role",
  Handler: "index.handler",
  Code: { ZipFile: functionCode },
};

const command = new CreateFunctionCommand(params);
const response = await client.send(command);
console.log(response.FunctionName);

SDK for Python (Boto3)

다음 예제는 AWS SDK for Python(Boto3)로 Lambda 함수를 만드는 방법을 보여줍니다.

import boto3

lambda_client = boto3.client('lambda')

with open('function.zip', 'rb') as f:
    zipped_code = f.read()

response = lambda_client.create_function(
    FunctionName='my-function',
    Runtime='nodejs24.x',
    Role='arn:aws:iam::123456789012:role/lambda-role',
    Handler='index.handler',
    Code={
        'ZipFile': zipped_code
    },
    Description='Created with the AWS SDK for Python'
)
print(response)

SDK for Go V2

다음 예제는 AWS SDK for Go V2로 Lambda 함수를 만드는 방법을 보여줍니다.

import (
    "context"
    "os"
    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/service/lambda"
)

func createFunction(client *lambda.Client, functionName, filePath, role string) error {
    content, err := os.ReadFile(filePath)
    if err != nil {
        return err
    }
    _, err = client.CreateFunction(context.TODO(), &lambda.CreateFunctionInput{
        FunctionName: aws.String(functionName),
        Runtime:      "nodejs24.x",
        Role:         aws.String(role),
        Handler:      aws.String("index.handler"),
        Code: &lambda.FunctionCode{
            ZipFile: content,
        },
    })
    return err
}

.NET

다음 예제는 AWS SDK for .NET으로 Lambda 함수를 만드는 방법을 보여줍니다.

using Amazon.Lambda;
using Amazon.Lambda.Model;

var client = new AmazonLambdaClient(Amazon.RegionEndpoint.USWest2);
var request = new CreateFunctionRequest
{
    FunctionName = "my-function",
    Runtime = "nodejs24.x",
    Role = "arn:aws:iam::123456789012:role/lambda-role",
    Handler = "index.handler",
    Code = new FunctionCode
    {
        ZipFile = File.ReadAllBytes("path/to/function.zip")
    }
};
var response = await client.CreateFunctionAsync(request);
Console.WriteLine(response.FunctionName);

Ruby

다음 예제는 AWS SDK for Ruby로 Lambda 함수를 만드는 방법을 보여줍니다.

require 'aws-sdk-lambda'

client = Aws::Lambda::Client.new(region: 'us-west-2')
response = client.create_function(
  function_name: 'my-function',
  runtime: 'nodejs24.x',
  role: 'arn:aws:iam::123456789012:role/lambda-role',
  handler: 'index.handler',
  code: {
    zip_file: File.binread('path/to/function.zip')
  }
)

Rust

다음 예제는 AWS SDK for Rust로 Lambda 함수를 만드는 방법을 보여줍니다.

use aws_sdk_lambda::Client;
use aws_sdk_lambda::primitives::Blob;
use std::fs;

async fn create_function(client: &Client, function_name: &str, file_path: &str) -> Result<(), aws_sdk_lambda::Error> {
    let data = fs::read(file_path).unwrap();
    client
        .create_function()
        .function_name(function_name)
        .runtime("nodejs24.x")
        .role("arn:aws:iam::123456789012:role/lambda-role")
        .handler("index.handler")
        .code().zip_file(Blob::new(data))
        .send()
        .await?;
    Ok(())
}

PHP

다음 예제는 AWS SDK for PHP로 Lambda 함수를 만드는 방법을 보여줍니다.

use Aws\Lambda\LambdaClient;

$client = new LambdaClient([
    'region' => 'us-west-2',
    'version' => 'latest'
]);

$result = $client->createFunction([
    'FunctionName' => 'my-function',
    'Runtime' => 'nodejs24.x',
    'Role' => 'arn:aws:iam::123456789012:role/lambda-role',
    'Handler' => 'index.handler',
    'Code' => [
        'ZipFile' => file_get_contents('path/to/function.zip')
    ]
]);

AWS SDK 개발자 안내서와 코드 예제의 전체 목록은 AWS SDK와 함께 Lambda 사용을 참조하세요. 이 주제에는 시작하기와 이전 SDK 버전에 대한 자세한 내용도 포함되어 있습니다.

더 알아보기 (Learn more)

  • Lambda 함수 만들기
  • CreateFunction API
  • AWS SDK와 함께 Lambda 사용