You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CloudFormation创建S3 Bucket时正则匹配无效名称的问题求助

Fixing S3 Bucket Name Validation Regex for CloudFormation

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..bucket is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:37:00