简体   繁体   English

在 python 中的 AWS Lambda 函数中获取环境名称

[英]Get environment name in AWS Lambda function in python

I want to get the environment name (dev/qa/prod) where my AWS Lambda function is running or being executed programatically.我想获取运行我的 AWS Lambda 函数或以编程方式执行的环境名称 (dev/qa/prod)。 I don't want to give as part of my environment variables.我不想作为环境变量的一部分提供。 How do we do that?我们怎么做?

In AWS, everything is in "Production".在 AWS 中,一切都在“生产”中。 That is, there is no concept of "AWS for Dev" or "AWS for QA".也就是说,没有“AWS for Dev”或“AWS for QA”的概念。

It is up to you to create resources that you declare to be Dev, QA or Production.来创建您声明为开发、质量保证或生产的资源。 Some people do this in different AWS Accounts, or at least use different VPCs for each environment.有些人在不同的 AWS 账户中这样做,或者至少为每个环境使用不同的 VPC。

Fortunately, you mention that "each environment in AWS has a different role" .幸运的是,您提到“AWS 中的每个环境都有不同的角色”

This means that the AWS Lambda function can call get_caller_identity() to obtain "details about the IAM user or role whose credentials are used to call the operation":这意味着 AWS Lambda 函数可以调用get_caller_identity()来获取“有关其凭证用于调用操作的 IAM 用户或角色的详细信息”:

import boto3

def lambda_handler(event, context):
    
    sts_client = boto3.client('sts')
    print(sts_client.get_caller_identity())

It returns:它返回:

{
    "UserId": "AROAJK7HIAAAAAJYPQN7E:My-Function",
    "Account": "111111111111",
    "Arn": "arn:aws:sts: : 111111111111:assumed-role/my-role/My-Function",
    ...
    }
}

Thus, you could extract the name of the Role being used from the Arn .因此,您可以从Arn提取正在使用的角色的名称

Your lambda function can do one of the following :您的 lambda 函数可以执行以下操作之一:

  1. def handler_name(event, context): - read the data from the event dict. def handler_name(event, context): - 从event字典中读取数据。 The caller will have to add this argument (since I dont know what is the lambda trigger I cant tell if it is a good solution)调用者将不得不添加这个参数(因为我不知道什么是 lambda 触发器,我无法判断它是否是一个好的解决方案)
  2. Read the data from S3 (or other storage like DB)从 S3(或其他存储,如 DB)读取数据
  3. Read the data from AWS Systems Manager Parameter Store从 AWS Systems Manager Parameter Store 读取数据

I don't want to give as part of my environment variables我不想作为我的环境变量的一部分

Why?为什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM