Skip to content

Instantly share code, notes, and snippets.

@LouisAmon
Last active January 25, 2020 09:17
Show Gist options
  • Save LouisAmon/ea395d39d80b28eb78181831fa523456 to your computer and use it in GitHub Desktop.
Save LouisAmon/ea395d39d80b28eb78181831fa523456 to your computer and use it in GitHub Desktop.
Terraform's `filebase64sha256` function, in Python (cf. https://www.terraform.io/docs/providers/aws/r/lambda_function.html)
import base64
import hashlib
def sha256sum(filename):
"""
Helper function that calculates the hash of a file
using the SHA256 algorithm
Inspiration:
https://stackoverflow.com/a/44873382
NB: we're deliberately using `digest` instead of `hexdigest` in order to
mimic Terraform.
"""
h = hashlib.sha256()
b = bytearray(128*1024)
mv = memoryview(b)
with open(filename, 'rb', buffering=0) as f:
for n in iter(lambda : f.readinto(mv), 0):
h.update(mv[:n])
return h.digest()
def filebase64sha256(filename):
"""
Computes the Base64-encoded SHA256 hash of a file
This function mimics its Terraform counterpart, therefore being compatible
with Pulumi's provisioning engine.
"""
h = sha256sum(filename)
b = base64.b64encode(h)
return b.decode()
def lambda_function(event, context):
print('Hello World')
return {
'foo': 'bar'
}
from pulumi_aws import lambda_
from filebase64sha256 import filebase64sha256
# Assuming we have zipped the content of our Lambda as per AWS requirements
PACKAGE_PATH = './lambda.zip'
function = lambda_.Function(
resource_name='function'
code=PACKAGE_PATH,
# Use the package's hash to determine wether Lamdba needs to be updated
source_code_hash=filebase64sha256(PACKAGE_PATH),
description='Hello World',
handler='lambda_handler.lambda_function',
#layers=[layer.arn],
memory_size=128,
#role=lambda_role.arn,
runtime='python3.8',
tags={
'PROJECT': pulumi.get_project(),
'STACK': pulumi.get_stack()
},
timeout=30,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment