skip to Main Content

My regex-foo is weak. I need to parse this string:

arn:${awsPartition}:iam::010101010101:user/${userName}

Partitions: aws|aws-us-gov|aws-cn

Basically, the matching should isolate everything except the last bit /${userName} and leave only arn:${awsPartition}:iam::010101010101:user.

I tried this in Terraform but I seem to have offended it with Perl syntax:

user_arn   = regex("^.+?(?=/|$)", data.aws_caller_identity.current.arn)[0]
│ Error: Invalid function argument
│ 
│   on main.tf line 23, in locals:
│   23:   user_arn = regex("^.+?(?=/|$)", data.aws_caller_identity.current.arn)[0]
│     ├────────────────
│     │ while calling regex(pattern, string)
│ 
│ Invalid value for "pattern" parameter: invalid regexp pattern: invalid or unsupported Perl syntax in (?=.

Terraform regex seems to support Google’s RE2-style.

Now my brain is tired. If anyone can lend some guidance I’d appreciate it.

2

Answers


  1. This RegEx should work
    ^(.*)\/[^/]+$

    Basically, it consists of 2 parts:

    • ^(.*) – matches start of the string and as much as it can while trying to match entire pattern.
    • \/[^/]+$ – matches the last slash and anything towards the end of the string.

    Example:

    regex("^(.*)\/[^/]+$", "arn:test:iam::010101010101:user/test")
    [
      "arn:test:iam::010101010101:user",
    ]
    
    Login or Signup to reply.
  2. You could just capture everything before the / character:

    regex("^(.*)/", data.aws_caller_identity.current.arn)[0]
    

    Although, you don’t even need regex for this, you could just split the string on the / character and take the first part:

    split("/", data.aws_caller_identity.current.arn)[0]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search