简体   繁体   中英

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. I don't want to give as part of my environment variables. How do we do that?

In AWS, everything is in "Production". That is, there is no concept of "AWS for Dev" or "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.

Fortunately, you mention that "each environment in AWS has a different role" .

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":

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 .

Your lambda function can do one of the following :

  1. def handler_name(event, context): - read the data from the event dict. 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)
  2. Read the data from S3 (or other storage like DB)
  3. Read the data from AWS Systems Manager Parameter Store

I don't want to give as part of my environment variables

Why?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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