From ce1f8dd22bf9fab55212cc547cacfac3d8129f21 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Wed, 27 Sep 2023 17:02:43 -0700 Subject: [PATCH] states: ParseDeposedKey function This is a helper for when we're accepting a deposed key from outside of Terraform, such as in a plan or state file. It doesn't really "parse" the string in the usual sense -- the result is always just the input verbatim if successful -- but it's named that way for consistency with how we usually name functions like this. --- internal/states/resource.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/internal/states/resource.go b/internal/states/resource.go index e472cc4569..8eb9c5e8da 100644 --- a/internal/states/resource.go +++ b/internal/states/resource.go @@ -4,8 +4,10 @@ package states import ( + "encoding/hex" "fmt" "math/rand" + "strings" "time" "github.com/hashicorp/terraform/internal/addrs" @@ -189,6 +191,22 @@ func NewDeposedKey() DeposedKey { return DeposedKey(fmt.Sprintf("%08x", v)) } +// ParseDeposedKey parses a string that is expected to be a deposed key, +// returning an error if it doesn't conform to the expected syntax. +func ParseDeposedKey(raw string) (DeposedKey, error) { + if len(raw) != 8 { + return "00000000", fmt.Errorf("must be eight hexadecimal digits") + } + if raw != strings.ToLower(raw) { + return "00000000", fmt.Errorf("must use lowercase hex digits") + } + _, err := hex.DecodeString(raw) + if err != nil { + return "00000000", fmt.Errorf("must be eight hexadecimal digits") + } + return DeposedKey(raw), nil +} + func (k DeposedKey) String() string { return string(k) }