AWS SDK 또는 CLI와 함께 CreateFunction
사용
다음 코드 예제는 CreateFunction
의 사용 방법을 보여 줍니다.
작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.
- .NET
-
- AWS SDK for .NET
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. /// <summary> /// Creates a new Lambda function. /// </summary> /// <param name="functionName">The name of the function.</param> /// <param name="s3Bucket">The Amazon Simple Storage Service (Amazon S3) /// bucket where the zip file containing the code is located.</param> /// <param name="s3Key">The Amazon S3 key of the zip file.</param> /// <param name="role">The Amazon Resource Name (ARN) of a role with the /// appropriate Lambda permissions.</param> /// <param name="handler">The name of the handler function.</param> /// <returns>The Amazon Resource Name (ARN) of the newly created /// Lambda function.</returns> public async Task<string> CreateLambdaFunctionAsync( string functionName, string s3Bucket, string s3Key, string role, string handler) { // Defines the location for the function code. // S3Bucket - The S3 bucket where the file containing // the source code is stored. // S3Key - The name of the file containing the code. var functionCode = new FunctionCode { S3Bucket = s3Bucket, S3Key = s3Key, }; var createFunctionRequest = new CreateFunctionRequest { FunctionName = functionName, Description = "Created by the Lambda .NET API", Code = functionCode, Handler = handler, Runtime = Runtime.Dotnet6, Role = role, }; var reponse = await _lambdaService.CreateFunctionAsync(createFunctionRequest); return reponse.FunctionArn; }
-
API 세부 정보는 AWS SDK for .NET API 참조의 CreateFunction을 참조하십시오.
-
- C++
-
- SDK for C++
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region in which the bucket was created (overrides config file). // clientConfig.region = "us-east-1"; Aws::Lambda::LambdaClient client(clientConfig); Aws::Lambda::Model::CreateFunctionRequest request; request.SetFunctionName(LAMBDA_NAME); request.SetDescription(LAMBDA_DESCRIPTION); // Optional. #if USE_CPP_LAMBDA_FUNCTION request.SetRuntime(Aws::Lambda::Model::Runtime::provided_al2); request.SetTimeout(15); request.SetMemorySize(128); // Assume the AWS Lambda function was built in Docker with same architecture // as this code. #if defined(__x86_64__) request.SetArchitectures({Aws::Lambda::Model::Architecture::x86_64}); #elif defined(__aarch64__) request.SetArchitectures({Aws::Lambda::Model::Architecture::arm64}); #else #error "Unimplemented architecture" #endif // defined(architecture) #else request.SetRuntime(Aws::Lambda::Model::Runtime::python3_8); #endif request.SetRole(roleArn); request.SetHandler(LAMBDA_HANDLER_NAME); request.SetPublish(true); Aws::Lambda::Model::FunctionCode code; std::ifstream ifstream(INCREMENT_LAMBDA_CODE.c_str(), std::ios_base::in | std::ios_base::binary); if (!ifstream.is_open()) { std::cerr << "Error opening file " << INCREMENT_LAMBDA_CODE << "." << std::endl; #if USE_CPP_LAMBDA_FUNCTION std::cerr << "The cpp Lambda function must be built following the instructions in the cpp_lambda/README.md file. " << std::endl; #endif deleteIamRole(clientConfig); return false; } Aws::StringStream buffer; buffer << ifstream.rdbuf(); code.SetZipFile(Aws::Utils::ByteBuffer((unsigned char *) buffer.str().c_str(), buffer.str().length())); request.SetCode(code); Aws::Lambda::Model::CreateFunctionOutcome outcome = client.CreateFunction( request); if (outcome.IsSuccess()) { std::cout << "The lambda function was successfully created. " << seconds << " seconds elapsed." << std::endl; break; } else { std::cerr << "Error with CreateFunction. " << outcome.GetError().GetMessage() << std::endl; deleteIamRole(clientConfig); return false; }
-
API 세부 정보는 AWS SDK for C++ API 참조의 CreateFunction을 참조하십시오.
-
- CLI
-
- AWS CLI
-
Lambda 함수를 생성하는 방법
다음
create-function
예제에서는 이름이my-function
인 Lambda 함수를 생성합니다.aws lambda create-function \ --function-name
my-function
\ --runtimenodejs18.x
\ --zip-filefileb://my-function.zip
\ --handlermy-function.handler
\ --rolearn:aws:iam::123456789012:role/service-role/MyTestFunction-role-tges6bf4
my-function.zip
의 콘텐츠:This file is a deployment package that contains your function code and any dependencies.
출력:
{ "TracingConfig": { "Mode": "PassThrough" }, "CodeSha256": "PFn4S+er27qk+UuZSTKEQfNKG/XNn7QJs90mJgq6oH8=", "FunctionName": "my-function", "CodeSize": 308, "RevisionId": "873282ed-4cd3-4dc8-a069-d0c647e470c6", "MemorySize": 128, "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function", "Version": "$LATEST", "Role": "arn:aws:iam::123456789012:role/service-role/MyTestFunction-role-zgur6bf4", "Timeout": 3, "LastModified": "2023-10-14T22:26:11.234+0000", "Handler": "my-function.handler", "Runtime": "nodejs18.x", "Description": "" }
자세한 설명은 AWS 개발자 안내서에서 AWS Lambda 함수 구성을 참조하세요.
-
API 세부 정보는 AWS CLI 명령 참조에서 CreateFunction
을 참조하세요.
-
- Go
-
- SDK for Go V2
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. // FunctionWrapper encapsulates function actions used in the examples. // It contains an AWS Lambda service client that is used to perform user actions. type FunctionWrapper struct { LambdaClient *lambda.Client } // CreateFunction creates a new Lambda function from code contained in the zipPackage // buffer. The specified handlerName must match the name of the file and function // contained in the uploaded code. The role specified by iamRoleArn is assumed by // Lambda and grants specific permissions. // When the function already exists, types.StateActive is returned. // When the function is created, a lambda.FunctionActiveV2Waiter is used to wait until the // function is active. func (wrapper FunctionWrapper) CreateFunction(ctx context.Context, functionName string, handlerName string, iamRoleArn *string, zipPackage *bytes.Buffer) types.State { var state types.State _, err := wrapper.LambdaClient.CreateFunction(ctx, &lambda.CreateFunctionInput{ Code: &types.FunctionCode{ZipFile: zipPackage.Bytes()}, FunctionName: aws.String(functionName), Role: iamRoleArn, Handler: aws.String(handlerName), Publish: true, Runtime: types.RuntimePython38, }) if err != nil { var resConflict *types.ResourceConflictException if errors.As(err, &resConflict) { log.Printf("Function %v already exists.\n", functionName) state = types.StateActive } else { log.Panicf("Couldn't create function %v. Here's why: %v\n", functionName, err) } } else { waiter := lambda.NewFunctionActiveV2Waiter(wrapper.LambdaClient) funcOutput, err := waiter.WaitForOutput(ctx, &lambda.GetFunctionInput{ FunctionName: aws.String(functionName)}, 1*time.Minute) if err != nil { log.Panicf("Couldn't wait for function %v to be active. Here's why: %v\n", functionName, err) } else { state = funcOutput.Configuration.State } } return state }
-
API 세부 정보는 AWS SDK for Go API 참조의 CreateFunction
을 참조하십시오.
-
- Java
-
- SDK for Java 2.x
-
참고
GitHub에 더 많은 내용이 있습니다. AWS코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest; import software.amazon.awssdk.services.lambda.model.FunctionCode; import software.amazon.awssdk.services.lambda.model.CreateFunctionResponse; import software.amazon.awssdk.services.lambda.model.GetFunctionRequest; import software.amazon.awssdk.services.lambda.model.GetFunctionResponse; import software.amazon.awssdk.services.lambda.model.LambdaException; import software.amazon.awssdk.services.lambda.model.Runtime; import software.amazon.awssdk.services.lambda.waiters.LambdaWaiter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; /** * This code example requires a ZIP or JAR that represents the code of the * Lambda function. * If you do not have a ZIP or JAR, please refer to the following document: * * https://github.com/aws-doc-sdk-examples/tree/master/javav2/usecases/creating_workflows_stepfunctions * * Also, set up your development environment, including your credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateFunction { public static void main(String[] args) { final String usage = """ Usage: <functionName> <filePath> <role> <handler>\s Where: functionName - The name of the Lambda function.\s filePath - The path to the ZIP or JAR where the code is located.\s role - The role ARN that has Lambda permissions.\s handler - The fully qualified method name (for example, example.Handler::handleRequest). \s """; if (args.length != 4) { System.out.println(usage); System.exit(1); } String functionName = args[0]; String filePath = args[1]; String role = args[2]; String handler = args[3]; Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() .region(region) .build(); createLambdaFunction(awsLambda, functionName, filePath, role, handler); awsLambda.close(); } public static void createLambdaFunction(LambdaClient awsLambda, String functionName, String filePath, String role, String handler) { try { LambdaWaiter waiter = awsLambda.waiter(); InputStream is = new FileInputStream(filePath); SdkBytes fileToUpload = SdkBytes.fromInputStream(is); FunctionCode code = FunctionCode.builder() .zipFile(fileToUpload) .build(); CreateFunctionRequest functionRequest = CreateFunctionRequest.builder() .functionName(functionName) .description("Created by the Lambda Java API") .code(code) .handler(handler) .runtime(Runtime.JAVA8) .role(role) .build(); // Create a Lambda function using a waiter. CreateFunctionResponse functionResponse = awsLambda.createFunction(functionRequest); GetFunctionRequest getFunctionRequest = GetFunctionRequest.builder() .functionName(functionName) .build(); WaiterResponse<GetFunctionResponse> waiterResponse = waiter.waitUntilFunctionExists(getFunctionRequest); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("The function ARN is " + functionResponse.functionArn()); } catch (LambdaException | FileNotFoundException e) { System.err.println(e.getMessage()); System.exit(1); } } }
-
API 세부 정보는 AWS SDK for Java 2.x API 참조의 CreateFunction을 참조하십시오.
-
- JavaScript
-
- SDK for JavaScript (v3)
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. const createFunction = async (funcName, roleArn) => { const client = new LambdaClient({}); const code = await readFile(`${dirname}../functions/${funcName}.zip`); const command = new CreateFunctionCommand({ Code: { ZipFile: code }, FunctionName: funcName, Role: roleArn, Architectures: [Architecture.arm64], Handler: "index.handler", // Required when sending a .zip file PackageType: PackageType.Zip, // Required when sending a .zip file Runtime: Runtime.nodejs16x, // Required when sending a .zip file }); return client.send(command); };
-
API 세부 정보는 AWS SDK for JavaScript API 참조의 CreateFunction을 참조하십시오.
-
- Kotlin
-
- SDK for Kotlin
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. suspend fun createNewFunction( myFunctionName: String, s3BucketName: String, myS3Key: String, myHandler: String, myRole: String, ): String? { val functionCode = FunctionCode { s3Bucket = s3BucketName s3Key = myS3Key } val request = CreateFunctionRequest { functionName = myFunctionName code = functionCode description = "Created by the Lambda Kotlin API" handler = myHandler role = myRole runtime = Runtime.Java8 } LambdaClient { region = "us-west-2" }.use { awsLambda -> val functionResponse = awsLambda.createFunction(request) awsLambda.waitUntilFunctionActive { functionName = myFunctionName } return functionResponse.functionArn } }
-
API 세부 정보는 AWS SDK for Kotlin API 참조의 CreateFunction
를 참조하십시오.
-
- PHP
-
- SDK for PHP
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. public function createFunction($functionName, $role, $bucketName, $handler) { //This assumes the Lambda function is in an S3 bucket. return $this->customWaiter(function () use ($functionName, $role, $bucketName, $handler) { return $this->lambdaClient->createFunction([ 'Code' => [ 'S3Bucket' => $bucketName, 'S3Key' => $functionName, ], 'FunctionName' => $functionName, 'Role' => $role['Arn'], 'Runtime' => 'python3.9', 'Handler' => "$handler.lambda_handler", ]); }); }
-
API 세부 정보는 AWS SDK for PHP API 참조의 CreateFunction을 참조하십시오.
-
- PowerShell
-
- PowerShell용 도구
-
예제 1: 이 예제에서는 AWS Lambda에서 MyFunction이라는 이름의 새 C#(dotnetcore1.0 런타임) 함수를 생성하여 로컬 파일 시스템의 zip 파일(상대 경로 또는 절대 경로 사용 가능)에서 함수에 대한 컴파일된 바이너리를 제공합니다. C# Lambda 함수는 AssemblyName::Namespace.ClassName::MethodName 지정을 사용하여 함수에 대한 핸들러를 지정합니다. 핸들러 사양의 어셈블리 이름 (.dll 접미사 제외), 네임스페이스, 클래스 이름, 메서드 이름 부분을 적절하게 바꿔야 합니다. 새 함수에는 제공된 값으로부터 환경 변수 'envvar1' 및 'envvar2'가 설정됩니다.
Publish-LMFunction -Description "My C# Lambda Function" ` -FunctionName MyFunction ` -ZipFilename .\MyFunctionBinaries.zip ` -Handler "AssemblyName::Namespace.ClassName::MethodName" ` -Role "arn:aws:iam::123456789012:role/LambdaFullExecRole" ` -Runtime dotnetcore1.0 ` -Environment_Variable @{ "envvar1"="value";"envvar2"="value" }
출력:
CodeSha256 : /NgBMd...gq71I= CodeSize : 214784 DeadLetterConfig : Description : My C# Lambda Function Environment : Amazon.Lambda.Model.EnvironmentResponse FunctionArn : arn:aws:lambda:us-west-2:123456789012:function:ToUpper FunctionName : MyFunction Handler : AssemblyName::Namespace.ClassName::MethodName KMSKeyArn : LastModified : 2016-12-29T23:50:14.207+0000 MemorySize : 128 Role : arn:aws:iam::123456789012:role/LambdaFullExecRole Runtime : dotnetcore1.0 Timeout : 3 Version : $LATEST VpcConfig :
예제 2: 이 예제는 함수 바이너리가 먼저 Amazon S3 버킷(의도한 Lambda 함수와 동일한 리전에 있어야 함)에 업로드되고 함수 생성 시 결과 S3 객체가 참조된다는 점을 제외하면 이전 예제와 유사합니다.
Write-S3Object -BucketName amzn-s3-demo-bucket -Key MyFunctionBinaries.zip -File .\MyFunctionBinaries.zip Publish-LMFunction -Description "My C# Lambda Function" ` -FunctionName MyFunction ` -BucketName amzn-s3-demo-bucket ` -Key MyFunctionBinaries.zip ` -Handler "AssemblyName::Namespace.ClassName::MethodName" ` -Role "arn:aws:iam::123456789012:role/LambdaFullExecRole" ` -Runtime dotnetcore1.0 ` -Environment_Variable @{ "envvar1"="value";"envvar2"="value" }
-
API 세부 정보는 AWS Tools for PowerShell Cmdlet 참조의 CreateFunction을 참조하세요.
-
- Python
-
- SDK for Python (Boto3)
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. class LambdaWrapper: def __init__(self, lambda_client, iam_resource): self.lambda_client = lambda_client self.iam_resource = iam_resource def create_function( self, function_name, handler_name, iam_role, deployment_package ): """ Deploys a Lambda function. :param function_name: The name of the Lambda function. :param handler_name: The fully qualified name of the handler function. This must include the file name and the function name. :param iam_role: The IAM role to use for the function. :param deployment_package: The deployment package that contains the function code in .zip format. :return: The Amazon Resource Name (ARN) of the newly created function. """ try: response = self.lambda_client.create_function( FunctionName=function_name, Description="AWS Lambda doc example", Runtime="python3.8", Role=iam_role.arn, Handler=handler_name, Code={"ZipFile": deployment_package}, Publish=True, ) function_arn = response["FunctionArn"] waiter = self.lambda_client.get_waiter("function_active_v2") waiter.wait(FunctionName=function_name) logger.info( "Created function '%s' with ARN: '%s'.", function_name, response["FunctionArn"], ) except ClientError: logger.error("Couldn't create function %s.", function_name) raise else: return function_arn
-
API 세부 정보는 AWSSDK for Python (Boto3) API 참조의 CreateFunction를 참조하십시오.
-
- Ruby
-
- SDK for Ruby
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. class LambdaWrapper attr_accessor :lambda_client, :cloudwatch_client, :iam_client def initialize @lambda_client = Aws::Lambda::Client.new @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1') @iam_client = Aws::IAM::Client.new(region: 'us-east-1') @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Deploys a Lambda function. # # @param function_name: The name of the Lambda function. # @param handler_name: The fully qualified name of the handler function. # @param role_arn: The IAM role to use for the function. # @param deployment_package: The deployment package that contains the function code in .zip format. # @return: The Amazon Resource Name (ARN) of the newly created function. def create_function(function_name, handler_name, role_arn, deployment_package) response = @lambda_client.create_function({ role: role_arn.to_s, function_name: function_name, handler: handler_name, runtime: 'ruby2.7', code: { zip_file: deployment_package }, environment: { variables: { 'LOG_LEVEL' => 'info' } } }) @lambda_client.wait_until(:function_active_v2, { function_name: function_name }) do |w| w.max_attempts = 5 w.delay = 5 end response rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error creating #{function_name}:\n #{e.message}") rescue Aws::Waiters::Errors::WaiterFailed => e @logger.error("Failed waiting for #{function_name} to activate:\n #{e.message}") end
-
API 세부 정보는 AWS SDK for Ruby API 참조의 CreateFunction을 참조하십시오.
-
- Rust
-
- SDK for Rust
-
참고
GitHub에 더 많은 내용이 있습니다. AWS코드 예시 리포지토리
에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요. /** * Create a function, uploading from a zip file. */ pub async fn create_function(&self, zip_file: PathBuf) -> Result<String, anyhow::Error> { let code = self.prepare_function(zip_file, None).await?; let key = code.s3_key().unwrap().to_string(); let role = self.create_role().await.map_err(|e| anyhow!(e))?; info!("Created iam role, waiting 15s for it to become active"); tokio::time::sleep(Duration::from_secs(15)).await; info!("Creating lambda function {}", self.lambda_name); let _ = self .lambda_client .create_function() .function_name(self.lambda_name.clone()) .code(code) .role(role.arn()) .runtime(aws_sdk_lambda::types::Runtime::Providedal2) .handler("_unused") .send() .await .map_err(anyhow::Error::from)?; self.wait_for_function_ready().await?; self.lambda_client .publish_version() .function_name(self.lambda_name.clone()) .send() .await?; Ok(key) } /** * Upload function code from a path to a zip file. * The zip file must have an AL2 Linux-compatible binary called `bootstrap`. * The easiest way to create such a zip is to use `cargo lambda build --output-format Zip`. */ async fn prepare_function( &self, zip_file: PathBuf, key: Option<String>, ) -> Result<FunctionCode, anyhow::Error> { let body = ByteStream::from_path(zip_file).await?; let key = key.unwrap_or_else(|| format!("{}_code", self.lambda_name)); info!("Uploading function code to s3://{}/{}", self.bucket, key); let _ = self .s3_client .put_object() .bucket(self.bucket.clone()) .key(key.clone()) .body(body) .send() .await?; Ok(FunctionCode::builder() .s3_bucket(self.bucket.clone()) .s3_key(key) .build()) }
-
API 세부 정보는 AWS SDK for Rust API 참조의 CreateFunction
을 참조하십시오.
-
- SAP ABAP
-
- SDK for SAP ABAP API
-
참고
GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리
에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요. TRY. lo_lmd->createfunction( iv_functionname = iv_function_name iv_runtime = `python3.9` iv_role = iv_role_arn iv_handler = iv_handler io_code = io_zip_file iv_description = 'AWS Lambda code example' ). MESSAGE 'Lambda function created.' TYPE 'I'. CATCH /aws1/cx_lmdcodesigningcfgno00. MESSAGE 'Code signing configuration does not exist.' TYPE 'E'. CATCH /aws1/cx_lmdcodestorageexcdex. MESSAGE 'Maximum total code size per account exceeded.' TYPE 'E'. CATCH /aws1/cx_lmdcodeverification00. MESSAGE 'Code signature failed one or more validation checks for signature mismatch or expiration.' TYPE 'E'. CATCH /aws1/cx_lmdinvalidcodesigex. MESSAGE 'Code signature failed the integrity check.' TYPE 'E'. CATCH /aws1/cx_lmdinvparamvalueex. MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'. CATCH /aws1/cx_lmdresourceconflictex. MESSAGE 'Resource already exists or another operation is in progress.' TYPE 'E'. CATCH /aws1/cx_lmdresourcenotfoundex. MESSAGE 'The requested resource does not exist.' TYPE 'E'. CATCH /aws1/cx_lmdserviceexception. MESSAGE 'An internal problem was encountered by the AWS Lambda service.' TYPE 'E'. CATCH /aws1/cx_lmdtoomanyrequestsex. MESSAGE 'The maximum request throughput was reached.' TYPE 'E'. ENDTRY.
-
API 세부 정보는 SAP ABAP용 AWS SDK API 참조의 CreateFunction을 참조하세요.
-
AWS SDK 개발자 가이드 및 코드 예시의 전체 목록은 AWS SDK에서 Lambda 사용 단원을 참조하세요. 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.