我正在尝试实现一个 Lambda 脚本,该脚本将检查新创建的 s3 存储桶的加密情况。如果发现存储桶未加密,我希望 Lambda 在这些存储桶上强制使用 SSE-KMS。我正在使用以下代码:
from boto3 import resource, client
from logging import getLogger, info, error, debug
from os import environ
from botocore.exceptions import ClientError
SSEAlgorithm = "aws:kms"
KMSMasterKeyID = environ['KMSMasterKeyID']
class Enforce_EBS_Encryption(object):
def __init__(self):
self.s3_client = client('s3')
self.logger = getLogger()
self.logger.setLevel("INFO")
self.unencryptedbucket = list()
def getlistofUnEncryptedBucket(self):
response = self.s3_client.list_buckets()
for bucket in response['Buckets']:
try:
resp_encryption = self.s3_client.get_bucket_encryption(
Bucket=bucket['Name']
)
rules = resp_encryption['ServerSideEncryptionConfiguration']['Rules']
info("{0} is already encrypted : Encryption : {1}".format(bucket['Name'],rules))
except ClientError as e:
if e.response['Error']['Code'] == 'ServerSideEncryptionConfigurationNotFoundError':
info("{0} is not encrypted but will be, No Encrytion found".format(bucket['Name']))
self.unencryptedbucket.append(bucket['Name'])
else:
error("Unexpected error on Bucket: {0}".format(bucket['Name']))
def _putEncryptiononSingleBucket(self,bucket_name):
resp = self.s3_client.put_bucket_encryption(
Bucket=bucket_name,
ServerSideEncryptionConfiguration={
'Rules': [
{
'ApplyServerSideEncryptionByDefault': {
'SSEAlgorithm': SSEAlgorithm,
'KMSMasterKeyID': KMSMasterKeyID
}
},
]
}
)
def forceEncrytionOnUnEncryptedBucket(self):
for bucket in self.unencryptedbucket:
self._putEncryptiononSingleBucket(bucket)
info("The Bucket : {0} has been encrypted with KMS key".format(bucket))
def lambda_handler(event, context):
print("***** Start Processing ****")
s3_encryption = Enforce_EBS_Encryption()
s3_encryption.getlistofUnEncryptedBucket()
s3_encryption.forceEncrytionOnUnEncryptedBucket()
print("***** End Processing ****")
但是,在测试时,我收到以下错误:
{
"errorMessage": "'KMSMasterKeyID'",
"errorType": "KeyError",
"stackTrace": [
" File \"/var/lang/lib/python3.7/imp.py\", line 234, in load_module\n return load_source(name, filename, file)\n",
" File \"/var/lang/lib/python3.7/imp.py\", line 171, in load_source\n module = _load(spec)\n",
" File \"<frozen importlib._bootstrap>\", line 696, in _load\n",
" File \"<frozen importlib._bootstrap>\", line 677, in _load_unlocked\n",
" File \"<frozen importlib._bootstrap_external>\", line 728, in exec_module\n",
" File \"<frozen importlib._bootstrap>\", line 219, in _call_with_frames_removed\n",
" File \"/var/task/lambda_function.py\", line 7, in <module>\n KMSMasterKeyID = environ['KMSMasterKeyID']\n",
" File \"/var/lang/lib/python3.7/os.py\", line 681, in __getitem__\n raise KeyError(key) from None\n"
]
}
Request ID:
"1a3ceb27-f2ed-4cf9-8b89-87e593a75ac6"
Function logs:
START RequestId: 1a3ceb27-f2ed-4cf9-8b89-87e593a75ac6 Version: $LATEST
[ERROR] KeyError: 'KMSMasterKeyID'
Traceback (most recent call last):
File "/var/lang/lib/python3.7/imp.py", line 234, in load_module
return load_source(name, filename, file)
File "/var/lang/lib/python3.7/imp.py", line 171, in load_source
module = _load(spec)
File "<frozen importlib._bootstrap>", line 696, in _load
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/var/task/lambda_function.py", line 7, in <module>
KMSMasterKeyID = environ['KMSMasterKeyID']
File "/var/lang/lib/python3.7/os.py", line 681, in __getitem__
raise KeyError(key) from None
END RequestId: 1a3ceb27-f2ed-4cf9-8b89-87e593a75ac6
REPORT RequestId: 1a3ceb27-f2ed-4cf9-8b89-87e593a75ac6 Duration: 4130.89 ms Billed Duration: 4200 ms Memory Size: 128 MB Max Memory Used: 25 MB
Unknown application error occurred
如有任何建议,我们将不胜感激,谢谢!
我看到这篇文章是在大约 4 年前发布的——对任何浏览此页面的人来说: os.environ['someKey'] 将读取 lambda 的环境变量。 首先确保您的 lambda 中有一个同名的环境变量(它们区分大小写)
您可以通过导航到 Lambda => 配置 => 环境变量在控制台中查看和编辑此内容。 (但请确保也更新您的 IAC!)