From 5d0b8d92509e3979b9f0cbb63ba886a6c31406c1 Mon Sep 17 00:00:00 2001 From: Thayne McCombs Date: Wed, 1 Oct 2025 10:30:52 -0600 Subject: [PATCH] fix[ec2_instance]: Handle invalid utf8 in Read When reading the UserData for an instance, if the decoded user data isn't valid UTF-8, then store the base64 value in user_data_base64 instead of the raw value in user_data. This ensures that we don't store an invalid string in the `user_data` field, resulting in invalid json. In particular, this allows importing an aws_instance that has binary UserData without resulting in an invalid state. Fixes: #44506 --- .changelog/44506.txt | 3 +++ internal/service/ec2/ec2_instance.go | 8 +++++++- 2 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 .changelog/44506.txt diff --git a/.changelog/44506.txt b/.changelog/44506.txt new file mode 100644 index 000000000000..afc50c962c1a --- /dev/null +++ b/.changelog/44506.txt @@ -0,0 +1,3 @@ +```release-note:bug +resource/aws_instance: Don't store invalid string in user_data attribute +``` diff --git a/internal/service/ec2/ec2_instance.go b/internal/service/ec2/ec2_instance.go index 6ec037f7bd37..f104302967d9 100644 --- a/internal/service/ec2/ec2_instance.go +++ b/internal/service/ec2/ec2_instance.go @@ -16,6 +16,7 @@ import ( "strconv" "strings" "time" + "unicode/utf8" "github.com/YakDriver/regexache" "github.com/aws/aws-sdk-go-v2/aws" @@ -3382,7 +3383,12 @@ func resourceInstanceFlatten(ctx context.Context, client *conns.AWSClient, insta if err != nil { return sdkdiag.AppendErrorf(diags, "decoding user_data: %s", err) } - rd.Set("user_data", string(data)) + if utf8.Valid(data) { + rd.Set("user_data", string(data)) + } else { + // The user_data wasn't valid UTF-8, so we need to store it as base64 instead of as the raw string. + rd.Set("user_data_base64", attr.UserData.Value) + } } } }