【问题标题】:Lambda function to store JSON attribute in DynamoDB using Boto使用 Boto 在 DynamoDB 中存储 JSON 属性的 Lambda 函数
【发布时间】:2021-04-18 08:07:25
【问题描述】:

我正在编写一个 python 脚本,它将使用 lambda 函数在 dynamodb 表中存储 JSON 属性,例如 ("region","ebs_volume_size","instance_type") 这是我的 lambda 函数,它从我的 python 函数中获取策略的输入

import boto3
import time
import json
import meta_templates
from jinja2 import Template
from template_utils import create_aws_iam_policy_template 
dynamodb = boto3.resource('dynamodb')
lambd = boto3.client('lambda')

def lambda_handler(event, context):
  template_json = create_aws_iam_policy_template(**event)
  return template_json

table =dynamodb.create_table(
    TableName='GoodTable',
    AttributeDefinitions=[
    {
      "AttributeName": "Content",
      "AttributeType": "S"
    }
    ],
      KeySchema=[
    {
      "AttributeName": "Content",
      "KeyType": "HASH"
    }
  ],
  ProvisionedThroughput={
    "ReadCapacityUnits": 1,
    "WriteCapacityUnits": 1
  }
)
time.sleep(20)
table = dynamodb.Table('GoodTable')
response = table.put_item(
    Item= {
        'Content': 'Volume Size', 
        'Details': kwargs.get('ebs_volume_size'),
    }
)
response = table.put_item(
    Item= {
        'Content': 'Instance Type', 
        'Details': kwargs.get('instance_type'),
    }
)
response = table.put_item(
    Item= {
        'Content': 'Region', 
        'Details': kwargs.get('region'),
    }
)

这是我的python函数“template_utils.py”:

   import json
    import meta_templates
    from jinja2 import Template
    
    start_time_1 = input("What's the start time")
    end_time1 = input("What's the end time")
    def create_aws_iam_policy_template(**kwargs):
      template_data = {}
      template_data["region"] = kwargs.get('region')
      template_data["start_time"] = kwargs.get('end_time')
      template_data["end_time"] = kwargs.get('start_time')
      template_data["instance_types"] = kwargs.get('instance_type')
      template_data["ebs_volume_size"] = kwargs.get('ebs_volume_size')
      template_data["meta_template_name"] = kwargs.get('meta_template_name')
    
      meta_template_dict = getattr(meta_templates, template_data["meta_template_name"])
      meta_template_json = json.dumps(meta_template_dict)
      template_json = Template(meta_template_json).render(template_data)
      return template_json  
    
    
    template_json = create_aws_iam_policy_template(
      region="us-east-2",
      instance_type="t2.micro",
      ebs_volume_size="20",
      meta_template_name="ec2_policy_meta_template",
      start_time = start_time_1,
      end_time = end_time1
    )
    
    
    print(template_json)

This is my IAM policy:
ec2_policy_meta_template = { 
        "Version": "2012-10-17",
        "Statement": [
            {
                "Sid": "VisualEditor0",
                "Effect": "Allow",
                "Action": "ec2:RunInstances",
                "Resource": [
                    "arn:aws:ec2:{{region}}::instance/*",
                    "arn:aws:ec2:{{region}}::image/ami-*"
                ],
                "Condition": {
                    "ForAllValues:NumericLessThanEquals": {
                        "ec2:VolumeSize": "{{ebs_volume_size}}"
                    },
                    "ForAllValues:StringEquals": {
                        "ec2:InstanceType": "{{instance_type}}"
                    }
                }
            },
            {
                "Sid": "VisualEditor1",
                "Effect": "Allow",
                "Action": [
                    "ec2:TerminateInstances",
                    "ec2:StopInstances"
                ],
                "Resource": "arn:aws:ec2:{{region}}::instance/*",
                "Condition": {
                    "ForAllValues:StringEquals": {
                        "ec2:InstanceType": "{{instance_type}}"
                    }
                }
            },
            {
                "Sid": "VisualEditor2",
                "Effect": "Allow",
                "Action": [
                    "ec2:Describe*",
                    "ec2:GetConsole*",
                    "ec2:CreateKeyPair"
                ],
                "Resource": "*",
                "Condition": {
                    "DateGreaterThan": {
                        "aws:CurrentTime": "{{start_time}}"
                    },
                    "DateLessThanEquals": {
                        "aws:CurrentTime": "{{end_time}}"
                    }
                }
            }
        ]
    }

我不想使用“f-strings”而只是使用 python 函数中的值,我收到一个错误“未定义的变量'kwargs'”。

【问题讨论】:

  • 您的 lambda 缩进错误。 dynamodb.create_table 永远不会运行。 ebs_volume_size 应该来自哪里?它是 lambda 函数的输入吗?
  • “ebs_volume_size”将来自“template_json”

标签: python python-3.x amazon-web-services aws-lambda boto3


【解决方案1】:

indentationkwargs 应该在以下代码的更正版本中得到修复。还要确保您在 lambda 执行角色 中提供正确的权限,以便它有权访问 dynamodb。

import boto3
import time
import json
import meta_templates
from jinja2 import Template
from template_utils import create_aws_iam_policy_template 

dynamodb = boto3.resource('dynamodb')
lambd = boto3.client('lambda')

def lambda_handler(event, context):
  template_json = create_aws_iam_policy_template(**event)
  
  table = dynamodb.create_table(
      TableName='GoodTable',
      AttributeDefinitions=[
      {
        "AttributeName": "Content",
        "AttributeType": "S"
      }
      ],
        KeySchema=[
      {
        "AttributeName": "Content",
        "KeyType": "HASH"
      }
    ],
    ProvisionedThroughput={
      "ReadCapacityUnits": 1,
      "WriteCapacityUnits": 1
    }
  )
  time.sleep(20)
  table = dynamodb.Table('GoodTable')
  response = table.put_item(
      Item= {
          'Content': 'Volume Size', 
          'Details': template_json.get('ebs_volume_size'),
      }
  )
  response = table.put_item(
      Item= {
          'Content': 'Instance Type', 
          'Details': template_json.get('instance_type'),
      }
  )
  response = table.put_item(
      Item= {
          'Content': 'Region', 
          'Details': template_json.get('region'),
      }
  )

【讨论】:

  • 我已向我的 Dynamo 授予 Lambda 权限,但即使在此之后运行 lambda 函数,我也无法创建 dynamodb 表,有什么想法可能会出错吗?
  • @PranaySinghParihar 您的函数创建了表。当您第二次调用它时,创建将失败,因为您不能有两个同名的表。
  • 在运行这个程序时是否应该至少创建一次表,我没有错误只是以dict形式输出
  • @PranaySinghParihar 它应该。检查 CloudWatch 日志是否有错误。您可以使用错误和问题的详细信息提出新问题。
猜你喜欢
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 2016-10-20
相关资源
最近更新 更多