

# 使用 Amazon SDK 对 Lambda 执行的操作
操作

以下代码示例演示了如何使用 Amazon SDK 来执行各个 Lambda 操作。每个示例都包含一个指向 GitHub 的链接，您可以在其中找到有关设置和运行代码的说明。

这些代码节选调用了 Lambda API，是必须在上下文中运行的大型程序的代码节选。您可以在[适用于使用 Amazon SDK 的 Lambda 的场景](service_code_examples_scenarios.md)中结合上下文查看操作。

 以下示例仅包括最常用的操作。有关完整列表，请参阅 [Amazon Lambda API 参考](https://docs.amazonaws.cn/lambda/latest/dg/API_Reference.html)。

**Topics**
+ [`CreateAlias`](example_lambda_CreateAlias_section.md)
+ [`CreateFunction`](example_lambda_CreateFunction_section.md)
+ [`DeleteAlias`](example_lambda_DeleteAlias_section.md)
+ [`DeleteFunction`](example_lambda_DeleteFunction_section.md)
+ [`DeleteFunctionConcurrency`](example_lambda_DeleteFunctionConcurrency_section.md)
+ [`DeleteProvisionedConcurrencyConfig`](example_lambda_DeleteProvisionedConcurrencyConfig_section.md)
+ [`GetAccountSettings`](example_lambda_GetAccountSettings_section.md)
+ [`GetAlias`](example_lambda_GetAlias_section.md)
+ [`GetFunction`](example_lambda_GetFunction_section.md)
+ [`GetFunctionConcurrency`](example_lambda_GetFunctionConcurrency_section.md)
+ [`GetFunctionConfiguration`](example_lambda_GetFunctionConfiguration_section.md)
+ [`GetPolicy`](example_lambda_GetPolicy_section.md)
+ [`GetProvisionedConcurrencyConfig`](example_lambda_GetProvisionedConcurrencyConfig_section.md)
+ [`Invoke`](example_lambda_Invoke_section.md)
+ [`ListFunctions`](example_lambda_ListFunctions_section.md)
+ [`ListProvisionedConcurrencyConfigs`](example_lambda_ListProvisionedConcurrencyConfigs_section.md)
+ [`ListTags`](example_lambda_ListTags_section.md)
+ [`ListVersionsByFunction`](example_lambda_ListVersionsByFunction_section.md)
+ [`PublishVersion`](example_lambda_PublishVersion_section.md)
+ [`PutFunctionConcurrency`](example_lambda_PutFunctionConcurrency_section.md)
+ [`PutProvisionedConcurrencyConfig`](example_lambda_PutProvisionedConcurrencyConfig_section.md)
+ [`RemovePermission`](example_lambda_RemovePermission_section.md)
+ [`TagResource`](example_lambda_TagResource_section.md)
+ [`UntagResource`](example_lambda_UntagResource_section.md)
+ [`UpdateAlias`](example_lambda_UpdateAlias_section.md)
+ [`UpdateFunctionCode`](example_lambda_UpdateFunctionCode_section.md)
+ [`UpdateFunctionConfiguration`](example_lambda_UpdateFunctionConfiguration_section.md)

# 将 `CreateAlias` 与 CLI 配合使用
`CreateAlias`

以下代码示例演示如何使用 `CreateAlias`。

------
#### [ CLI ]

**Amazon CLI**  
**为 Lambda 函数创建别名**  
以下 `create-alias` 示例会创建名为 `LIVE` 的别名，该别名指向 `my-function` Lambda 函数的版本 1。  

```
aws lambda create-alias \
    --function-name my-function \
    --description "alias for live version of function" \
    --function-version 1 \
    --name LIVE
```
输出：  

```
{
    "FunctionVersion": "1",
    "Name": "LIVE",
    "AliasArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:LIVE",
    "RevisionId": "873282ed-4cd3-4dc8-a069-d0c647e470c6",
    "Description": "alias for live version of function"
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[配置 Amazon Lambda 函数别名](https://docs.amazonaws.cn/lambda/latest/dg/aliases-intro.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [CreateAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/create-alias.html)。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：本示例为指定版本和路由配置创建了新的 Lambda 别名，可指定相应版本收到的调用请求的百分比。**  

```
New-LMAlias -FunctionName "MylambdaFunction123" -RoutingConfig_AdditionalVersionWeight @{Name="1";Value="0.6} -Description "Alias for version 4" -FunctionVersion 4 -Name "PowershellAlias"
```
+  有关 API 的详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [CreateAlias](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例为指定版本和路由配置创建了新的 Lambda 别名，可指定相应版本收到的调用请求的百分比。**  

```
New-LMAlias -FunctionName "MylambdaFunction123" -RoutingConfig_AdditionalVersionWeight @{Name="1";Value="0.6} -Description "Alias for version 4" -FunctionVersion 4 -Name "PowershellAlias"
```
+  有关 API 的详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [CreateAlias](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `CreateFunction` 与 Amazon SDK 或 CLI 配合使用
`CreateFunction`

以下代码示例演示如何使用 `CreateFunction`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_lambda_Scenario_GettingStartedFunctions_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 Amazon SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <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 详细信息，请参阅《适用于 .NET 的 Amazon SDK API Reference》**中的 [CreateFunction](https://docs.amazonaws.cn/goto/DotNetSDKV3/lambda-2015-03-31/CreateFunction)。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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_9);
#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 详细信息，请参阅《适用于 C\$1\$1 的 Amazon SDK API Reference》**中的 [CreateFunction](https://docs.amazonaws.cn/goto/SdkForCpp/lambda-2015-03-31/CreateFunction)。

------
#### [ CLI ]

**Amazon CLI**  
**创建 Lambda 函数**  
以下 `create-function` 示例创建一个名为 `my-function` 的 Lambda 函数。  

```
aws lambda create-function \
    --function-name my-function \
    --runtime nodejs22.x \
    --zip-file fileb://my-function.zip \
    --handler my-function.handler \
    --role arn: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": "2025-10-14T22:26:11.234+0000",
    "Handler": "my-function.handler",
    "Runtime": "nodejs22.x",
    "Description": ""
}
```
有关更多信息，请参阅*《Amazon Lambda 开发人员指南》*中的 [配置 Lambda 函数内存](https://docs.amazonaws.cn/lambda/latest/dg/configuration-memory.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI Command Reference》**中的 [CreateFunction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/create-function.html)。

------
#### [ Go ]

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// 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.RuntimePython39,
	})
	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 详细信息，请参阅《适用于 Go 的 Amazon SDK API Reference》**中的 [CreateFunction](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.CreateFunction)。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Creates a new Lambda function in AWS using the AWS Lambda Java API.
     *
     * @param awsLambda    the AWS Lambda client used to interact with the AWS Lambda service
     * @param functionName the name of the Lambda function to create
     * @param key          the S3 key of the function code
     * @param bucketName   the name of the S3 bucket containing the function code
     * @param role         the IAM role to assign to the Lambda function
     * @param handler      the fully qualified class name of the function handler
     * @return the Amazon Resource Name (ARN) of the created Lambda function
     */
    public static String createLambdaFunction(LambdaClient awsLambda,
                                              String functionName,
                                              String key,
                                              String bucketName,
                                              String role,
                                              String handler) {

        try {
            LambdaWaiter waiter = awsLambda.waiter();
            FunctionCode code = FunctionCode.builder()
                .s3Key(key)
                .s3Bucket(bucketName)
                .build();

            CreateFunctionRequest functionRequest = CreateFunctionRequest.builder()
                .functionName(functionName)
                .description("Created by the Lambda Java API")
                .code(code)
                .handler(handler)
                .runtime(Runtime.JAVA17)
                .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);
            return functionResponse.functionArn();

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Java 2.x API Reference》**中的 [CreateFunction](https://docs.amazonaws.cn/goto/SdkForJavaV2/lambda-2015-03-31/CreateFunction)。

------
#### [ JavaScript ]

**适用于 JavaScript 的 SDK（v3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [CreateFunction](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/lambda/command/CreateFunctionCommand)。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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.Java17
        }

    LambdaClient { region = "us-east-1" }.use { awsLambda ->
        val functionResponse = awsLambda.createFunction(request)
        awsLambda.waitUntilFunctionActive {
            functionName = myFunctionName
        }
        return functionResponse.functionArn
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Kotlin API Reference》**中的 [CreateFunction](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    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 详细信息，请参阅《适用于 PHP 的 Amazon SDK API Reference》**中的 [CreateFunction](https://docs.amazonaws.cn/goto/SdkForPHPV3/lambda-2015-03-31/CreateFunction)。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：本示例在 Amazon Lambda 中创建了一个名为 MyFunction 的新 C\$1（dotnetcore1.0 运行时系统）函数，从本地文件系统上的 zip 文件为该函数提供编译后的二进制文件（可以使用相对路径或绝对路径）。C\$1 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 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [CreateFunction](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例在 Amazon Lambda 中创建了一个名为 MyFunction 的新 C\$1（dotnetcore1.0 运行时系统）函数，从本地文件系统上的 zip 文件为该函数提供编译后的二进制文件（可以使用相对路径或绝对路径）。C\$1 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 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V5)*》中的 [CreateFunction](https://docs.amazonaws.cn/powershell/v5/reference)。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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.9",
                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 详细信息，请参阅《Amazon SDK for Python (Boto3) API Reference》**中的 [CreateFunction](https://docs.amazonaws.cn/goto/boto3/lambda-2015-03-31/CreateFunction)。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 详细信息，请参阅《适用于 Ruby 的 Amazon SDK API Reference》**中的 [CreateFunction](https://docs.amazonaws.cn/goto/SdkForRubyV3/lambda-2015-03-31/CreateFunction)。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * 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 详细信息，请参阅《Amazon SDK for Rust API Reference》**中的 [CreateFunction](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.create_function)。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    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 的 Amazon SDK 的 API 参考*中的 [CreateFunction](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

------
#### [ Swift ]

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import AWSClientRuntime
import AWSLambda
import Foundation

        do {
            // Read the Zip archive containing the AWS Lambda function.

            let zipUrl = URL(fileURLWithPath: path)
            let zipData = try Data(contentsOf: zipUrl)

            // Create the AWS Lambda function that runs the specified code,
            // using the name given on the command line. The Lambda function
            // will run using the Amazon Linux 2 runtime.

            _ = try await lambdaClient.createFunction(
                input: CreateFunctionInput(
                    code: LambdaClientTypes.FunctionCode(zipFile: zipData),
                    functionName: functionName,
                    handler: "handle",
                    role: roleArn,
                    runtime: .providedal2
                )
            )
        } catch {
            print("*** Error creating Lambda function:")
            dump(error)
            return false
        }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Swift API reference》**中的 [CreateFunction](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/createfunction(input:))。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DeleteAlias` 与 CLI 配合使用
`DeleteAlias`

以下代码示例演示如何使用 `DeleteAlias`。

------
#### [ CLI ]

**Amazon CLI**  
**删除 Lambda 函数别名**  
以下 `delete-alias` 示例从 `my-function` Lambda 函数中删除了名为 `LIVE` 的别名。  

```
aws lambda delete-alias \
    --function-name my-function \
    --name LIVE
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[配置 Amazon Lambda 函数别名](https://docs.amazonaws.cn/lambda/latest/dg/aliases-intro.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [DeleteAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/delete-alias.html)。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：本示例删除了命令中提到的 Lambda 函数别名。**  

```
Remove-LMAlias -FunctionName "MylambdaFunction123" -Name "NewAlias"
```
+  有关 API 的详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [DeleteAlias](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例删除了命令中提到的 Lambda 函数别名。**  

```
Remove-LMAlias -FunctionName "MylambdaFunction123" -Name "NewAlias"
```
+  有关 API 的详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [DeleteAlias](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DeleteFunction` 与 Amazon SDK 或 CLI 配合使用
`DeleteFunction`

以下代码示例演示如何使用 `DeleteFunction`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_lambda_Scenario_GettingStartedFunctions_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 Amazon SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Delete an AWS Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the Lambda function to
    /// delete.</param>
    /// <returns>A Boolean value that indicates the success of the action.</returns>
    public async Task<bool> DeleteFunctionAsync(string functionName)
    {
        var request = new DeleteFunctionRequest
        {
            FunctionName = functionName,
        };

        var response = await _lambdaService.DeleteFunctionAsync(request);

        // A return value of NoContent means that the request was processed.
        // In this case, the function was deleted, and the return value
        // is intentionally blank.
        return response.HttpStatusCode == System.Net.HttpStatusCode.NoContent;
    }
```
+  有关 API 详细信息，请参阅《适用于 .NET 的 Amazon SDK API Reference》**中的 [DeleteFunction](https://docs.amazonaws.cn/goto/DotNetSDKV3/lambda-2015-03-31/DeleteFunction)。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::DeleteFunctionRequest request;
    request.SetFunctionName(LAMBDA_NAME);

    Aws::Lambda::Model::DeleteFunctionOutcome outcome = client.DeleteFunction(
            request);

    if (outcome.IsSuccess()) {
        std::cout << "The lambda function was successfully deleted." << std::endl;
    }
    else {
        std::cerr << "Error with Lambda::DeleteFunction. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }
```
+  有关 API 详细信息，请参阅《适用于 C\$1\$1 的 Amazon SDK API Reference》**中的 [DeleteFunction](https://docs.amazonaws.cn/goto/SdkForCpp/lambda-2015-03-31/DeleteFunction)。

------
#### [ CLI ]

**Amazon CLI**  
**示例 1：按函数名称删除 Lambda 函数**  
以下 `delete-function` 示例删除通过指定函数名称命名为 `my-function` 的 Lambda 函数。  

```
aws lambda delete-function \
    --function-name my-function
```
此命令不生成任何输出。  
**示例 2：按函数 ARN 删除 Lambda 函数**  
以下 `delete-function` 示例删除通过指定函数 ARN 命名为 `my-function` 的 Lambda 函数。  

```
aws lambda delete-function \
    --function-name arn:aws:lambda:us-west-2:123456789012:function:my-function
```
此命令不生成任何输出。  
**示例 3：按部分函数 ARN 删除 Lambda 函数**  
以下 `delete-function` 示例删除通过指定函数的部分 ARN 命名为 `my-function` 的 Lambda 函数。  

```
aws lambda delete-function \
    --function-name 123456789012:function:my-function
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon Lambda 开发人员指南》中的 [Amazon Lambda 函数配置](https://docs.amazonaws.cn/lambda/latest/dg/resource-model.html)。**  
+  有关 API 详细信息，请参阅《Amazon CLI Command Reference》**中的 [DeleteFunction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/delete-function.html)。

------
#### [ Go ]

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// 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
}



// DeleteFunction deletes the Lambda function specified by functionName.
func (wrapper FunctionWrapper) DeleteFunction(ctx context.Context, functionName string) {
	_, err := wrapper.LambdaClient.DeleteFunction(ctx, &lambda.DeleteFunctionInput{
		FunctionName: aws.String(functionName),
	})
	if err != nil {
		log.Panicf("Couldn't delete function %v. Here's why: %v\n", functionName, err)
	}
}
```
+  有关 API 详细信息，请参阅《适用于 Go 的 Amazon SDK API Reference》**中的 [DeleteFunction](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.DeleteFunction)。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Deletes an AWS Lambda function.
     *
     * @param awsLambda     an instance of the {@link LambdaClient} class, which is used to interact with the AWS Lambda service
     * @param functionName  the name of the Lambda function to be deleted
     *
     * @throws LambdaException if an error occurs while deleting the Lambda function
     */
    public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName) {
        try {
            DeleteFunctionRequest request = DeleteFunctionRequest.builder()
                .functionName(functionName)
                .build();

            awsLambda.deleteFunction(request);
            System.out.println("The " + functionName + " function was deleted");

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Java 2.x API Reference》**中的 [DeleteFunction](https://docs.amazonaws.cn/goto/SdkForJavaV2/lambda-2015-03-31/DeleteFunction)。

------
#### [ JavaScript ]

**适用于 JavaScript 的 SDK（v3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
/**
 * @param {string} funcName
 */
const deleteFunction = (funcName) => {
  const client = new LambdaClient({});
  const command = new DeleteFunctionCommand({ FunctionName: funcName });
  return client.send(command);
};
```
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [DeleteFunction](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/lambda/command/DeleteFunctionCommand)。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun delLambdaFunction(myFunctionName: String) {
    val request =
        DeleteFunctionRequest {
            functionName = myFunctionName
        }

    LambdaClient { region = "us-east-1" }.use { awsLambda ->
        awsLambda.deleteFunction(request)
        println("$myFunctionName was deleted")
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Kotlin API Reference》**中的 [DeleteFunction](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function deleteFunction($functionName)
    {
        return $this->lambdaClient->deleteFunction([
            'FunctionName' => $functionName,
        ]);
    }
```
+  有关 API 详细信息，请参阅《适用于 PHP 的 Amazon SDK API Reference》**中的 [DeleteFunction](https://docs.amazonaws.cn/goto/SdkForPHPV3/lambda-2015-03-31/DeleteFunction)。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：本示例删除了特定版本的 Lambda 函数**  

```
Remove-LMFunction -FunctionName "MylambdaFunction123" -Qualifier '3'
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [DeleteFunction](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例删除了特定版本的 Lambda 函数**  

```
Remove-LMFunction -FunctionName "MylambdaFunction123" -Qualifier '3'
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V5)*》中的 [DeleteFunction](https://docs.amazonaws.cn/powershell/v5/reference)。

------
#### [ Python ]

**适用于 Python 的 SDK (Boto3)**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    def delete_function(self, function_name):
        """
        Deletes a Lambda function.

        :param function_name: The name of the function to delete.
        """
        try:
            self.lambda_client.delete_function(FunctionName=function_name)
        except ClientError:
            logger.exception("Couldn't delete function %s.", function_name)
            raise
```
+  有关 API 详细信息，请参阅《Amazon SDK for Python (Boto3) API Reference》**中的 [DeleteFunction](https://docs.amazonaws.cn/goto/boto3/lambda-2015-03-31/DeleteFunction)。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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

  # Deletes a Lambda function.
  # @param function_name: The name of the function to delete.
  def delete_function(function_name)
    print "Deleting function: #{function_name}..."
    @lambda_client.delete_function(
      function_name: function_name
    )
    print 'Done!'.green
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error deleting #{function_name}:\n #{e.message}")
  end
```
+  有关 API 详细信息，请参阅《适用于 Ruby 的 Amazon SDK API Reference》**中的 [DeleteFunction](https://docs.amazonaws.cn/goto/SdkForRubyV3/lambda-2015-03-31/DeleteFunction)。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /** Delete a function and its role, and if possible or necessary, its associated code object and bucket. */
    pub async fn delete_function(
        &self,
        location: Option<String>,
    ) -> (
        Result<DeleteFunctionOutput, anyhow::Error>,
        Result<DeleteRoleOutput, anyhow::Error>,
        Option<Result<DeleteObjectOutput, anyhow::Error>>,
    ) {
        info!("Deleting lambda function {}", self.lambda_name);
        let delete_function = self
            .lambda_client
            .delete_function()
            .function_name(self.lambda_name.clone())
            .send()
            .await
            .map_err(anyhow::Error::from);

        info!("Deleting iam role {}", self.role_name);
        let delete_role = self
            .iam_client
            .delete_role()
            .role_name(self.role_name.clone())
            .send()
            .await
            .map_err(anyhow::Error::from);

        let delete_object: Option<Result<DeleteObjectOutput, anyhow::Error>> =
            if let Some(location) = location {
                info!("Deleting object {location}");
                Some(
                    self.s3_client
                        .delete_object()
                        .bucket(self.bucket.clone())
                        .key(location)
                        .send()
                        .await
                        .map_err(anyhow::Error::from),
                )
            } else {
                info!(?location, "Skipping delete object");
                None
            };

        (delete_function, delete_role, delete_object)
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Rust API Reference》**中的 [DeleteFunction](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.delete_function)。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        lo_lmd->deletefunction( iv_functionname = iv_function_name ).
        MESSAGE 'Lambda function deleted.' TYPE 'I'.
      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 的 Amazon SDK 的 API 参考*中的 [DeleteFunction](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

------
#### [ Swift ]

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import AWSClientRuntime
import AWSLambda
import Foundation

        do {
            _ = try await lambdaClient.deleteFunction(
                input: DeleteFunctionInput(
                    functionName: "lambda-basics-function"
                )
            )
        } catch {
            print("Error: Unable to delete the function.")
        }
```
+  有关 API 详细信息，请参阅*《Amazon SDK for Swift API 参考》*中的 [DeleteFunction](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/deletefunction(input:))。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DeleteFunctionConcurrency` 与 CLI 配合使用
`DeleteFunctionConcurrency`

以下代码示例演示如何使用 `DeleteFunctionConcurrency`。

------
#### [ CLI ]

**Amazon CLI**  
**从函数中删除预留的并发执行限制**  
以下 `delete-function-concurrency` 示例从 `my-function` 函数中删除了预留的并发执行限制。  

```
aws lambda delete-function-concurrency \
    --function-name  my-function
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[为 Lambda 函数预留并发](https://docs.amazonaws.cn/lambda/latest/dg/per-function-concurrency.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [DeleteFunctionConcurrency](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/delete-function-concurrency.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例删除了 Lambda 函数的函数并发。**  

```
Remove-LMFunctionConcurrency -FunctionName "MylambdaFunction123"
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [DeleteFunctionConcurrency](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例删除了 Lambda 函数的函数并发。**  

```
Remove-LMFunctionConcurrency -FunctionName "MylambdaFunction123"
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [DeleteFunctionConcurrency](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DeleteProvisionedConcurrencyConfig` 与 CLI 配合使用
`DeleteProvisionedConcurrencyConfig`

以下代码示例演示如何使用 `DeleteProvisionedConcurrencyConfig`。

------
#### [ CLI ]

**Amazon CLI**  
**删除预置并发配置**  
以下 `delete-provisioned-concurrency-config` 示例删除了指定函数 `GREEN` 别名的预置并发配置。  

```
aws lambda delete-provisioned-concurrency-config \
    --function-name my-function \
    --qualifier GREEN
```
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [DeleteProvisionedConcurrencyConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/delete-provisioned-concurrency-config.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例删除了特定别名的预置并发配置。**  

```
Remove-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -Qualifier "NewAlias1"
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [DeleteProvisionedConcurrencyConfig](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例删除了特定别名的预置并发配置。**  

```
Remove-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -Qualifier "NewAlias1"
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [DeleteProvisionedConcurrencyConfig](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `GetAccountSettings` 与 CLI 配合使用
`GetAccountSettings`

以下代码示例演示如何使用 `GetAccountSettings`。

------
#### [ CLI ]

**Amazon CLI**  
**在 Amazon 区域中检索关于账户的详细信息**  
以下 `get-account-settings` 示例展示了账户的 Lambda 限制和使用信息。  

```
aws lambda get-account-settings
```
输出：  

```
{
    "AccountLimit": {
       "CodeSizeUnzipped": 262144000,
       "UnreservedConcurrentExecutions": 1000,
       "ConcurrentExecutions": 1000,
       "CodeSizeZipped": 52428800,
       "TotalCodeSize": 80530636800
    },
    "AccountUsage": {
       "FunctionCount": 4,
       "TotalCodeSize": 9426
    }
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的 [Amazon Lambda 限制](https://docs.amazonaws.cn/lambda/latest/dg/limits.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [GetAccountSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-account-settings.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例是为了比较账户限制与账户使用情况**  

```
Get-LMAccountSetting | Select-Object @{Name="TotalCodeSizeLimit";Expression={$_.AccountLimit.TotalCodeSize}}, @{Name="TotalCodeSizeUsed";Expression={$_.AccountUsage.TotalCodeSize}}
```
**输出**：  

```
TotalCodeSizeLimit TotalCodeSizeUsed
------------------ -----------------
       80530636800          15078795
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [GetAccountSettings](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例是为了比较账户限制与账户使用情况**  

```
Get-LMAccountSetting | Select-Object @{Name="TotalCodeSizeLimit";Expression={$_.AccountLimit.TotalCodeSize}}, @{Name="TotalCodeSizeUsed";Expression={$_.AccountUsage.TotalCodeSize}}
```
**输出**：  

```
TotalCodeSizeLimit TotalCodeSizeUsed
------------------ -----------------
       80530636800          15078795
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [GetAccountSettings](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `GetAlias` 与 CLI 配合使用
`GetAlias`

以下代码示例演示如何使用 `GetAlias`。

------
#### [ CLI ]

**Amazon CLI**  
**检索关于函数别名的详细信息**  
以下 `get-alias` 示例展示了 `my-function` Lambda 函数中名为 `LIVE` 的别名的详细信息。  

```
aws lambda get-alias \
    --function-name my-function \
    --name LIVE
```
输出：  

```
{
    "FunctionVersion": "3",
    "Name": "LIVE",
    "AliasArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:LIVE",
    "RevisionId": "594f41fb-b85f-4c20-95c7-6ca5f2a92c93",
    "Description": "alias for live version of function"
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[配置 Amazon Lambda 函数别名](https://docs.amazonaws.cn/lambda/latest/dg/aliases-intro.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [GetAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-alias.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例检索了特定 Lambda 函数别名的路由配置权重。**  

```
Get-LMAlias -FunctionName "MylambdaFunction123" -Name "newlabel1" -Select RoutingConfig
```
**输出**：  

```
AdditionalVersionWeights
------------------------
{[1, 0.6]}
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [GetAlias](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例检索了特定 Lambda 函数别名的路由配置权重。**  

```
Get-LMAlias -FunctionName "MylambdaFunction123" -Name "newlabel1" -Select RoutingConfig
```
**输出**：  

```
AdditionalVersionWeights
------------------------
{[1, 0.6]}
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [GetAlias](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `GetFunction` 与 Amazon SDK 或 CLI 配合使用
`GetFunction`

以下代码示例演示如何使用 `GetFunction`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_lambda_Scenario_GettingStartedFunctions_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 Amazon SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Gets information about a Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the Lambda function for
    /// which to retrieve information.</param>
    /// <returns>Async Task.</returns>
    public async Task<FunctionConfiguration> GetFunctionAsync(string functionName)
    {
        var functionRequest = new GetFunctionRequest
        {
            FunctionName = functionName,
        };

        var response = await _lambdaService.GetFunctionAsync(functionRequest);
        return response.Configuration;
    }
```
+  有关 API 详细信息，请参阅《适用于 .NET 的 Amazon SDK API Reference》**中的 [GetFunction](https://docs.amazonaws.cn/goto/DotNetSDKV3/lambda-2015-03-31/GetFunction)。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::GetFunctionRequest request;
        request.SetFunctionName(functionName);

        Aws::Lambda::Model::GetFunctionOutcome outcome = client.GetFunction(request);

        if (outcome.IsSuccess()) {
            std::cout << "Function retrieve.\n" <<
                      outcome.GetResult().GetConfiguration().Jsonize().View().WriteReadable()
                      << std::endl;
        }
        else {
            std::cerr << "Error with Lambda::GetFunction. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
```
+  有关 API 详细信息，请参阅《适用于 C\$1\$1 的 Amazon SDK API Reference》**中的 [GetFunction](https://docs.amazonaws.cn/goto/SdkForCpp/lambda-2015-03-31/GetFunction)。

------
#### [ CLI ]

**Amazon CLI**  
**检索有关函数的信息**  
以下 `get-function` 示例显示有关 `my-function` 函数的信息：  

```
aws lambda get-function \
    --function-name  my-function
```
输出：  

```
{
    "Concurrency": {
        "ReservedConcurrentExecutions": 100
    },
    "Code": {
        "RepositoryType": "S3",
        "Location": "https://awslambda-us-west-2-tasks.s3.us-west-2.amazonaws.com/snapshots/123456789012/my-function..."
    },
    "Configuration": {
        "TracingConfig": {
            "Mode": "PassThrough"
        },
        "Version": "$LATEST",
        "CodeSha256": "5tT2qgzYUHoqwR616pZ2dpkn/0J1FrzJmlKidWaaCgk=",
        "FunctionName": "my-function",
        "VpcConfig": {
            "SubnetIds": [],
            "VpcId": "",
            "SecurityGroupIds": []
        },
        "MemorySize": 128,
        "RevisionId": "28f0fb31-5c5c-43d3-8955-03e76c5c1075",
        "CodeSize": 304,
        "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
        "Handler": "index.handler",
        "Role": "arn:aws:iam::123456789012:role/service-role/helloWorldPython-role-uy3l9qyq",
        "Timeout": 3,
        "LastModified": "2025-09-24T18:20:35.054+0000",
        "Runtime": "nodejs22.x",
        "Description": ""
    }
}
```
有关更多信息，请参阅*《Amazon Lambda 开发人员指南》*中的 [配置 Lambda 函数内存](https://docs.amazonaws.cn/lambda/latest/dg/configuration-memory.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI Command Reference》中的 [GetFunction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-function.html)。**

------
#### [ Go ]

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// 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
}



// GetFunction gets data about the Lambda function specified by functionName.
func (wrapper FunctionWrapper) GetFunction(ctx context.Context, functionName string) types.State {
	var state types.State
	funcOutput, err := wrapper.LambdaClient.GetFunction(ctx, &lambda.GetFunctionInput{
		FunctionName: aws.String(functionName),
	})
	if err != nil {
		log.Panicf("Couldn't get function %v. Here's why: %v\n", functionName, err)
	} else {
		state = funcOutput.Configuration.State
	}
	return state
}
```
+  有关 API 详细信息，请参阅《适用于 Go 的 Amazon SDK API Reference》**中的 [GetFunction](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.GetFunction)。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Retrieves information about an AWS Lambda function.
     *
     * @param awsLambda    an instance of the {@link LambdaClient} class, which is used to interact with the AWS Lambda service
     * @param functionName the name of the AWS Lambda function to retrieve information about
     */
    public static void getFunction(LambdaClient awsLambda, String functionName) {
        try {
            GetFunctionRequest functionRequest = GetFunctionRequest.builder()
                .functionName(functionName)
                .build();

            GetFunctionResponse response = awsLambda.getFunction(functionRequest);
            System.out.println("The runtime of this Lambda function is " + response.configuration().runtime());

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Java 2.x API Reference》**中的 [GetFunction](https://docs.amazonaws.cn/goto/SdkForJavaV2/lambda-2015-03-31/GetFunction)。

------
#### [ JavaScript ]

**适用于 JavaScript 的 SDK（v3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
const getFunction = (funcName) => {
  const client = new LambdaClient({});
  const command = new GetFunctionCommand({ FunctionName: funcName });
  return client.send(command);
};
```
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [GetFunction](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/lambda/command/GetFunctionCommand)。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function getFunction($functionName)
    {
        return $this->lambdaClient->getFunction([
            'FunctionName' => $functionName,
        ]);
    }
```
+  有关 API 详细信息，请参阅《适用于 PHP 的 Amazon SDK API Reference》**中的 [GetFunction](https://docs.amazonaws.cn/goto/SdkForPHPV3/lambda-2015-03-31/GetFunction)。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    def get_function(self, function_name):
        """
        Gets data about a Lambda function.

        :param function_name: The name of the function.
        :return: The function data.
        """
        response = None
        try:
            response = self.lambda_client.get_function(FunctionName=function_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.info("Function %s does not exist.", function_name)
            else:
                logger.error(
                    "Couldn't get function %s. Here's why: %s: %s",
                    function_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        return response
```
+  有关 API 详细信息，请参阅《Amazon SDK for Python (Boto3) API Reference》**中的 [GetFunction](https://docs.amazonaws.cn/goto/boto3/lambda-2015-03-31/GetFunction)。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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

  # Gets data about a Lambda function.
  #
  # @param function_name: The name of the function.
  # @return response: The function data, or nil if no such function exists.
  def get_function(function_name)
    @lambda_client.get_function(
      {
        function_name: function_name
      }
    )
  rescue Aws::Lambda::Errors::ResourceNotFoundException => e
    @logger.debug("Could not find function: #{function_name}:\n #{e.message}")
    nil
  end
```
+  有关 API 详细信息，请参阅《适用于 Ruby 的 Amazon SDK API Reference》**中的 [GetFunction](https://docs.amazonaws.cn/goto/SdkForRubyV3/lambda-2015-03-31/GetFunction)。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /** Get the Lambda function with this Manager's name. */
    pub async fn get_function(&self) -> Result<GetFunctionOutput, anyhow::Error> {
        info!("Getting lambda function");
        self.lambda_client
            .get_function()
            .function_name(self.lambda_name.clone())
            .send()
            .await
            .map_err(anyhow::Error::from)
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Rust API Reference》**中的 [GetFunction](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.get_function)。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        oo_result = lo_lmd->getfunction( iv_functionname = iv_function_name ).       " oo_result is returned for testing purposes. "
        MESSAGE 'Lambda function information retrieved.' TYPE 'I'.
      CATCH /aws1/cx_lmdinvparamvalueex.
        MESSAGE 'The request contains a non-valid parameter.' 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 的 Amazon SDK 的 API 参考*中的 [GetFunction](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

------
#### [ Swift ]

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import AWSClientRuntime
import AWSLambda
import Foundation

    /// Detect whether or not the AWS Lambda function with the specified name
    /// exists, by requesting its function information.
    ///
    /// - Parameters:
    ///   - lambdaClient: The `LambdaClient` to use.
    ///   - name: The name of the AWS Lambda function to find.
    ///
    /// - Returns: `true` if the Lambda function exists. Otherwise `false`.
    func doesLambdaFunctionExist(lambdaClient: LambdaClient, name: String) async -> Bool {
        do {
            _ = try await lambdaClient.getFunction(
                input: GetFunctionInput(functionName: name)
            )
        } catch {
            return false
        }

        return true
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Swift API reference》**中的 [GetFunction](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/getfunction(input:))。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `GetFunctionConcurrency` 与 CLI 配合使用
`GetFunctionConcurrency`

以下代码示例演示如何使用 `GetFunctionConcurrency`。

------
#### [ CLI ]

**Amazon CLI**  
**查看函数的预留并发设置**  
以下 `get-function-concurrency` 示例检索了指定函数的预留并发设置。  

```
aws lambda get-function-concurrency \
    --function-name my-function
```
输出：  

```
{
    "ReservedConcurrentExecutions": 250
}
```
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [GetFunctionConcurrency](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-function-concurrency.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例获取了 Lambda 函数的预留并发**  

```
Get-LMFunctionConcurrency -FunctionName "MylambdaFunction123" -Select *
```
**输出**：  

```
ReservedConcurrentExecutions
----------------------------
100
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [GetFunctionConcurrency](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例获取了 Lambda 函数的预留并发**  

```
Get-LMFunctionConcurrency -FunctionName "MylambdaFunction123" -Select *
```
**输出**：  

```
ReservedConcurrentExecutions
----------------------------
100
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [GetFunctionConcurrency](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `GetFunctionConfiguration` 与 CLI 配合使用
`GetFunctionConfiguration`

以下代码示例演示如何使用 `GetFunctionConfiguration`。

------
#### [ CLI ]

**Amazon CLI**  
**检索 Lambda 函数的版本特定设置**  
以下 `get-function-configuration` 示例展示了 `my-function` 函数版本 2 的设置。  

```
aws lambda get-function-configuration \
    --function-name  my-function:2
```
输出：  

```
{
    "FunctionName": "my-function",
    "LastModified": "2019-09-26T20:28:40.438+0000",
    "RevisionId": "e52502d4-9320-4688-9cd6-152a6ab7490d",
    "MemorySize": 256,
    "Version": "2",
    "Role": "arn:aws:iam::123456789012:role/service-role/my-function-role-uy3l9qyq",
    "Timeout": 3,
    "Runtime": "nodejs10.x",
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "CodeSha256": "5tT2qgzYUHaqwR716pZ2dpkn/0J1FrzJmlKidWoaCgk=",
    "Description": "",
    "VpcConfig": {
        "SubnetIds": [],
        "VpcId": "",
        "SecurityGroupIds": []
    },
    "CodeSize": 304,
    "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:2",
    "Handler": "index.handler"
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》中的 [Amazon Lambda 函数配置](https://docs.amazonaws.cn/lambda/latest/dg/resource-model.html)。**  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [GetFunctionConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-function-configuration.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例返回了 Lambda 函数的版本特定配置。**  

```
Get-LMFunctionConfiguration -FunctionName "MylambdaFunction123" -Qualifier "PowershellAlias"
```
**输出**：  

```
CodeSha256                 : uWOW0R7z+f0VyLuUg7+/D08hkMFsq0SF4seuyUZJ/R8=
CodeSize                   : 1426
DeadLetterConfig           : Amazon.Lambda.Model.DeadLetterConfig
Description                : Verson 3 to test Aliases
Environment                : Amazon.Lambda.Model.EnvironmentResponse
FunctionArn                : arn:aws:lambda:us-east-1:123456789012:function:MylambdaFunction123
                             :PowershellAlias
FunctionName               : MylambdaFunction123
Handler                    : lambda_function.launch_instance
KMSKeyArn                  : 
LastModified               : 2019-12-25T09:52:59.872+0000
LastUpdateStatus           : Successful
LastUpdateStatusReason     : 
LastUpdateStatusReasonCode : 
Layers                     : {}
MasterArn                  : 
MemorySize                 : 128
RevisionId                 : 5d7de38b-87f2-4260-8f8a-e87280e10c33
Role                       : arn:aws:iam::123456789012:role/service-role/lambda
Runtime                    : python3.8
State                      : Active
StateReason                : 
StateReasonCode            : 
Timeout                    : 600
TracingConfig              : Amazon.Lambda.Model.TracingConfigResponse
Version                    : 4
VpcConfig                  : Amazon.Lambda.Model.VpcConfigDetail
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [GetFunctionConfiguration](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例返回了 Lambda 函数的版本特定配置。**  

```
Get-LMFunctionConfiguration -FunctionName "MylambdaFunction123" -Qualifier "PowershellAlias"
```
**输出**：  

```
CodeSha256                 : uWOW0R7z+f0VyLuUg7+/D08hkMFsq0SF4seuyUZJ/R8=
CodeSize                   : 1426
DeadLetterConfig           : Amazon.Lambda.Model.DeadLetterConfig
Description                : Verson 3 to test Aliases
Environment                : Amazon.Lambda.Model.EnvironmentResponse
FunctionArn                : arn:aws:lambda:us-east-1:123456789012:function:MylambdaFunction123
                             :PowershellAlias
FunctionName               : MylambdaFunction123
Handler                    : lambda_function.launch_instance
KMSKeyArn                  : 
LastModified               : 2019-12-25T09:52:59.872+0000
LastUpdateStatus           : Successful
LastUpdateStatusReason     : 
LastUpdateStatusReasonCode : 
Layers                     : {}
MasterArn                  : 
MemorySize                 : 128
RevisionId                 : 5d7de38b-87f2-4260-8f8a-e87280e10c33
Role                       : arn:aws:iam::123456789012:role/service-role/lambda
Runtime                    : python3.8
State                      : Active
StateReason                : 
StateReasonCode            : 
Timeout                    : 600
TracingConfig              : Amazon.Lambda.Model.TracingConfigResponse
Version                    : 4
VpcConfig                  : Amazon.Lambda.Model.VpcConfigDetail
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [GetFunctionConfiguration](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `GetPolicy` 与 CLI 配合使用
`GetPolicy`

以下代码示例演示如何使用 `GetPolicy`。

------
#### [ CLI ]

**Amazon CLI**  
**检索函数、版本或别名的基于资源的 IAM 策略**  
以下 `get-policy` 示例展示了有关 `my-function` Lambda 函数的策略信息。  

```
aws lambda get-policy \
    --function-name my-function
```
输出：  

```
{
    "Policy": {
        "Version":"2012-10-17",		 	 	 
        "Id":"default",
        "Statement":
        [
            {
                "Sid":"iot-events",
                "Effect":"Allow",
                "Principal": {"Service":"iotevents.amazonaws.com"},
                "Action":"lambda:InvokeFunction",
                "Resource":"arn:aws:lambda:us-west-2:123456789012:function:my-function"
            }
        ]
    },
    "RevisionId": "93017fc9-59cb-41dc-901b-4845ce4bf668"
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[对 Amazon Lambda 使用基于资源的策略](https://docs.amazonaws.cn/lambda/latest/dg/access-control-resource-based.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [GetPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-policy.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例展示了 Lambda 函数的函数策略**  

```
Get-LMPolicy -FunctionName test -Select Policy
```
**输出**：  

```
{"Version":"2012-10-17",		 	 	 "Id":"default","Statement":[{"Sid":"xxxx","Effect":"Allow","Principal":{"Service":"sns.amazonaws.com"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-east-1:123456789102:function:test"}]}
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [GetPolicy](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例展示了 Lambda 函数的函数策略**  

```
Get-LMPolicy -FunctionName test -Select Policy
```
**输出**：  

```
{"Version":"2012-10-17",		 	 	 "Id":"default","Statement":[{"Sid":"xxxx","Effect":"Allow","Principal":{"Service":"sns.amazonaws.com"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-east-1:123456789102:function:test"}]}
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V5)*》中的 [GetPolicy](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `GetProvisionedConcurrencyConfig` 与 CLI 配合使用
`GetProvisionedConcurrencyConfig`

以下代码示例演示如何使用 `GetProvisionedConcurrencyConfig`。

------
#### [ CLI ]

**Amazon CLI**  
**查看预置并发配置**  
以下 `get-provisioned-concurrency-config` 示例展示了指定函数 `BLUE` 别名的预置并发配置的详细信息。  

```
aws lambda get-provisioned-concurrency-config \
    --function-name my-function \
    --qualifier BLUE
```
输出：  

```
{
    "RequestedProvisionedConcurrentExecutions": 100,
    "AvailableProvisionedConcurrentExecutions": 100,
    "AllocatedProvisionedConcurrentExecutions": 100,
    "Status": "READY",
    "LastModified": "2019-12-31T20:28:49+0000"
}
```
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [GetProvisionedConcurrencyConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-provisioned-concurrency-config.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例获取了 Lambda 函数指定别名的预置并发配置。**  

```
C:\>Get-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -Qualifier "NewAlias1"
```
**输出**：  

```
AllocatedProvisionedConcurrentExecutions : 0
AvailableProvisionedConcurrentExecutions : 0
LastModified                             : 2020-01-15T03:21:26+0000
RequestedProvisionedConcurrentExecutions : 70
Status                                   : IN_PROGRESS
StatusReason                             :
```
+  有关 API 的详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [GetProvisionedConcurrencyConfig](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例获取了 Lambda 函数指定别名的预置并发配置。**  

```
C:\>Get-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -Qualifier "NewAlias1"
```
**输出**：  

```
AllocatedProvisionedConcurrentExecutions : 0
AvailableProvisionedConcurrentExecutions : 0
LastModified                             : 2020-01-15T03:21:26+0000
RequestedProvisionedConcurrentExecutions : 70
Status                                   : IN_PROGRESS
StatusReason                             :
```
+  有关 API 的详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [GetProvisionedConcurrencyConfig](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `Invoke` 与 Amazon SDK 或 CLI 配合使用
`Invoke`

以下代码示例演示如何使用 `Invoke`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_lambda_Scenario_GettingStartedFunctions_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 Amazon SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Invoke a Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the Lambda function to
    /// invoke.</param
    /// <param name="parameters">The parameter values that will be passed to the function.</param>
    /// <returns>A System Threading Task.</returns>
    public async Task<string> InvokeFunctionAsync(
        string functionName,
        string parameters)
    {
        var payload = parameters;
        var request = new InvokeRequest
        {
            FunctionName = functionName,
            Payload = payload,
        };

        var response = await _lambdaService.InvokeAsync(request);
        MemoryStream stream = response.Payload;
        string returnValue = System.Text.Encoding.UTF8.GetString(stream.ToArray());
        return returnValue;
    }
```
+  有关 API 详细信息，请参阅《适用于 .NET 的 Amazon SDK API Reference》**中的 [Invoke](https://docs.amazonaws.cn/goto/DotNetSDKV3/lambda-2015-03-31/Invoke)。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::InvokeRequest request;
        request.SetFunctionName(LAMBDA_NAME);
        request.SetLogType(logType);
        std::shared_ptr<Aws::IOStream> payload = Aws::MakeShared<Aws::StringStream>(
                "FunctionTest");
        *payload << jsonPayload.View().WriteReadable();
        request.SetBody(payload);
        request.SetContentType("application/json");
        Aws::Lambda::Model::InvokeOutcome outcome = client.Invoke(request);

        if (outcome.IsSuccess()) {
            invokeResult = std::move(outcome.GetResult());
            result = true;
            break;
        }

        else {
            std::cerr << "Error with Lambda::InvokeRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            break;
        }
```
+  有关 API 详细信息，请参阅《适用于 C\$1\$1 的 Amazon SDK API Reference》**中的 [Invoke](https://docs.amazonaws.cn/goto/SdkForCpp/lambda-2015-03-31/Invoke)。

------
#### [ CLI ]

**Amazon CLI**  
**示例 1：同步调用 Lambda 函数**  
以下 `invoke` 示例同步调用该 `my-function` 函数。如果使用 `cli-binary-format` CLI 版本 2，则 Amazon 选项是必需的。有关更多信息，请参阅《Amazon 命令行界面用户指南》中 [Amazon CLI 支持的全局命令行选项](https://docs.amazonaws.cn/cli/latest/userguide/cli-configure-options.html#cli-configure-options-list)。**  

```
aws lambda invoke \
    --function-name my-function \
    --cli-binary-format raw-in-base64-out \
    --payload '{ "name": "Bob" }' \
    response.json
```
输出：  

```
{
    "ExecutedVersion": "$LATEST",
    "StatusCode": 200
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[同步调用 Lambda 函数](https://docs.amazonaws.cn/lambda/latest/dg/invocation-sync.html)。  
**示例 2：异步调用 Lambda 函数**  
以下 `invoke` 示例异步调用该 `my-function` 函数。如果使用 `cli-binary-format` CLI 版本 2，则 Amazon 选项是必需的。有关更多信息，请参阅《Amazon 命令行界面用户指南》中 [Amazon CLI 支持的全局命令行选项](https://docs.amazonaws.cn/cli/latest/userguide/cli-configure-options.html#cli-configure-options-list)。**  

```
aws lambda invoke \
    --function-name my-function \
    --invocation-type Event \
    --cli-binary-format raw-in-base64-out \
    --payload '{ "name": "Bob" }' \
    response.json
```
输出：  

```
{
    "StatusCode": 202
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[异步调用 Lambda 函数](https://docs.amazonaws.cn/lambda/latest/dg/invocation-async.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI Command Reference》**中的 [Invoke](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/invoke.html)。

------
#### [ Go ]

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// 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
}



// Invoke invokes the Lambda function specified by functionName, passing the parameters
// as a JSON payload. When getLog is true, types.LogTypeTail is specified, which tells
// Lambda to include the last few log lines in the returned result.
func (wrapper FunctionWrapper) Invoke(ctx context.Context, functionName string, parameters any, getLog bool) *lambda.InvokeOutput {
	logType := types.LogTypeNone
	if getLog {
		logType = types.LogTypeTail
	}
	payload, err := json.Marshal(parameters)
	if err != nil {
		log.Panicf("Couldn't marshal parameters to JSON. Here's why %v\n", err)
	}
	invokeOutput, err := wrapper.LambdaClient.Invoke(ctx, &lambda.InvokeInput{
		FunctionName: aws.String(functionName),
		LogType:      logType,
		Payload:      payload,
	})
	if err != nil {
		log.Panicf("Couldn't invoke function %v. Here's why: %v\n", functionName, err)
	}
	return invokeOutput
}
```
+  有关 API 详细信息，请参阅《适用于 Go 的 Amazon SDK API Reference》**中的 [Invoke](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.Invoke)。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Invokes a specific AWS Lambda function.
     *
     * @param awsLambda    an instance of {@link LambdaClient} to interact with the AWS Lambda service
     * @param functionName the name of the AWS Lambda function to be invoked
     */
    public static void invokeFunction(LambdaClient awsLambda, String functionName) {
        InvokeResponse res;
        try {
            // Need a SdkBytes instance for the payload.
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("inputValue", "2000");
            String json = jsonObj.toString();
            SdkBytes payload = SdkBytes.fromUtf8String(json);

            InvokeRequest request = InvokeRequest.builder()
                .functionName(functionName)
                .payload(payload)
                .build();

            res = awsLambda.invoke(request);
            String value = res.payload().asUtf8String();
            System.out.println(value);

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Java 2.x API Reference》**中的 [Invoke](https://docs.amazonaws.cn/goto/SdkForJavaV2/lambda-2015-03-31/Invoke)。

------
#### [ JavaScript ]

**适用于 JavaScript 的 SDK（v3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
const invoke = async (funcName, payload) => {
  const client = new LambdaClient({});
  const command = new InvokeCommand({
    FunctionName: funcName,
    Payload: JSON.stringify(payload),
    LogType: LogType.Tail,
  });

  const { Payload, LogResult } = await client.send(command);
  const result = Buffer.from(Payload).toString();
  const logs = Buffer.from(LogResult, "base64").toString();
  return { logs, result };
};
```
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [Invoke](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/lambda/command/InvokeCommand)。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun invokeFunction(functionNameVal: String) {
    val json = """{"inputValue":"1000"}"""
    val byteArray = json.trimIndent().encodeToByteArray()
    val request =
        InvokeRequest {
            functionName = functionNameVal
            logType = LogType.Tail
            payload = byteArray
        }

    LambdaClient { region = "us-west-2" }.use { awsLambda ->
        val res = awsLambda.invoke(request)
        println("${res.payload?.toString(Charsets.UTF_8)}")
        println("The log result is ${res.logResult}")
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Kotlin API Reference》**中的 [Invoke](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function invoke($functionName, $params, $logType = 'None')
    {
        return $this->lambdaClient->invoke([
            'FunctionName' => $functionName,
            'Payload' => json_encode($params),
            'LogType' => $logType,
        ]);
    }
```
+  有关 API 详细信息，请参阅《适用于 PHP 的 Amazon SDK API Reference》**中的 [Invoke](https://docs.amazonaws.cn/goto/SdkForPHPV3/lambda-2015-03-31/Invoke)。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    def invoke_function(self, function_name, function_params, get_log=False):
        """
        Invokes a Lambda function.

        :param function_name: The name of the function to invoke.
        :param function_params: The parameters of the function as a dict. This dict
                                is serialized to JSON before it is sent to Lambda.
        :param get_log: When true, the last 4 KB of the execution log are included in
                        the response.
        :return: The response from the function invocation.
        """
        try:
            response = self.lambda_client.invoke(
                FunctionName=function_name,
                Payload=json.dumps(function_params),
                LogType="Tail" if get_log else "None",
            )
            logger.info("Invoked function %s.", function_name)
        except ClientError:
            logger.exception("Couldn't invoke function %s.", function_name)
            raise
        return response
```
+  有关 API 详细信息，请参阅《Amazon SDK for Python (Boto3) API Reference》**中的 [Invoke](https://docs.amazonaws.cn/goto/boto3/lambda-2015-03-31/Invoke)。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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

  # Invokes a Lambda function.
  # @param function_name [String] The name of the function to invoke.
  # @param payload [nil] Payload containing runtime parameters.
  # @return [Object] The response from the function invocation.
  def invoke_function(function_name, payload = nil)
    params = { function_name: function_name }
    params[:payload] = payload unless payload.nil?
    @lambda_client.invoke(params)
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error executing #{function_name}:\n #{e.message}")
  end
```
+  有关 API 详细信息，请参阅《适用于 Ruby 的 Amazon SDK API Reference》**中的 [Invoke](https://docs.amazonaws.cn/goto/SdkForRubyV3/lambda-2015-03-31/Invoke)。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /** Invoke the lambda function using calculator InvokeArgs. */
    pub async fn invoke(&self, args: InvokeArgs) -> Result<InvokeOutput, anyhow::Error> {
        info!(?args, "Invoking {}", self.lambda_name);
        let payload = serde_json::to_string(&args)?;
        debug!(?payload, "Sending payload");
        self.lambda_client
            .invoke()
            .function_name(self.lambda_name.clone())
            .payload(Blob::new(payload))
            .send()
            .await
            .map_err(anyhow::Error::from)
    }

fn log_invoke_output(invoke: &InvokeOutput, message: &str) {
    if let Some(payload) = invoke.payload().cloned() {
        let payload = String::from_utf8(payload.into_inner());
        info!(?payload, message);
    } else {
        info!("Could not extract payload")
    }
    if let Some(logs) = invoke.log_result() {
        debug!(?logs, "Invoked function logs")
    } else {
        debug!("Invoked function had no logs")
    }
}
```
+  有关 API 详细信息，请参阅《Amazon SDK for Rust API Reference》**中的[调用](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.invoke)。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        DATA(lv_json) = /aws1/cl_rt_util=>string_to_xstring(
          `{`  &&
            `"action": "increment",`  &&
            `"number": 10` &&
          `}` ).
        oo_result = lo_lmd->invoke(                  " oo_result is returned for testing purposes. "
                 iv_functionname = iv_function_name
                 iv_payload = lv_json ).
        MESSAGE 'Lambda function invoked.' TYPE 'I'.
      CATCH /aws1/cx_lmdinvparamvalueex.
        MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
      CATCH /aws1/cx_lmdinvrequestcontex.
        MESSAGE 'Unable to parse request body as JSON.' TYPE 'E'.
      CATCH /aws1/cx_lmdinvalidzipfileex.
        MESSAGE 'The deployment package could not be unzipped.' TYPE 'E'.
      CATCH /aws1/cx_lmdrequesttoolargeex.
        MESSAGE 'Invoke request body JSON input limit was exceeded by the request payload.' 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'.
      CATCH /aws1/cx_lmdunsuppedmediatyp00.
        MESSAGE 'Invoke request body does not have JSON as its content type.' TYPE 'E'.
    ENDTRY.
```
+  有关 API 详细信息，请参阅*适用于 SAP ABAP 的 Amazon SDK 的 API 参考*中的[调用](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

------
#### [ Swift ]

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import AWSClientRuntime
import AWSLambda
import Foundation

    /// Invoke the Lambda function to increment a value.
    /// 
    /// - Parameters:
    ///   - lambdaClient: The `IAMClient` to use.
    ///   - number: The number to increment.
    ///
    /// - Throws: `ExampleError.noAnswerReceived`, `ExampleError.invokeError`
    ///
    /// - Returns: An integer number containing the incremented value.
    func invokeIncrement(lambdaClient: LambdaClient, number: Int) async throws -> Int {
        do {
            let incRequest = IncrementRequest(action: "increment", number: number)
            let incData = try! JSONEncoder().encode(incRequest)

            // Invoke the lambda function.

            let invokeOutput = try await lambdaClient.invoke(
                input: InvokeInput(
                    functionName: "lambda-basics-function",
                    payload: incData
                )
            )

            let response = try! JSONDecoder().decode(Response.self, from:invokeOutput.payload!)

            guard let answer = response.answer else {
                throw ExampleError.noAnswerReceived
            }
            return answer

        } catch {
            throw ExampleError.invokeError
        }
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Swift API Reference》**中的 [Invoke](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/invoke(input:))。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `ListFunctions` 与 Amazon SDK 或 CLI 配合使用
`ListFunctions`

以下代码示例演示如何使用 `ListFunctions`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_lambda_Scenario_GettingStartedFunctions_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 Amazon SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Get a list of Lambda functions.
    /// </summary>
    /// <returns>A list of FunctionConfiguration objects.</returns>
    public async Task<List<FunctionConfiguration>> ListFunctionsAsync()
    {
        var functionList = new List<FunctionConfiguration>();

        var functionPaginator =
            _lambdaService.Paginators.ListFunctions(new ListFunctionsRequest());
        await foreach (var function in functionPaginator.Functions)
        {
            functionList.Add(function);
        }

        return functionList;
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 Amazon SDK API 参考*中的 [ListFunctions](https://docs.amazonaws.cn/goto/DotNetSDKV3/lambda-2015-03-31/ListFunctions)。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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);

    std::vector<Aws::String> functions;
    Aws::String marker;

    do {
        Aws::Lambda::Model::ListFunctionsRequest request;
        if (!marker.empty()) {
            request.SetMarker(marker);
        }

        Aws::Lambda::Model::ListFunctionsOutcome outcome = client.ListFunctions(
                request);

        if (outcome.IsSuccess()) {
            const Aws::Lambda::Model::ListFunctionsResult &result = outcome.GetResult();
            std::cout << result.GetFunctions().size()
                      << " lambda functions were retrieved." << std::endl;

            for (const Aws::Lambda::Model::FunctionConfiguration &functionConfiguration: result.GetFunctions()) {
                functions.push_back(functionConfiguration.GetFunctionName());
                std::cout << functions.size() << "  "
                          << functionConfiguration.GetDescription() << std::endl;
                std::cout << "   "
                          << Aws::Lambda::Model::RuntimeMapper::GetNameForRuntime(
                                  functionConfiguration.GetRuntime()) << ": "
                          << functionConfiguration.GetHandler()
                          << std::endl;
            }
            marker = result.GetNextMarker();
        }
        else {
            std::cerr << "Error with Lambda::ListFunctions. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
    } while (!marker.empty());
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 Amazon SDK API 参考*中的 [ListFunctions](https://docs.amazonaws.cn/goto/SdkForCpp/lambda-2015-03-31/ListFunctions)。

------
#### [ CLI ]

**Amazon CLI**  
**检索 Lambda 函数列表**  
以下 `list-functions` 示例显示当前用户所有函数的列表。  

```
aws lambda list-functions
```
输出：  

```
{
    "Functions": [
        {
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "Version": "$LATEST",
            "CodeSha256": "dBG9m8SGdmlEjw/JYXlhhvCrAv5TxvXsbL/RMr0fT/I=",
            "FunctionName": "helloworld",
            "MemorySize": 128,
            "RevisionId": "1718e831-badf-4253-9518-d0644210af7b",
            "CodeSize": 294,
            "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:helloworld",
            "Handler": "helloworld.handler",
            "Role": "arn:aws:iam::123456789012:role/service-role/MyTestFunction-role-zgur6bf4",
            "Timeout": 3,
            "LastModified": "2025-09-23T18:32:33.857+0000",
            "Runtime": "nodejs22.x",
            "Description": ""
        },
        {
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "Version": "$LATEST",
            "CodeSha256": "sU0cJ2/hOZevwV/lTxCuQqK3gDZP3i8gUoqUUVRmY6E=",
            "FunctionName": "my-function",
            "VpcConfig": {
                "SubnetIds": [],
                "VpcId": "",
                "SecurityGroupIds": []
            },
            "MemorySize": 256,
            "RevisionId": "93017fc9-59cb-41dc-901b-4845ce4bf668",
            "CodeSize": 266,
            "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
            "Handler": "index.handler",
            "Role": "arn:aws:iam::123456789012:role/service-role/helloWorldPython-role-uy3l9qyq",
            "Timeout": 3,
            "LastModified": "2025-10-01T16:47:28.490+0000",
            "Runtime": "nodejs22.x",
            "Description": ""
        },
        {
            "Layers": [
                {
                    "CodeSize": 41784542,
                    "Arn": "arn:aws:lambda:us-west-2:420165488524:layer:AWSLambda-Python37-SciPy1x:2"
                },
                {
                    "CodeSize": 4121,
                    "Arn": "arn:aws:lambda:us-west-2:123456789012:layer:pythonLayer:1"
                }
            ],
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "Version": "$LATEST",
            "CodeSha256": "ZQukCqxtkqFgyF2cU41Avj99TKQ/hNihPtDtRcc08mI=",
            "FunctionName": "my-python-function",
            "VpcConfig": {
                "SubnetIds": [],
                "VpcId": "",
                "SecurityGroupIds": []
            },
            "MemorySize": 128,
            "RevisionId": "80b4eabc-acf7-4ea8-919a-e874c213707d",
            "CodeSize": 299,
            "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-python-function",
            "Handler": "lambda_function.lambda_handler",
            "Role": "arn:aws:iam::123456789012:role/service-role/my-python-function-role-z5g7dr6n",
            "Timeout": 3,
            "LastModified": "2025-10-01T19:40:41.643+0000",
            "Runtime": "python3.11",
            "Description": ""
        }
    ]
}
```
有关更多信息，请参阅*《Amazon Lambda 开发人员指南》*中的 [配置 Lambda 函数内存](https://docs.amazonaws.cn/lambda/latest/dg/configuration-memory.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI Command Reference》**中的 [ListFunctions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/list-functions.html)。

------
#### [ Go ]

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// 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
}



// ListFunctions lists up to maxItems functions for the account. This function uses a
// lambda.ListFunctionsPaginator to paginate the results.
func (wrapper FunctionWrapper) ListFunctions(ctx context.Context, maxItems int) []types.FunctionConfiguration {
	var functions []types.FunctionConfiguration
	paginator := lambda.NewListFunctionsPaginator(wrapper.LambdaClient, &lambda.ListFunctionsInput{
		MaxItems: aws.Int32(int32(maxItems)),
	})
	for paginator.HasMorePages() && len(functions) < maxItems {
		pageOutput, err := paginator.NextPage(ctx)
		if err != nil {
			log.Panicf("Couldn't list functions for your account. Here's why: %v\n", err)
		}
		functions = append(functions, pageOutput.Functions...)
	}
	return functions
}
```
+  有关 API 的详细信息，请参阅 *适用于 Go 的 Amazon SDK API 参考*中的 [ListFunctions](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.ListFunctions)。

------
#### [ JavaScript ]

**适用于 JavaScript 的 SDK（v3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
const listFunctions = () => {
  const client = new LambdaClient({});
  const command = new ListFunctionsCommand({});

  return client.send(command);
};
```
+  有关 API 的详细信息，请参阅 *适用于 JavaScript 的 Amazon SDK API 参考*中的 [ListFunctions](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/lambda/command/ListFunctionsCommand)。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function listFunctions($maxItems = 50, $marker = null)
    {
        if (is_null($marker)) {
            return $this->lambdaClient->listFunctions([
                'MaxItems' => $maxItems,
            ]);
        }

        return $this->lambdaClient->listFunctions([
            'Marker' => $marker,
            'MaxItems' => $maxItems,
        ]);
    }
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 Amazon SDK API 参考*中的 [ListFunctions](https://docs.amazonaws.cn/goto/SdkForPHPV3/lambda-2015-03-31/ListFunctions)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例展示了代码大小已排序的所有 Lambda 函数**  

```
Get-LMFunctionList | Sort-Object -Property CodeSize | Select-Object FunctionName, RunTime, Timeout, CodeSize
```
**输出**：  

```
FunctionName                                                 Runtime   Timeout CodeSize
------------                                                 -------   ------- --------
test                                                         python2.7       3      243
MylambdaFunction123                                          python3.8     600      659
myfuncpython1                                                python3.8     303      675
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [ListFunctions](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例展示了代码大小已排序的所有 Lambda 函数**  

```
Get-LMFunctionList | Sort-Object -Property CodeSize | Select-Object FunctionName, RunTime, Timeout, CodeSize
```
**输出**：  

```
FunctionName                                                 Runtime   Timeout CodeSize
------------                                                 -------   ------- --------
test                                                         python2.7       3      243
MylambdaFunction123                                          python3.8     600      659
myfuncpython1                                                python3.8     303      675
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V5)*》中的 [ListFunctions](https://docs.amazonaws.cn/powershell/v5/reference)。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    def list_functions(self):
        """
        Lists the Lambda functions for the current account.
        """
        try:
            func_paginator = self.lambda_client.get_paginator("list_functions")
            for func_page in func_paginator.paginate():
                for func in func_page["Functions"]:
                    print(func["FunctionName"])
                    desc = func.get("Description")
                    if desc:
                        print(f"\t{desc}")
                    print(f"\t{func['Runtime']}: {func['Handler']}")
        except ClientError as err:
            logger.error(
                "Couldn't list functions. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  有关 API 详细信息，请参阅《Amazon SDK for Python (Boto3) API Reference》**中的 [ListFunctions](https://docs.amazonaws.cn/goto/boto3/lambda-2015-03-31/ListFunctions)。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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

  # Lists the Lambda functions for the current account.
  def list_functions
    functions = []
    @lambda_client.list_functions.each do |response|
      response['functions'].each do |function|
        functions.append(function['function_name'])
      end
    end
    functions
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error listing functions:\n #{e.message}")
  end
```
+  有关 API 的详细信息，请参阅 *适用于 Ruby 的 Amazon SDK API 参考*中的 [ListFunctions](https://docs.amazonaws.cn/goto/SdkForRubyV3/lambda-2015-03-31/ListFunctions)。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /** List all Lambda functions in the current Region. */
    pub async fn list_functions(&self) -> Result<ListFunctionsOutput, anyhow::Error> {
        info!("Listing lambda functions");
        self.lambda_client
            .list_functions()
            .send()
            .await
            .map_err(anyhow::Error::from)
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Rust API Reference》**中的 [ListFunctions](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.list_functions)。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        oo_result = lo_lmd->listfunctions( ).       " oo_result is returned for testing purposes. "
        DATA(lt_functions) = oo_result->get_functions( ).
        MESSAGE 'Retrieved list of Lambda functions.' TYPE 'I'.
      CATCH /aws1/cx_lmdinvparamvalueex.
        MESSAGE 'The request contains a non-valid parameter.' 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 的 Amazon SDK 的 API 参考*中的 [ListFunctions](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

------
#### [ Swift ]

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import AWSClientRuntime
import AWSLambda
import Foundation

    /// Returns an array containing the names of all AWS Lambda functions
    /// available to the user.
    ///
    /// - Parameter lambdaClient: The `IAMClient` to use.
    ///
    /// - Throws: `ExampleError.listFunctionsError`
    ///
    /// - Returns: An array of lambda function name strings.
    func getFunctionNames(lambdaClient: LambdaClient) async throws -> [String] {
        let pages = lambdaClient.listFunctionsPaginated(
            input: ListFunctionsInput()
        )

        var functionNames: [String] = []

        for try await page in pages {
            guard let functions = page.functions else {
                throw ExampleError.listFunctionsError
            }

            for function in functions {
                functionNames.append(function.functionName ?? "<unknown>")
            }
        }

        return functionNames
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Swift API Reference》**中的 [ListFunctions](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/listfunctions(input:))。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `ListProvisionedConcurrencyConfigs` 与 CLI 配合使用
`ListProvisionedConcurrencyConfigs`

以下代码示例演示如何使用 `ListProvisionedConcurrencyConfigs`。

------
#### [ CLI ]

**Amazon CLI**  
**获取预置并发配置列表**  
以下 `list-provisioned-concurrency-configs` 示例列出了指定函数的预置并发配置。  

```
aws lambda list-provisioned-concurrency-configs \
    --function-name my-function
```
输出：  

```
{
    "ProvisionedConcurrencyConfigs": [
        {
            "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:GREEN",
            "RequestedProvisionedConcurrentExecutions": 100,
            "AvailableProvisionedConcurrentExecutions": 100,
            "AllocatedProvisionedConcurrentExecutions": 100,
            "Status": "READY",
            "LastModified": "2019-12-31T20:29:00+0000"
        },
        {
            "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:BLUE",
            "RequestedProvisionedConcurrentExecutions": 100,
            "AvailableProvisionedConcurrentExecutions": 100,
            "AllocatedProvisionedConcurrentExecutions": 100,
            "Status": "READY",
            "LastModified": "2019-12-31T20:28:49+0000"
        }
    ]
}
```
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [ListProvisionedConcurrencyConfigs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/list-provisioned-concurrency-configs.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例检索了 Lambda 函数的预置并发配置列表。**  

```
Get-LMProvisionedConcurrencyConfigList -FunctionName "MylambdaFunction123"
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [ListProvisionedConcurrencyConfigs](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例检索了 Lambda 函数的预置并发配置列表。**  

```
Get-LMProvisionedConcurrencyConfigList -FunctionName "MylambdaFunction123"
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [ListProvisionedConcurrencyConfigs](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `ListTags` 与 CLI 配合使用
`ListTags`

以下代码示例演示如何使用 `ListTags`。

------
#### [ CLI ]

**Amazon CLI**  
**检索 Lambda 函数的标签列表**  
以下 `list-tags` 示例展示了附加到 `my-function` Lambda 函数的标签。  

```
aws lambda list-tags \
    --resource arn:aws:lambda:us-west-2:123456789012:function:my-function
```
输出：  

```
{
    "Tags": {
        "Category": "Web Tools",
        "Department": "Sales"
    }
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[标记 Lambda 函数](https://docs.amazonaws.cn/lambda/latest/dg/tagging.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [ListTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/list-tags.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例检索了当前在指定函数上设置的标签及其值。**  

```
Get-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction"
```
**输出**：  

```
Key        Value
---        -----
California Sacramento
Oregon     Salem
Washington Olympia
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [ListTags](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例检索了当前在指定函数上设置的标签及其值。**  

```
Get-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction"
```
**输出**：  

```
Key        Value
---        -----
California Sacramento
Oregon     Salem
Washington Olympia
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [ListTags](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `ListVersionsByFunction` 与 CLI 配合使用
`ListVersionsByFunction`

以下代码示例演示如何使用 `ListVersionsByFunction`。

------
#### [ CLI ]

**Amazon CLI**  
**检索函数的版本列表**  
以下 `list-versions-by-function` 示例展示了 `my-function` Lambda 函数的版本列表。  

```
aws lambda list-versions-by-function \
    --function-name my-function
```
输出：  

```
{
    "Versions": [
        {
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "Version": "$LATEST",
            "CodeSha256": "sU0cJ2/hOZevwV/lTxCuQqK3gDZP3i8gUoqUUVRmY6E=",
            "FunctionName": "my-function",
            "VpcConfig": {
                "SubnetIds": [],
                "VpcId": "",
                "SecurityGroupIds": []
            },
            "MemorySize": 256,
            "RevisionId": "93017fc9-59cb-41dc-901b-4845ce4bf668",
            "CodeSize": 266,
            "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:$LATEST",
            "Handler": "index.handler",
            "Role": "arn:aws:iam::123456789012:role/service-role/helloWorldPython-role-uy3l9qyq",
            "Timeout": 3,
            "LastModified": "2019-10-01T16:47:28.490+0000",
            "Runtime": "nodejs10.x",
            "Description": ""
        },
        {
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "Version": "1",
            "CodeSha256": "5tT2qgzYUHoqwR616pZ2dpkn/0J1FrzJmlKidWaaCgk=",
            "FunctionName": "my-function",
            "VpcConfig": {
                "SubnetIds": [],
                "VpcId": "",
                "SecurityGroupIds": []
            },
            "MemorySize": 256,
            "RevisionId": "949c8914-012e-4795-998c-e467121951b1",
            "CodeSize": 304,
            "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:1",
            "Handler": "index.handler",
            "Role": "arn:aws:iam::123456789012:role/service-role/helloWorldPython-role-uy3l9qyq",
            "Timeout": 3,
            "LastModified": "2019-09-26T20:28:40.438+0000",
            "Runtime": "nodejs10.x",
            "Description": "new version"
        },
        {
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "Version": "2",
            "CodeSha256": "sU0cJ2/hOZevwV/lTxCuQqK3gDZP3i8gUoqUUVRmY6E=",
            "FunctionName": "my-function",
            "VpcConfig": {
                "SubnetIds": [],
                "VpcId": "",
                "SecurityGroupIds": []
            },
            "MemorySize": 256,
            "RevisionId": "cd669f21-0f3d-4e1c-9566-948837f2e2ea",
            "CodeSize": 266,
            "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:2",
            "Handler": "index.handler",
            "Role": "arn:aws:iam::123456789012:role/service-role/helloWorldPython-role-uy3l9qyq",
            "Timeout": 3,
            "LastModified": "2019-10-01T16:47:28.490+0000",
            "Runtime": "nodejs10.x",
            "Description": "newer version"
        }
    ]
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[配置 Amazon Lambda 函数别名](https://docs.amazonaws.cn/lambda/latest/dg/aliases-intro.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [ListVersionsByFunction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/list-versions-by-function.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例返回了 Lambda 函数各个版本的版本特定配置列表。**  

```
Get-LMVersionsByFunction -FunctionName "MylambdaFunction123"
```
**输出**：  

```
FunctionName        Runtime   MemorySize Timeout CodeSize LastModified                 RoleName
------------        -------   ---------- ------- -------- ------------                 --------
MylambdaFunction123 python3.8        128     600      659 2020-01-10T03:20:56.390+0000 lambda
MylambdaFunction123 python3.8        128       5     1426 2019-12-25T09:19:02.238+0000 lambda
MylambdaFunction123 python3.8        128       5     1426 2019-12-25T09:39:36.779+0000 lambda
MylambdaFunction123 python3.8        128     600     1426 2019-12-25T09:52:59.872+0000 lambda
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [ListVersionsByFunction](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例返回了 Lambda 函数各个版本的版本特定配置列表。**  

```
Get-LMVersionsByFunction -FunctionName "MylambdaFunction123"
```
**输出**：  

```
FunctionName        Runtime   MemorySize Timeout CodeSize LastModified                 RoleName
------------        -------   ---------- ------- -------- ------------                 --------
MylambdaFunction123 python3.8        128     600      659 2020-01-10T03:20:56.390+0000 lambda
MylambdaFunction123 python3.8        128       5     1426 2019-12-25T09:19:02.238+0000 lambda
MylambdaFunction123 python3.8        128       5     1426 2019-12-25T09:39:36.779+0000 lambda
MylambdaFunction123 python3.8        128     600     1426 2019-12-25T09:52:59.872+0000 lambda
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [ListVersionsByFunction](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `PublishVersion` 与 CLI 配合使用
`PublishVersion`

以下代码示例演示如何使用 `PublishVersion`。

------
#### [ CLI ]

**Amazon CLI**  
**发布函数的新版本**  
以下 `publish-version` 示例发布了 `my-function` Lambda 函数的新版本。  

```
aws lambda publish-version \
    --function-name my-function
```
输出：  

```
{
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "CodeSha256": "dBG9m8SGdmlEjw/JYXlhhvCrAv5TxvXsbL/RMr0fT/I=",
    "FunctionName": "my-function",
    "CodeSize": 294,
    "RevisionId": "f31d3d39-cc63-4520-97d4-43cd44c94c20",
    "MemorySize": 128,
    "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:3",
    "Version": "2",
    "Role": "arn:aws:iam::123456789012:role/service-role/MyTestFunction-role-zgur6bf4",
    "Timeout": 3,
    "LastModified": "2019-09-23T18:32:33.857+0000",
    "Handler": "my-function.handler",
    "Runtime": "nodejs10.x",
    "Description": ""
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[配置 Amazon Lambda 函数别名](https://docs.amazonaws.cn/lambda/latest/dg/aliases-intro.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [PublishVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/publish-version.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例创建了 Lambda 函数代码的现有快照版本**  

```
Publish-LMVersion -FunctionName "MylambdaFunction123" -Description "Publishing Existing Snapshot of function code as a  new version through Powershell"
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [PublishVersion](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例创建了 Lambda 函数代码的现有快照版本**  

```
Publish-LMVersion -FunctionName "MylambdaFunction123" -Description "Publishing Existing Snapshot of function code as a  new version through Powershell"
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [PublishVersion](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `PutFunctionConcurrency` 与 CLI 配合使用
`PutFunctionConcurrency`

以下代码示例演示如何使用 `PutFunctionConcurrency`。

------
#### [ CLI ]

**Amazon CLI**  
**配置函数的预留并发限制**  
以下 `put-function-concurrency` 示例为 `my-function` 函数配置了 100 个预留并发执行。  

```
aws lambda put-function-concurrency \
    --function-name  my-function  \
    --reserved-concurrent-executions 100
```
输出：  

```
{
    "ReservedConcurrentExecutions": 100
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[为 Lambda 函数预留并发](https://docs.amazonaws.cn/lambda/latest/dg/per-function-concurrency.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [PutFunctionConcurrency](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/put-function-concurrency.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例将函数的并发设置作为一个整体应用。**  

```
Write-LMFunctionConcurrency -FunctionName "MylambdaFunction123" -ReservedConcurrentExecution 100
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [PutFunctionConcurrency](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例将函数的并发设置作为一个整体应用。**  

```
Write-LMFunctionConcurrency -FunctionName "MylambdaFunction123" -ReservedConcurrentExecution 100
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [PutFunctionConcurrency](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `PutProvisionedConcurrencyConfig` 与 CLI 配合使用
`PutProvisionedConcurrencyConfig`

以下代码示例演示如何使用 `PutProvisionedConcurrencyConfig`。

------
#### [ CLI ]

**Amazon CLI**  
**分配预置并发**  
以下 `put-provisioned-concurrency-config` 示例为指定函数的 `BLUE` 别名分配了 100 个预置并发。  

```
aws lambda put-provisioned-concurrency-config \
    --function-name my-function \
    --qualifier BLUE \
    --provisioned-concurrent-executions 100
```
输出：  

```
{
    "Requested ProvisionedConcurrentExecutions": 100,
    "Allocated ProvisionedConcurrentExecutions": 0,
    "Status": "IN_PROGRESS",
    "LastModified": "2019-11-21T19:32:12+0000"
}
```
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [PutProvisionedConcurrencyConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/put-provisioned-concurrency-config.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例将预置并发配置添加到了函数的别名**  

```
Write-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -ProvisionedConcurrentExecution 20 -Qualifier "NewAlias1"
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [PutProvisionedConcurrencyConfig](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例将预置并发配置添加到了函数的别名**  

```
Write-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -ProvisionedConcurrentExecution 20 -Qualifier "NewAlias1"
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [PutProvisionedConcurrencyConfig](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `RemovePermission` 与 CLI 配合使用
`RemovePermission`

以下代码示例演示如何使用 `RemovePermission`。

------
#### [ CLI ]

**Amazon CLI**  
**从现有 Lambda 函数中删除权限**  
以下 `remove-permission` 示例删除了调用名为 `my-function` 的函数的权限。  

```
aws lambda remove-permission \
    --function-name my-function \
    --statement-id sns
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[对 Amazon Lambda 使用基于资源的策略](https://docs.amazonaws.cn/lambda/latest/dg/access-control-resource-based.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [RemovePermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/remove-permission.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例删除了 Lambda 函数指定 StatementId 的函数策略。**  

```
$policy =  Get-LMPolicy -FunctionName "MylambdaFunction123" -Select Policy | ConvertFrom-Json| Select-Object -ExpandProperty Statement
Remove-LMPermission -FunctionName "MylambdaFunction123" -StatementId $policy[0].Sid
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [RemovePermission](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例删除了 Lambda 函数指定 StatementId 的函数策略。**  

```
$policy =  Get-LMPolicy -FunctionName "MylambdaFunction123" -Select Policy | ConvertFrom-Json| Select-Object -ExpandProperty Statement
Remove-LMPermission -FunctionName "MylambdaFunction123" -StatementId $policy[0].Sid
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [RemovePermission](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `TagResource` 与 CLI 配合使用
`TagResource`

以下代码示例演示如何使用 `TagResource`。

------
#### [ CLI ]

**Amazon CLI**  
**将标签添加到现有 Lambda 函数**  
以下 `tag-resource` 示例向指定的 Lambda 函数添加了键名称为 `DEPARTMENT` 和值为 `Department A` 的标签。  

```
aws lambda tag-resource \
    --resource arn:aws:lambda:us-west-2:123456789012:function:my-function \
    --tags "DEPARTMENT=Department A"
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[标记 Lambda 函数](https://docs.amazonaws.cn/lambda/latest/dg/tagging.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/tag-resource.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例将三个标签（Washington、Oregon 和 California）及其关联值添加到了由函数 ARN 标识的指定函数。**  

```
Add-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction" -Tag @{ "Washington" = "Olympia"; "Oregon" = "Salem"; "California" = "Sacramento" }
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [TagResource](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例将三个标签（Washington、Oregon 和 California）及其关联值添加到了由函数 ARN 标识的指定函数。**  

```
Add-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction" -Tag @{ "Washington" = "Olympia"; "Oregon" = "Salem"; "California" = "Sacramento" }
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [TagResource](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `UntagResource` 与 CLI 配合使用
`UntagResource`

以下代码示例演示如何使用 `UntagResource`。

------
#### [ CLI ]

**Amazon CLI**  
**从现有 Lambda 函数中删除标签**  
以下 `untag-resource` 示例从 `my-function` Lambda 函数中删除了键名称为 `DEPARTMENT` 的标签。  

```
aws lambda untag-resource \
    --resource arn:aws:lambda:us-west-2:123456789012:function:my-function \
    --tag-keys DEPARTMENT
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[标记 Lambda 函数](https://docs.amazonaws.cn/lambda/latest/dg/tagging.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/untag-resource.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例从函数中删除了提供的标签。除非指定了 -Force 开关，否则在继续操作之前，cmdlet 会提示您进行确认。调用服务一次，即可删除标签。**  

```
Remove-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction" -TagKey "Washington","Oregon","California"
```
**示例 2：本示例从函数中删除了提供的标签。除非指定了 -Force 开关，否则在继续操作之前，cmdlet 会提示您进行确认。根据提供的标签调用了一次服务。**  

```
"Washington","Oregon","California" | Remove-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction"
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [UntagResource](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例从函数中删除了提供的标签。除非指定了 -Force 开关，否则在继续操作之前，cmdlet 会提示您进行确认。调用服务一次，即可删除标签。**  

```
Remove-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction" -TagKey "Washington","Oregon","California"
```
**示例 2：本示例从函数中删除了提供的标签。除非指定了 -Force 开关，否则在继续操作之前，cmdlet 会提示您进行确认。根据提供的标签调用了一次服务。**  

```
"Washington","Oregon","California" | Remove-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction"
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [UntagResource](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `UpdateAlias` 与 CLI 配合使用
`UpdateAlias`

以下代码示例演示如何使用 `UpdateAlias`。

------
#### [ CLI ]

**Amazon CLI**  
**更新函数别名**  
以下 `update-alias` 示例会更新名为 `LIVE` 的别名，该别名指向 `my-function` Lambda 函数的版本 3。  

```
aws lambda update-alias \
    --function-name my-function \
    --function-version 3 \
    --name LIVE
```
输出：  

```
{
    "FunctionVersion": "3",
    "Name": "LIVE",
    "AliasArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:LIVE",
    "RevisionId": "594f41fb-b85f-4c20-95c7-6ca5f2a92c93",
    "Description": "alias for live version of function"
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》**中的[配置 Amazon Lambda 函数别名](https://docs.amazonaws.cn/lambda/latest/dg/aliases-intro.html)。  
+  有关 API 详细信息，请参阅《Amazon CLI 命令参考》**中的 [UpdateAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/update-alias.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例更新了现有 Lambda 函数别名的配置。RoutingConfiguration 值得到更新，将 60%（0.6）的流量转移到版本 1**  

```
Update-LMAlias -FunctionName "MylambdaFunction123" -Description " Alias for version 2" -FunctionVersion 2 -Name "newlabel1" -RoutingConfig_AdditionalVersionWeight @{Name="1";Value="0.6}
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [UpdateAlias](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例更新了现有 Lambda 函数别名的配置。RoutingConfiguration 值得到更新，将 60%（0.6）的流量转移到版本 1**  

```
Update-LMAlias -FunctionName "MylambdaFunction123" -Description " Alias for version 2" -FunctionVersion 2 -Name "newlabel1" -RoutingConfig_AdditionalVersionWeight @{Name="1";Value="0.6}
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet 参考 (V5)*》中的 [UpdateAlias](https://docs.amazonaws.cn/powershell/v5/reference)。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `UpdateFunctionCode` 与 Amazon SDK 或 CLI 配合使用
`UpdateFunctionCode`

以下代码示例演示如何使用 `UpdateFunctionCode`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_lambda_Scenario_GettingStartedFunctions_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 Amazon SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Update an existing Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the Lambda function to update.</param>
    /// <param name="bucketName">The bucket where the zip file containing
    /// the Lambda function code is stored.</param>
    /// <param name="key">The key name of the source code file.</param>
    /// <returns>Async Task.</returns>
    public async Task UpdateFunctionCodeAsync(
        string functionName,
        string bucketName,
        string key)
    {
        var functionCodeRequest = new UpdateFunctionCodeRequest
        {
            FunctionName = functionName,
            Publish = true,
            S3Bucket = bucketName,
            S3Key = key,
        };

        var response = await _lambdaService.UpdateFunctionCodeAsync(functionCodeRequest);
        Console.WriteLine($"The Function was last modified at {response.LastModified}.");
    }
```
+  有关 API 详细信息，请参阅《适用于 .NET 的 Amazon SDK API Reference》**中的 [UpdateFunctionCode](https://docs.amazonaws.cn/goto/DotNetSDKV3/lambda-2015-03-31/UpdateFunctionCode)。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::UpdateFunctionCodeRequest request;
        request.SetFunctionName(LAMBDA_NAME);
        std::ifstream ifstream(CALCULATOR_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
            deleteLambdaFunction(client);
            deleteIamRole(clientConfig);
            return false;
        }

        Aws::StringStream buffer;
        buffer << ifstream.rdbuf();
        request.SetZipFile(
                Aws::Utils::ByteBuffer((unsigned char *) buffer.str().c_str(),
                                       buffer.str().length()));
        request.SetPublish(true);

        Aws::Lambda::Model::UpdateFunctionCodeOutcome outcome = client.UpdateFunctionCode(
                request);

        if (outcome.IsSuccess()) {
            std::cout << "The lambda code was successfully updated." << std::endl;
        }
        else {
            std::cerr << "Error with Lambda::UpdateFunctionCode. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
```
+  有关 API 详细信息，请参阅《适用于 C\$1\$1 的 Amazon SDK API Reference》**中的 [UpdateFunctionCode](https://docs.amazonaws.cn/goto/SdkForCpp/lambda-2015-03-31/UpdateFunctionCode)。

------
#### [ CLI ]

**Amazon CLI**  
**更新 Lambda 函数代码**  
以下 `update-function-code` 示例将 `my-function` 函数的未发布（\$1LATEST）版本的代码替换为指定 zip 文件的内容。  

```
aws lambda update-function-code \
    --function-name  my-function \
    --zip-file fileb://my-function.zip
```
输出：  

```
{
    "FunctionName": "my-function",
    "LastModified": "2019-09-26T20:28:40.438+0000",
    "RevisionId": "e52502d4-9320-4688-9cd6-152a6ab7490d",
    "MemorySize": 256,
    "Version": "$LATEST",
    "Role": "arn:aws:iam::123456789012:role/service-role/my-function-role-uy3l9qyq",
    "Timeout": 3,
    "Runtime": "nodejs10.x",
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "CodeSha256": "5tT2qgzYUHaqwR716pZ2dpkn/0J1FrzJmlKidWoaCgk=",
    "Description": "",
    "VpcConfig": {
        "SubnetIds": [],
        "VpcId": "",
        "SecurityGroupIds": []
    },
    "CodeSize": 304,
    "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
    "Handler": "index.handler"
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》中的[配置 Amazon Lambda 函数选项](https://docs.amazonaws.cn/lambda/latest/dg/resource-model.html)。**  
+  有关 API 详细信息，请参阅《Amazon CLI Command Reference》**中的 [UpdateFunctionCode](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/update-function-code.html)。

------
#### [ Go ]

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// 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
}



// UpdateFunctionCode updates the code for the Lambda function specified by functionName.
// The existing code for the Lambda function is entirely replaced by the code in the
// zipPackage buffer. After the update action is called, a lambda.FunctionUpdatedV2Waiter
// is used to wait until the update is successful.
func (wrapper FunctionWrapper) UpdateFunctionCode(ctx context.Context, functionName string, zipPackage *bytes.Buffer) types.State {
	var state types.State
	_, err := wrapper.LambdaClient.UpdateFunctionCode(ctx, &lambda.UpdateFunctionCodeInput{
		FunctionName: aws.String(functionName), ZipFile: zipPackage.Bytes(),
	})
	if err != nil {
		log.Panicf("Couldn't update code for function %v. Here's why: %v\n", functionName, err)
	} else {
		waiter := lambda.NewFunctionUpdatedV2Waiter(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 详细信息，请参阅《适用于 Go 的 Amazon SDK API Reference》**中的 [UpdateFunctionCode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.UpdateFunctionCode)。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Updates the code for an AWS Lambda function.
     *
     * @param awsLambda  the AWS Lambda client
     * @param functionName the name of the Lambda function to update
     * @param bucketName the name of the S3 bucket where the function code is located
     * @param key the key (file name) of the function code in the S3 bucket
     * @throws LambdaException if there is an error updating the function code
     */
    public static void updateFunctionCode(LambdaClient awsLambda, String functionName, String bucketName, String key) {
        try {
            LambdaWaiter waiter = awsLambda.waiter();
            UpdateFunctionCodeRequest functionCodeRequest = UpdateFunctionCodeRequest.builder()
                .functionName(functionName)
                .publish(true)
                .s3Bucket(bucketName)
                .s3Key(key)
                .build();

            UpdateFunctionCodeResponse response = awsLambda.updateFunctionCode(functionCodeRequest);
            GetFunctionConfigurationRequest getFunctionConfigRequest = GetFunctionConfigurationRequest.builder()
                .functionName(functionName)
                .build();

            WaiterResponse<GetFunctionConfigurationResponse> waiterResponse = waiter
                .waitUntilFunctionUpdated(getFunctionConfigRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("The last modified value is " + response.lastModified());

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Java 2.x API Reference》**中的 [UpdateFunctionCode](https://docs.amazonaws.cn/goto/SdkForJavaV2/lambda-2015-03-31/UpdateFunctionCode)。

------
#### [ JavaScript ]

**适用于 JavaScript 的 SDK（v3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
const updateFunctionCode = async (funcName, newFunc) => {
  const client = new LambdaClient({});
  const code = await readFile(`${dirname}../functions/${newFunc}.zip`);
  const command = new UpdateFunctionCodeCommand({
    ZipFile: code,
    FunctionName: funcName,
    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 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [UpdateFunctionCode](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/lambda/command/UpdateFunctionCodeCommand)。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function updateFunctionCode($functionName, $s3Bucket, $s3Key)
    {
        return $this->lambdaClient->updateFunctionCode([
            'FunctionName' => $functionName,
            'S3Bucket' => $s3Bucket,
            'S3Key' => $s3Key,
        ]);
    }
```
+  有关 API 详细信息，请参阅《适用于 PHP 的 Amazon SDK API Reference》**中的 [UpdateFunctionCode](https://docs.amazonaws.cn/goto/SdkForPHPV3/lambda-2015-03-31/UpdateFunctionCode)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例使用指定 zip 文件中包含的新内容来更新名为“MyFunction”的函数。对于 C\$1 .NET 核心 Lambda 函数，zip 文件应包含编译后的程序集。**  

```
Update-LMFunctionCode -FunctionName MyFunction -ZipFilename .\UpdatedCode.zip
```
**示例 2：本示例与前例类似，但使用包含了已更新代码的 Amazon S3 对象来更新函数。**  

```
Update-LMFunctionCode -FunctionName MyFunction -BucketName amzn-s3-demo-bucket -Key UpdatedCode.zip
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [UpdateFunctionCode](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例使用指定 zip 文件中包含的新内容来更新名为“MyFunction”的函数。对于 C\$1 .NET 核心 Lambda 函数，zip 文件应包含编译后的程序集。**  

```
Update-LMFunctionCode -FunctionName MyFunction -ZipFilename .\UpdatedCode.zip
```
**示例 2：本示例与前例类似，但使用包含了已更新代码的 Amazon S3 对象来更新函数。**  

```
Update-LMFunctionCode -FunctionName MyFunction -BucketName amzn-s3-demo-bucket -Key UpdatedCode.zip
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V5)*》中的 [UpdateFunctionCode](https://docs.amazonaws.cn/powershell/v5/reference)。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    def update_function_code(self, function_name, deployment_package):
        """
        Updates the code for a Lambda function by submitting a .zip archive that contains
        the code for the function.

        :param function_name: The name of the function to update.
        :param deployment_package: The function code to update, packaged as bytes in
                                   .zip format.
        :return: Data about the update, including the status.
        """
        try:
            response = self.lambda_client.update_function_code(
                FunctionName=function_name, ZipFile=deployment_package
            )
        except ClientError as err:
            logger.error(
                "Couldn't update function %s. Here's why: %s: %s",
                function_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  有关 API 详细信息，请参阅《Amazon SDK for Python (Boto3) API Reference》**中的 [UpdateFunctionCode](https://docs.amazonaws.cn/goto/boto3/lambda-2015-03-31/UpdateFunctionCode)。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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

  # Updates the code for a Lambda function by submitting a .zip archive that contains
  # the code for the function.
  #
  # @param function_name: The name of the function to update.
  # @param deployment_package: The function code to update, packaged as bytes in
  #                            .zip format.
  # @return: Data about the update, including the status.
  def update_function_code(function_name, deployment_package)
    @lambda_client.update_function_code(
      function_name: function_name,
      zip_file: deployment_package
    )
    @lambda_client.wait_until(:function_updated_v2, { function_name: function_name }) do |w|
      w.max_attempts = 5
      w.delay = 5
    end
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error updating function code for: #{function_name}:\n #{e.message}")
    nil
  rescue Aws::Waiters::Errors::WaiterFailed => e
    @logger.error("Failed waiting for #{function_name} to update:\n #{e.message}")
  end
```
+  有关 API 详细信息，请参阅《适用于 Ruby 的 Amazon SDK API Reference》**中的 [UpdateFunctionCode](https://docs.amazonaws.cn/goto/SdkForRubyV3/lambda-2015-03-31/UpdateFunctionCode)。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /** Given a Path to a zip file, update the function's code and wait for the update to finish. */
    pub async fn update_function_code(
        &self,
        zip_file: PathBuf,
        key: String,
    ) -> Result<UpdateFunctionCodeOutput, anyhow::Error> {
        let function_code = self.prepare_function(zip_file, Some(key)).await?;

        info!("Updating code for {}", self.lambda_name);
        let update = self
            .lambda_client
            .update_function_code()
            .function_name(self.lambda_name.clone())
            .s3_bucket(self.bucket.clone())
            .s3_key(function_code.s3_key().unwrap().to_string())
            .send()
            .await
            .map_err(anyhow::Error::from)?;

        self.wait_for_function_ready().await?;

        Ok(update)
    }

    /**
     * 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 详细信息，请参阅《Amazon SDK for Rust API Reference》**中的 [UpdateFunctionCode](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.update_function_code)。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        oo_result = lo_lmd->updatefunctioncode(     " oo_result is returned for testing purposes. "
              iv_functionname = iv_function_name
              iv_zipfile = io_zip_file ).

        MESSAGE 'Lambda function code updated.' 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 的 Amazon SDK 的 API 参考*中的 [UpdateFunctionCode](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

------
#### [ Swift ]

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import AWSClientRuntime
import AWSLambda
import Foundation

        let zipUrl = URL(fileURLWithPath: path)
        let zipData: Data

        // Read the function's Zip file.

        do {
            zipData = try Data(contentsOf: zipUrl)
        } catch {
            throw ExampleError.zipFileReadError
        }

        // Update the function's code and wait for the updated version to be
        // ready for use.

        do {
            _ = try await lambdaClient.updateFunctionCode(
                input: UpdateFunctionCodeInput(
                    functionName: functionName,
                    zipFile: zipData
                )
            )
        } catch {
            return false
        }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Swift API Reference》**中的 [UpdateFunctionCode](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/updatefunctioncode(input:))。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `UpdateFunctionConfiguration` 与 Amazon SDK 或 CLI 配合使用
`UpdateFunctionConfiguration`

以下代码示例演示如何使用 `UpdateFunctionConfiguration`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_lambda_Scenario_GettingStartedFunctions_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 Amazon SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Update the code of a Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the function to update.</param>
    /// <param name="functionHandler">The code that performs the function's actions.</param>
    /// <param name="environmentVariables">A dictionary of environment variables.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> UpdateFunctionConfigurationAsync(
        string functionName,
        string functionHandler,
        Dictionary<string, string> environmentVariables)
    {
        var request = new UpdateFunctionConfigurationRequest
        {
            Handler = functionHandler,
            FunctionName = functionName,
            Environment = new Amazon.Lambda.Model.Environment { Variables = environmentVariables },
        };

        var response = await _lambdaService.UpdateFunctionConfigurationAsync(request);

        Console.WriteLine(response.LastModified);

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  有关 API 详细信息，请参阅《适用于 .NET 的 Amazon SDK API Reference》**中的 [UpdateFunctionConfiguration](https://docs.amazonaws.cn/goto/DotNetSDKV3/lambda-2015-03-31/UpdateFunctionConfiguration)。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::UpdateFunctionConfigurationRequest request;
        request.SetFunctionName(LAMBDA_NAME);
        Aws::Lambda::Model::Environment environment;
        environment.AddVariables("LOG_LEVEL", "DEBUG");
        request.SetEnvironment(environment);

        Aws::Lambda::Model::UpdateFunctionConfigurationOutcome outcome = client.UpdateFunctionConfiguration(
                request);

        if (outcome.IsSuccess()) {
            std::cout << "The lambda configuration was successfully updated."
                      << std::endl;
            break;
        }

        else {
            std::cerr << "Error with Lambda::UpdateFunctionConfiguration. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
```
+  有关 API 详细信息，请参阅《适用于 C\$1\$1 的 Amazon SDK API Reference》**中的 [UpdateFunctionConfiguration](https://docs.amazonaws.cn/goto/SdkForCpp/lambda-2015-03-31/UpdateFunctionConfiguration)。

------
#### [ CLI ]

**Amazon CLI**  
**修改函数的配置**  
以下 `update-function-configuration` 示例将 `my-function` 函数的未发布（\$1LATEST）版本的内存大小修改为 256 MB。  

```
aws lambda update-function-configuration \
    --function-name  my-function \
    --memory-size 256
```
输出：  

```
{
    "FunctionName": "my-function",
    "LastModified": "2019-09-26T20:28:40.438+0000",
    "RevisionId": "e52502d4-9320-4688-9cd6-152a6ab7490d",
    "MemorySize": 256,
    "Version": "$LATEST",
    "Role": "arn:aws:iam::123456789012:role/service-role/my-function-role-uy3l9qyq",
    "Timeout": 3,
    "Runtime": "nodejs10.x",
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "CodeSha256": "5tT2qgzYUHaqwR716pZ2dpkn/0J1FrzJmlKidWoaCgk=",
    "Description": "",
    "VpcConfig": {
        "SubnetIds": [],
        "VpcId": "",
        "SecurityGroupIds": []
    },
    "CodeSize": 304,
    "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
    "Handler": "index.handler"
}
```
有关更多信息，请参阅《Amazon Lambda 开发人员指南》中的[配置 Amazon Lambda 函数选项](https://docs.amazonaws.cn/lambda/latest/dg/resource-model.html)。**  
+  有关 API 详细信息，请参阅《Amazon CLI Command Reference》**中的 [UpdateFunctionConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/update-function-configuration.html)。

------
#### [ Go ]

**适用于 Go 的 SDK V2**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// 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
}



// UpdateFunctionConfiguration updates a map of environment variables configured for
// the Lambda function specified by functionName.
func (wrapper FunctionWrapper) UpdateFunctionConfiguration(ctx context.Context, functionName string, envVars map[string]string) {
	_, err := wrapper.LambdaClient.UpdateFunctionConfiguration(ctx, &lambda.UpdateFunctionConfigurationInput{
		FunctionName: aws.String(functionName),
		Environment:  &types.Environment{Variables: envVars},
	})
	if err != nil {
		log.Panicf("Couldn't update configuration for %v. Here's why: %v", functionName, err)
	}
}
```
+  有关 API 详细信息，请参阅《适用于 Go 的 Amazon SDK API Reference》**中的 [UpdateFunctionConfiguration](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.UpdateFunctionConfiguration)。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Updates the configuration of an AWS Lambda function.
     *
     * @param awsLambda     the {@link LambdaClient} instance to use for the AWS Lambda operation
     * @param functionName  the name of the AWS Lambda function to update
     * @param handler       the new handler for the AWS Lambda function
     *
     * @throws LambdaException if there is an error while updating the function configuration
     */
    public static void updateFunctionConfiguration(LambdaClient awsLambda, String functionName, String handler) {
        try {
            UpdateFunctionConfigurationRequest configurationRequest = UpdateFunctionConfigurationRequest.builder()
                .functionName(functionName)
                .handler(handler)
                .runtime(Runtime.JAVA17)
                .build();

            awsLambda.updateFunctionConfiguration(configurationRequest);

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Java 2.x API Reference》**中的 [UpdateFunctionConfiguration](https://docs.amazonaws.cn/goto/SdkForJavaV2/lambda-2015-03-31/UpdateFunctionConfiguration)。

------
#### [ JavaScript ]

**适用于 JavaScript 的 SDK（v3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
const updateFunctionConfiguration = (funcName) => {
  const client = new LambdaClient({});
  const config = readFileSync(`${dirname}../functions/config.json`).toString();
  const command = new UpdateFunctionConfigurationCommand({
    ...JSON.parse(config),
    FunctionName: funcName,
  });
  const result = client.send(command);
  waitForFunctionUpdated({ FunctionName: funcName });
  return result;
};
```
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 Amazon SDK API Reference》**中的 [UpdateFunctionConfiguration](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/lambda/command/UpdateFunctionConfigurationCommand)。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function updateFunctionConfiguration($functionName, $handler, $environment = '')
    {
        return $this->lambdaClient->updateFunctionConfiguration([
            'FunctionName' => $functionName,
            'Handler' => "$handler.lambda_handler",
            'Environment' => $environment,
        ]);
    }
```
+  有关 API 详细信息，请参阅《适用于 PHP 的 Amazon SDK API Reference》**中的 [UpdateFunctionConfiguration](https://docs.amazonaws.cn/goto/SdkForPHPV3/lambda-2015-03-31/UpdateFunctionConfiguration)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**示例 1：本示例更新了现有 Lambda 函数配置**  

```
Update-LMFunctionConfiguration -FunctionName "MylambdaFunction123" -Handler "lambda_function.launch_instance" -Timeout 600 -Environment_Variable @{ "envvar1"="value";"envvar2"="value" } -Role arn:aws:iam::123456789101:role/service-role/lambda -DeadLetterConfig_TargetArn arn:aws:sns:us-east-1: 123456789101:MyfirstTopic
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V4)*》中的 [UpdateFunctionConfiguration](https://docs.amazonaws.cn/powershell/v4/reference)。

**适用于 PowerShell V5 的工具**  
**示例 1：本示例更新了现有 Lambda 函数配置**  

```
Update-LMFunctionConfiguration -FunctionName "MylambdaFunction123" -Handler "lambda_function.launch_instance" -Timeout 600 -Environment_Variable @{ "envvar1"="value";"envvar2"="value" } -Role arn:aws:iam::123456789101:role/service-role/lambda -DeadLetterConfig_TargetArn arn:aws:sns:us-east-1: 123456789101:MyfirstTopic
```
+  有关 API 详细信息，请参阅《*Amazon Tools for PowerShell Cmdlet Reference (V5)*》中的 [UpdateFunctionConfiguration](https://docs.amazonaws.cn/powershell/v5/reference)。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    def update_function_configuration(self, function_name, env_vars):
        """
        Updates the environment variables for a Lambda function.

        :param function_name: The name of the function to update.
        :param env_vars: A dict of environment variables to update.
        :return: Data about the update, including the status.
        """
        try:
            response = self.lambda_client.update_function_configuration(
                FunctionName=function_name, Environment={"Variables": env_vars}
            )
        except ClientError as err:
            logger.error(
                "Couldn't update function configuration %s. Here's why: %s: %s",
                function_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  有关 API 详细信息，请参阅《Amazon SDK for Python (Boto3) API Reference》**中的 [UpdateFunctionConfiguration](https://docs.amazonaws.cn/goto/boto3/lambda-2015-03-31/UpdateFunctionConfiguration)。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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

  # Updates the environment variables for a Lambda function.
  # @param function_name: The name of the function to update.
  # @param log_level: The log level of the function.
  # @return: Data about the update, including the status.
  def update_function_configuration(function_name, log_level)
    @lambda_client.update_function_configuration({
                                                   function_name: function_name,
                                                   environment: {
                                                     variables: {
                                                       'LOG_LEVEL' => log_level
                                                     }
                                                   }
                                                 })
    @lambda_client.wait_until(:function_updated_v2, { function_name: function_name }) do |w|
      w.max_attempts = 5
      w.delay = 5
    end
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error updating configurations for #{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 详细信息，请参阅《适用于 Ruby 的 Amazon SDK API Reference》**中的 [UpdateFunctionConfiguration](https://docs.amazonaws.cn/goto/SdkForRubyV3/lambda-2015-03-31/UpdateFunctionConfiguration)。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /** Update the environment for a function. */
    pub async fn update_function_configuration(
        &self,
        environment: Environment,
    ) -> Result<UpdateFunctionConfigurationOutput, anyhow::Error> {
        info!(
            ?environment,
            "Updating environment for {}", self.lambda_name
        );
        let updated = self
            .lambda_client
            .update_function_configuration()
            .function_name(self.lambda_name.clone())
            .environment(environment)
            .send()
            .await
            .map_err(anyhow::Error::from)?;

        self.wait_for_function_ready().await?;

        Ok(updated)
    }
```
+  有关 API 详细信息，请参阅《Amazon SDK for Rust API Reference》**中的 [UpdateFunctionConfiguration](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.update_function_configuration)。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        oo_result = lo_lmd->updatefunctionconfiguration(     " oo_result is returned for testing purposes. "
              iv_functionname = iv_function_name
              iv_runtime = iv_runtime
              iv_description  = 'Updated Lambda function'
              iv_memorysize  = iv_memory_size ).

        MESSAGE 'Lambda function configuration/settings updated.' TYPE 'I'.
      CATCH /aws1/cx_lmdcodesigningcfgno00.
        MESSAGE 'Code signing configuration does not exist.' 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 的 Amazon SDK 的 API 参考*中的 [UpdateFunctionConfiguration](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)。

------
#### [ Swift ]

**适用于 Swift 的 SDK**  
 查看 GitHub，了解更多信息。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import AWSClientRuntime
import AWSLambda
import Foundation

    /// Tell the server-side component to log debug output by setting its
    /// environment's `LOG_LEVEL` to `DEBUG`.
    ///
    /// - Parameters:
    ///   - lambdaClient: The `LambdaClient` to use.
    ///   - functionName: The name of the AWS Lambda function to enable debug
    ///     logging for.
    ///
    /// - Throws: `ExampleError.environmentResponseMissingError`,
    ///   `ExampleError.updateFunctionConfigurationError`,
    ///   `ExampleError.environmentVariablesMissingError`,
    ///   `ExampleError.logLevelIncorrectError`,
    ///   `ExampleError.updateFunctionConfigurationError`
    func enableDebugLogging(lambdaClient: LambdaClient, functionName: String) async throws {
        let envVariables = [
            "LOG_LEVEL": "DEBUG"
        ]
        let environment = LambdaClientTypes.Environment(variables: envVariables)

        do {
            let output = try await lambdaClient.updateFunctionConfiguration(
                input: UpdateFunctionConfigurationInput(
                    environment: environment,
                    functionName: functionName
                )
            )

            guard let response = output.environment else {
                throw ExampleError.environmentResponseMissingError
            }

            if response.error != nil {
                throw ExampleError.updateFunctionConfigurationError
            }

            guard let retVariables = response.variables else {
                throw ExampleError.environmentVariablesMissingError
            }

            for envVar in retVariables {
                if envVar.key == "LOG_LEVEL" && envVar.value != "DEBUG" {
                    print("*** Log level is not set to DEBUG!")
                    throw ExampleError.logLevelIncorrectError
                }
            }
        } catch {
            throw ExampleError.updateFunctionConfigurationError
        }
    }
```
+  有关 API 详细信息，请参阅*《Amazon SDK for Swift API Reference》*中的 [UpdateFunctionConfiguration](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/updatefunctionconfiguration(input:))。

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 Lambda 与 Amazon SDK 配合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。