aws_lambda_function: Force code update on SHA sum mismatch

This commit is contained in:
Chris Marchesi 2015-12-09 17:42:12 -08:00 committed by Radek Simko
parent 4aeb5bb8e9
commit b5c7521f52
1 changed files with 41 additions and 2 deletions

View File

@ -2,6 +2,7 @@ package aws
import ( import (
"crypto/sha256" "crypto/sha256"
"encoding/base64"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log" "log"
@ -102,6 +103,11 @@ func resourceAwsLambdaFunction() *schema.Resource {
}, },
}, },
}, },
"update_code": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"arn": &schema.Schema{ "arn": &schema.Schema{
Type: schema.TypeString, Type: schema.TypeString,
Computed: true, Computed: true,
@ -113,7 +119,10 @@ func resourceAwsLambdaFunction() *schema.Resource {
"source_code_hash": &schema.Schema{ "source_code_hash": &schema.Schema{
Type: schema.TypeString, Type: schema.TypeString,
Computed: true, 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) 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 return nil
} }
@ -361,6 +390,7 @@ func resourceAwsLambdaFunctionUpdate(d *schema.ResourceData, meta interface{}) e
return resourceAwsLambdaFunctionRead(d, meta) return resourceAwsLambdaFunctionRead(d, meta)
} }
// loads the local ZIP data and the SHA sum of the data.
func loadLocalZipFile(v string) ([]byte, string, error) { func loadLocalZipFile(v string) ([]byte, string, error) {
filename, err := homedir.Expand(v) filename, err := homedir.Expand(v)
if err != nil { if err != nil {
@ -371,7 +401,16 @@ func loadLocalZipFile(v string) ([]byte, string, error) {
return nil, "", err return nil, "", err
} }
sum := sha256.Sum256(zipfile) 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) { func validateVPCConfig(v interface{}) (map[string]interface{}, error) {