From b5c7521f52b72493eceeb3b3be2024c559b74511 Mon Sep 17 00:00:00 2001 From: Chris Marchesi Date: Wed, 9 Dec 2015 17:42:12 -0800 Subject: [PATCH] aws_lambda_function: Force code update on SHA sum mismatch --- .../aws/resource_aws_lambda_function.go | 43 ++++++++++++++++++- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/builtin/providers/aws/resource_aws_lambda_function.go b/builtin/providers/aws/resource_aws_lambda_function.go index 8da45720e..178b0d88f 100644 --- a/builtin/providers/aws/resource_aws_lambda_function.go +++ b/builtin/providers/aws/resource_aws_lambda_function.go @@ -2,6 +2,7 @@ package aws import ( "crypto/sha256" + "encoding/base64" "fmt" "io/ioutil" "log" @@ -102,6 +103,11 @@ func resourceAwsLambdaFunction() *schema.Resource { }, }, }, + "update_code": &schema.Schema{ + Type: schema.TypeBool, + Optional: true, + Default: false, + }, "arn": &schema.Schema{ Type: schema.TypeString, Computed: true, @@ -113,7 +119,10 @@ func resourceAwsLambdaFunction() *schema.Resource { "source_code_hash": &schema.Schema{ Type: schema.TypeString, Computed: true, - ForceNew: true, + }, + "remote_code_hash": &schema.Schema{ + Type: schema.TypeString, + Computed: true, }, }, } @@ -249,6 +258,26 @@ func resourceAwsLambdaFunctionRead(d *schema.ResourceData, meta interface{}) err d.Set("vpc_config", config) } + // Compare code hashes, and see if an update is required to code. If there + // is, set the "update_code" attribute. + + remoteSum, err := decodeBase64(*function.CodeSha256) + if err != nil { + return err + } + _, localSum, err := loadLocalZipFile(d.Get("filename").(string)) + if err != nil { + return err + } + d.Set("remote_code_hash", remoteSum) + d.Set("source_code_hash", localSum) + + if remoteSum != localSum { + d.Set("update_code", true) + } else { + d.Set("update_code", false) + } + return nil } @@ -361,6 +390,7 @@ func resourceAwsLambdaFunctionUpdate(d *schema.ResourceData, meta interface{}) e return resourceAwsLambdaFunctionRead(d, meta) } +// loads the local ZIP data and the SHA sum of the data. func loadLocalZipFile(v string) ([]byte, string, error) { filename, err := homedir.Expand(v) if err != nil { @@ -371,7 +401,16 @@ func loadLocalZipFile(v string) ([]byte, string, error) { return nil, "", err } sum := sha256.Sum256(zipfile) - return zipfile, string(sum[:32]), nil + return zipfile, fmt.Sprintf("%x", sum), nil +} + +// Decodes a base64 string to a string. +func decodeBase64(s string) (string, error) { + sum, err := base64.StdEncoding.DecodeString(s) + if err != nil { + return "", err + } + return fmt.Sprintf("%x", sum), nil } func validateVPCConfig(v interface{}) (map[string]interface{}, error) {