【发布时间】:2021-10-18 04:14:14
【问题描述】:
我正在尝试使用 lambda 函数 Python 3.7 使用一个入站规则更新 AWS 安全组。例如:我想在现有安全组中添加具有 8443 端口的公共 IP。我已经按照下面的链接来实现了。
Modifying ec2 security group using lambda function
当我在 Python 3.7 的 Lambda 函数上使用此代码时,它不起作用。
import boto3
import hashlib
import json
import copy
import urllib2
# ID of the security group we want to update
SECURITY_GROUP_ID = "sg-XXXX"
# Description of the security rule we want to replace
SECURITY_RULE_DESCR = "My Home IP"
def lambda_handler(event, context):
new_ip_address = list(event.values())[0]
result = update_security_group(new_ip_address)
return result
def update_security_group(new_ip_address):
client = boto3.client('ec2')
response = client.describe_security_groups(GroupIds=[SECURITY_GROUP_ID])
group = response['SecurityGroups'][0]
for permission in group['IpPermissions']:
new_permission = copy.deepcopy(permission)
ip_ranges = new_permission['IpRanges']
for ip_range in ip_ranges:
if ip_range['Description'] == 'My Home IP':
ip_range['CidrIp'] = "%s/32" % new_ip_address
client.revoke_security_group_ingress(GroupId=group['GroupId'], IpPermissions=
[permission])
client.authorize_security_group_ingress(GroupId=group['GroupId'], IpPermissions=
[new_permission])
return ""
当我在 lambda 函数上测试此代码时,我得到了 "" 的响应。
【问题讨论】:
-
那么,如何在 lambda 上使用这段代码?
-
我刚刚点击了这个链接。 griggheo.medium.com/…。我不能在 Lambda 函数上使用此代码吗?如果我错了,你能纠正我吗?
-
不就是你的
return ""语句缩进不正确吗? -
是的。不正确的缩进。现在它正在运行。但未添加入站规则。你能检查一下这个python代码吗?
-
我的问题错了吗?没有人回答我的问题。我错了吗?
标签: python python-3.x amazon-web-services aws-lambda