文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
UpdateFunctionCode
搭配 a AWS SDK 或 CLI 使用
下列程式碼範例示範如何使用 UpdateFunctionCode
。
動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:
- .NET
-
- AWS SDK for .NET
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /// <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 詳細資訊,請參閱 UpdateFunctionCode AWS SDK for .NET 參考中的 API。
-
- C++
-
- C++ 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region in which the bucket was created (overrides config file). // clientConfig.region = "us-east-1"; Aws::Lambda::LambdaClient client(clientConfig); Aws::Lambda::Model::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 詳細資訊,請參閱 UpdateFunctionCode AWS SDK for C++ 參考中的 API。
-
- CLI
-
- AWS CLI
-
若要更新 Lambda 函數的程式碼
下列
update-function-code
範例會將函數未發佈 ($LATEST) 版本的程式碼取代my-function
為指定的 zip 檔案的內容。aws lambda update-function-code \ --function-name
my-function
\ --zip-filefileb://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" }
如需詳細資訊,請參閱《AWS Lambda 開發人員指南》中的 AWS Lambda 函數組態。
-
如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 UpdateFunctionCode
。
-
- Go
-
- SDK for Go V2
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 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 詳細資訊,請參閱 UpdateFunctionCode
AWS SDK for Go 參考中的 API。
-
- Java
-
- Java 2.x 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /** * 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 詳細資訊,請參閱 UpdateFunctionCode AWS SDK for Java 2.x 參考中的 API。
-
- JavaScript
-
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 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 詳細資訊,請參閱 UpdateFunctionCode AWS SDK for JavaScript 參考中的 API。
-
- PHP
-
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 public function updateFunctionCode($functionName, $s3Bucket, $s3Key) { return $this->lambdaClient->updateFunctionCode([ 'FunctionName' => $functionName, 'S3Bucket' => $s3Bucket, 'S3Key' => $s3Key, ]); }
-
如需 API 詳細資訊,請參閱 UpdateFunctionCode AWS SDK for PHP 參考中的 API。
-
- PowerShell
-
- for PowerShell 工具
-
範例 1:將名為 'MyFunction' 的函數更新為包含在指定 zip 檔案中的新內容。對於 C# .NET 壓縮檔案應包含編譯組件的核心 Lambda 函數。
Update-LMFunctionCode -FunctionName MyFunction -ZipFilename .\UpdatedCode.zip
範例 2:此範例類似於上一個範例,但使用包含更新程式碼的 Amazon S3 物件來更新函數。
Update-LMFunctionCode -FunctionName MyFunction -BucketName amzn-s3-demo-bucket -Key UpdatedCode.zip
-
如需 API 詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考中的 UpdateFunctionCode。
-
- Python
-
- SDK for Python (Boto3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 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 詳細資訊,請參閱 UpdateFunctionCode AWS SDK for Python (Boto3) Word 參考中的 API。
-
- Ruby
-
- Ruby 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 class LambdaWrapper attr_accessor :lambda_client, :cloudwatch_client, :iam_client def initialize @lambda_client = Aws::Lambda::Client.new @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1') @iam_client = Aws::IAM::Client.new(region: 'us-east-1') @logger = Logger.new($stdout) @logger.level = Logger::WARN end # 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 詳細資訊,請參閱 UpdateFunctionCode AWS SDK for Ruby 參考中的 API。
-
- Rust
-
- Rust 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /** 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 詳細資訊,請參閱 UpdateFunctionCode
AWS for Rust SDK 參考中的 API。
-
- SAP ABAP
-
- SDK for SAP ABAP
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 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 詳細資訊,請參閱 UpdateFunctionCode AWS for SDK ABAP 參考中的 SAP API。
-