【问题标题】:How to read SSM Parameter dynamically from Lambda Environment variable如何从 Lambda 环境变量中动态读取 SSM 参数
【发布时间】:2022-01-23 17:56:57
【问题描述】:

我将应用程序端点保存在 SSM 参数存储中,并且能够从 Lambda 环境访问。

Resources:
M4IAcarsScheduler:
Type: AWS::Serverless::Function
Properties:
Handler: not.used.in.provided.runtime
Runtime: provided
CodeUri: target/function.zip
MemorySize: 512
Timeout: 900
FunctionName: Sample
Environment:
Variables:
SamplePath: !Ref sample1path
SampleId: !Ref sample1pathid



Parameters:
sample1path:
Type: AWS::SSM::Parameter::Value<String>
Description: Select existing security group for lambda function from Parameter Store
Default: /sample/path
sample1pathid:
Type: AWS::SSM::Parameter::Value<String>
Description: Select existing security group for lambda function from Parameter Store
Default: /sample/id

我的问题是在我更新 SSM 参数 Lambda Env 时。不是动态更新的,每次都需要重启。

有什么方法可以动态处理它,这意味着当它在 SSM 参数存储中发生变化时,它会在不重新启动 Lambda 的情况下反映?

【问题讨论】:

    标签: amazon-web-services aws-lambda aws-ssm


    【解决方案1】:

    通过在 CloudFormation 堆栈中使用 SSM 参数,可以在部署 CloudFormation 堆栈时解析参数。如果 SSM 中的值随后发生更改,则不会更新 lambda,因此 lambda 仍将具有部署 CloudFormation 堆栈时从 SSM 中提取的值。 lambda 甚至不知道参数来自 SSM;相反,它只会知道配置了静态环境变量。

    相反,要在您的 lambda 中使用 SSM 参数,您应该更改您的 lambda 代码,以便它从代码中获取参数This AWS blog 展示了一个 Python lambda 示例,说明如何从 lambda 代码中获取参数(当 lambda 运行时):

    import os, traceback, json, configparser, boto3
    from aws_xray_sdk.core import patch_all
    patch_all()
    
    # Initialize boto3 client at global scope for connection reuse
    client = boto3.client('ssm')
    env = os.environ['ENV']
    app_config_path = os.environ['APP_CONFIG_PATH']
    full_config_path = '/' + env + '/' + app_config_path
    # Initialize app at global scope for reuse across invocations
    app = None
    
    class MyApp:
        def __init__(self, config):
            """
            Construct new MyApp with configuration
            :param config: application configuration
            """
            self.config = config
    
        def get_config(self):
            return self.config
    
    def load_config(ssm_parameter_path):
        """
        Load configparser from config stored in SSM Parameter Store
        :param ssm_parameter_path: Path to app config in SSM Parameter Store
        :return: ConfigParser holding loaded config
        """
        configuration = configparser.ConfigParser()
        try:
            # Get all parameters for this app
            param_details = client.get_parameters_by_path(
                Path=ssm_parameter_path,
                Recursive=False,
                WithDecryption=True
            )
    
            # Loop through the returned parameters and populate the ConfigParser
            if 'Parameters' in param_details and len(param_details.get('Parameters')) > 0:
                for param in param_details.get('Parameters'):
                    param_path_array = param.get('Name').split("/")
                    section_position = len(param_path_array) - 1
                    section_name = param_path_array[section_position]
                    config_values = json.loads(param.get('Value'))
                    config_dict = {section_name: config_values}
                    print("Found configuration: " + str(config_dict))
                    configuration.read_dict(config_dict)
    
        except:
            print("Encountered an error loading config from SSM.")
            traceback.print_exc()
        finally:
            return configuration
    
    def lambda_handler(event, context):
        global app
        # Initialize app if it doesn't yet exist
        if app is None:
            print("Loading config and creating new MyApp...")
            config = load_config(full_config_path)
            app = MyApp(config)
    
        return "MyApp config is " + str(app.get_config()._sections)
    

    这里是a post 的 Node 示例,其他语言也有类似的示例。

    // parameter expected by SSM.getParameter
    var parameter = {
        "Name" : "/systems/"+event.Name+"/config"
    };
    responseFromSSM = await SSM.getParameter(parameter).promise();
    console.log('SUCCESS');
    console.log(responseFromSSM);
    var value = responseFromSSM.Parameter.Value;
    

    【讨论】:

      猜你喜欢
      • 2021-05-09
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 2018-07-07
      • 2012-09-05
      相关资源
      最近更新 更多