简体   繁体   English

Python 3 AWS Lambda函数可让用户访问密钥年龄

[英]Python 3 AWS lambda function to get users access key age

I'm trying to get the access key age for each user in multiple AWS accounts. 我正在尝试获取多个AWS账户中每个用户的访问密钥年龄。 I currently have code that prints out the access key age but the code doesn't return it properly from an error. 我目前有一些打印出访问密钥使用期限的代码,但是该代码无法从错误中正确返回它。 The code I'm working with is, 我正在使用的代码是

import boto3
from time import gmtime, strftime
from datetime import datetime
sts = boto3.client('sts')

def lambda_handler(event, context):
    rolesessionname = "rolename"
    account = "123456789"
    response = sts.assume_role(
    RoleArn = "arn:aws:iam::" + str(account) + ":role/audit",
    RoleSessionName= rolesessionname
    )
  credentials = response['Credentials']
  iam = boto3.client(
   'iam',
    aws_access_key_id = credentials['AccessKeyId'], 
    aws_secret_access_key = credentials['SecretAccessKey'], 
    aws_session_token = credentials['SessionToken']
    )


    response = iam.list_users()
    nameList = []
    todaysDate = strftime("%Y-%m-%d %H:%M:%S", gmtime())
    todaysDate = str(todaysDate)
    todaysDate = todaysDate[0:10]
    todaysDate = datetime.strptime(todaysDate, "%Y-%m-%d")

    for person in response["Users"]:
        curPersonName = person["UserName"]

        keys = iam.list_access_keys(UserName=curPersonName)
        for keyData in keys["AccessKeyMetadata"]:
           keyID = keyData["AccessKeyId"]
           status = keyData["Status"]
            CreateDate = keyData.get("CreateDate","none")
            CreateDate = str(CreateDate)
            CreateDate = CreateDate[0:10]
            CreateDate = datetime.strptime(CreateDate, "%Y-%m-%d")

            totalDays =  abs((CreateDate - todaysDate).days)
            print (totalDays-1)
            nameList.append({
            "UserName:":curPersonName,
            "Status:": status,
            "Create Date": CreateDate
            #"Total days:" : totalDays-1
                })            

     return nameList

My problem is that if I comment out the mentions of 我的问题是,如果我注释掉

CreateDate = datetime.strptime(CreateDate, "%Y-%m-%d")

and

totalDays = abs((CreateDate - todaysDate).days)

I get successful build and return data, just without the age of the key which is mainly what I want. 我获得了成功的构建和返回数据,而没有关键的期限,而这正是我想要的。 However if I keep those lines in and print out to see if it's getting the age correctly it is. 但是,如果我保留这些行并打印出来,看它是否正确地达到了年龄。 However It only prints them out and then errors with. 但是,它只会打印出来,然后出现错误。

{
  "errorMessage": "datetime.datetime(2017, 1, 11, 0, 0) is not JSON serializable",
  "errorType": "TypeError",
  "stackTrace": [
    [
      "/var/lang/lib/python3.6/json/__init__.py",
      238,
      "dumps",
      "**kw).encode(obj)"
    ],
    [
      "/var/lang/lib/python3.6/json/encoder.py",
      199,
      "encode",
      "chunks = self.iterencode(o, _one_shot=True)"
    ],
    [
      "/var/lang/lib/python3.6/json/encoder.py",
      257,
      "iterencode",
      "return _iterencode(o, 0)"
    ],
    [
      "/var/runtime/awslambda/bootstrap.py",
      110,
      "decimal_serializer",
      "raise TypeError(repr(o) + \" is not JSON serializable\")"
    ]
  ]
}

You're getting this error because datetime is not JSON serializable. 您收到此错误,因为datetime不可JSON序列化。 You are saving a datetime object in CreateDate with 您正在使用以下方法将datetime对象保存在CreateDate中:

datetime.strptime(CreateDate, "%Y-%m-%d")

It seems like the answer would be to use this value to calculate your days: 似乎答案是使用此值来计算您的工作日:

totalDays =  abs((CreateDate - todaysDate).days)

and then change it to a string representation before adding it to the return object: 然后将其更改为字符串表示形式,然后再将其添加到返回对象中:

CreateDate = CreateDate.isoformat() #or whatever return format you want.

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

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