CloudFormation创建S3 Bucket时正则匹配无效名称的问题求助
Got it, let's sort out that regex to properly align with AWS S3's bucket naming rules. Your current pattern ^([0-9a-z.-]){3,63}$ lets through invalid names like ... or --- because it misses several critical restrictions that S3 enforces.
First, let's recap the non-negotiable S3 bucket naming rules that your regex needs to cover:
- Length must be between 3 and 63 characters
- Can only include lowercase letters, numbers, hyphens (
-), and periods (.) - Cannot start or end with a hyphen or period
- Cannot contain consecutive periods (e.g.,
my..bucketis invalid) - Cannot be formatted as an IPv4 address (like
192.168.1.1)
The Corrected Regex
Here's a pattern that enforces all these rules:
^(?!(?:\d+\.){3}\d+$)(?!.*\.\.)[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$
Let's break down what each part does:
^(?!(?:\d+\.){3}\d+$): A negative lookahead that blocks any string matching an IPv4 address format(?!.*\.\.): Another negative lookahead to prevent consecutive periods anywhere in the name[a-z0-9]: Ensures the bucket name starts with a valid character (no hyphens or periods)[a-z0-9.-]{1,61}: Allows 1-61 valid characters in the middle (since start and end take 2 characters, total length stays within 3-63)[a-z0-9]: Ensures the name ends with a valid character (no hyphens or periods)
Using This in CloudFormation
You can plug this directly into the AllowedPattern field of your bucket name parameter. Here's an example YAML snippet:
Parameters: S3BucketName: Type: String Description: Name for your new S3 bucket AllowedPattern: "^(?!(?:\\d+\\.){3}\\d+$)(?!.*\\.\\.)[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$" ConstraintDescription: Must be a valid S3 bucket name (3-63 lowercase letters/numbers/hyphens/periods; no leading/trailing hyphens/periods, no consecutive periods, not an IPv4 address)
This will block all the invalid cases you mentioned (like ... or ---) and ensure your bucket names comply with AWS's requirements.
内容的提问来源于stack exchange,提问作者user4108565

