`UpdateFunctionConfiguration`을 AWS SDK 또는 CLI로 사용
UpdateFunctionConfiguration을 AWS SDK 또는 CLI로 사용
다음 코드 예제는 UpdateFunctionConfiguration 사용 방법을 보여줘요.
액션 예제는 더 큰 프로그램의 코드 발췌본으로 컨텍스트 안에서 실행해야 해요. 이 액션을 다음 코드 예제에서 컨텍스트로 볼 수 있어요:
본문
[ .NET ]
SDK for .NET
GitHub에서 더 많은 내용을 볼 수 있어요. AWS Code Examples Repository에서 전체 예제를 찾고 설정·실행 방법을 배워 보세요.
/// <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 세부 정보는 AWS SDK for .NET API Reference의 UpdateFunctionConfiguration을 참고하세요.
[ C++ ]
SDK for C++
GitHub에서 더 많은 내용을 볼 수 있어요. AWS Code Examples Repository에서 전체 예제를 찾고 설정·실행 방법을 배워 보세요.
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 세부 정보는 AWS SDK for C++ API Reference의 UpdateFunctionConfiguration을 참고하세요.
[ CLI ]
AWS CLI
함수의 구성 수정하기
다음 update-function-configuration 예제는 my-function 함수의 게시되지 않은($LATEST) 버전의 메모리 크기를 256MB로 수정해요.
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"
}
자세한 내용은 AWS Lambda 개발자 안내서의 AWS Lambda 함수 구성을 참고하세요.
- API 세부 정보는 AWS CLI Command Reference의 UpdateFunctionConfiguration을 참고하세요.
[ Go ]
SDK for Go V2
GitHub에서 더 많은 내용을 볼 수 있어요. AWS Code Examples Repository에서 전체 예제를 찾고 설정·실행 방법을 배워 보세요.
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 세부 정보는 AWS SDK for Go API Reference의 UpdateFunctionConfiguration을 참고하세요.
[ Java ]
SDK for Java 2.x
GitHub에서 더 많은 내용을 볼 수 있어요. AWS Code Examples Repository에서 전체 예제를 찾고 설정·실행 방법을 배워 보세요.
/**
* 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 세부 정보는 AWS SDK for Java 2.x API Reference의 UpdateFunctionConfiguration을 참고하세요.
[ JavaScript ]
SDK for JavaScript (v3)
GitHub에서 더 많은 내용을 볼 수 있어요. AWS Code Examples Repository에서 전체 예제를 찾고 설정·실행 방법을 배워 보세요.
const updateFunctionConfiguration = async (funcName) => {
const client = new LambdaClient({});
const config = readFileSync(`${dirname}../functions/config.json`).toString();
const command = new UpdateFunctionConfigurationCommand({
...JSON.parse(config),
FunctionName: funcName,
});
const result = await client.send(command);
await waitForFunctionUpdated({ FunctionName: funcName });
return result;
};
- API 세부 정보는 AWS SDK for JavaScript API Reference의 UpdateFunctionConfiguration을 참고하세요.
[ PHP ]
SDK for PHP
GitHub에서 더 많은 내용을 볼 수 있어요. AWS Code Examples Repository에서 전체 예제를 찾고 설정·실행 방법을 배워 보세요.
public function updateFunctionConfiguration($functionName, $handler, $environment = '')
{
return $this->lambdaClient->updateFunctionConfiguration([
'FunctionName' => $functionName,
'Handler' => "$handler.lambda_handler",
'Environment' => $environment,
]);
}
- API 세부 정보는 AWS SDK for PHP API Reference의 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 세부 정보는 *AWS Tools for PowerShell Cmdlet Reference (V4)*의 UpdateFunctionConfiguration을 참고하세요.
Tools for 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 세부 정보는 *AWS Tools for PowerShell Cmdlet Reference (V5)*의 UpdateFunctionConfiguration을 참고하세요.
[ Python ]
SDK for Python (Boto3)
GitHub에서 더 많은 내용을 볼 수 있어요. AWS Code Examples Repository에서 전체 예제를 찾고 설정·실행 방법을 배워 보세요.
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 세부 정보는 AWS SDK for Python (Boto3) API Reference의 UpdateFunctionConfiguration을 참고하세요.
[ Ruby ]
SDK for Ruby
GitHub에서 더 많은 내용을 볼 수 있어요. AWS Code Examples Repository에서 전체 예제를 찾고 설정·실행 방법을 배워 보세요.
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 세부 정보는 AWS SDK for Ruby API Reference의 UpdateFunctionConfiguration을 참고하세요.
[ Rust ]
SDK for Rust
GitHub에서 더 많은 내용을 볼 수 있어요. AWS Code Examples Repository에서 전체 예제를 찾고 설정·실행 방법을 배워 보세요.
/** 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 세부 정보는 AWS SDK for Rust API reference의 UpdateFunctionConfiguration을 참고하세요.
[ SAP ABAP ]
SDK for SAP ABAP
GitHub에서 더 많은 내용을 볼 수 있어요. AWS Code Examples Repository에서 전체 예제를 찾고 설정·실행 방법을 배워 보세요.
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 세부 정보는 AWS SDK for SAP ABAP API reference의 UpdateFunctionConfiguration을 참고하세요.
[ Swift ]
SDK for Swift
GitHub에서 더 많은 내용을 볼 수 있어요. AWS Code Examples Repository에서 전체 예제를 찾고 설정·실행 방법을 배워 보세요.
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 세부 정보는 AWS SDK for Swift API reference의 UpdateFunctionConfiguration을 참고하세요.
AWS SDK 개발자 안내서와 코드 예제 전체 목록은 Lambda를 AWS SDK와 함께 사용을 참고하세요. 이 주제에는 시작하기 정보와 이전 SDK 버전에 대한 세부 정보도 포함돼요.
더 알아보기 (Learn more)
- .NET·C++·CLI·Go·Java·JavaScript·PHP·PowerShell·Python·Ruby·Rust·SAP ABAP·Swift에서
UpdateFunctionConfiguration으로 Lambda 함수 구성을 수정하는 방법을 익혀 보세요.