Skip to content

Unexpected Token parsing HCL/Terraform files with conditional statements. #149

Closed

Description

@dvpierce

Error:

  File "/home/chrobinson.com/pierdavpa/.local/lib/python3.11/site-packages/lark/parsers/lalr_parser.py", line 126, in feed_token
    action, arg = states[state][token.type]
                  ~~~~~~~~~~~~~^^^^^^^^^^^^
KeyError: '__ANON_3'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/home/chrobinson.com/pierdavpa/.local/lib/python3.11/site-packages/hcl2/api.py", line 14, in load
    return loads(file.read(), with_meta=with_meta)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/chrobinson.com/pierdavpa/.local/lib/python3.11/site-packages/hcl2/api.py", line 27, in loads
    tree = hcl2.parse(text + "\n")
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/chrobinson.com/pierdavpa/.local/lib/python3.11/site-packages/lark/lark.py", line 652, in parse
    return self.parser.parse(text, start=start, on_error=on_error)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/chrobinson.com/pierdavpa/.local/lib/python3.11/site-packages/lark/parser_frontends.py", line 101, in parse
    return self.parser.parse(stream, chosen_start, **kw)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/chrobinson.com/pierdavpa/.local/lib/python3.11/site-packages/lark/parsers/lalr_parser.py", line 41, in parse
    return self.parser.parse(lexer, start)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/chrobinson.com/pierdavpa/.local/lib/python3.11/site-packages/lark/parsers/lalr_parser.py", line 171, in parse
    return self.parse_from_state(parser_state)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/chrobinson.com/pierdavpa/.local/lib/python3.11/site-packages/lark/parsers/lalr_parser.py", line 193, in parse_from_state
    raise e
  File "/home/chrobinson.com/pierdavpa/.local/lib/python3.11/site-packages/lark/parsers/lalr_parser.py", line 184, in parse_from_state
    state.feed_token(token)
  File "/home/chrobinson.com/pierdavpa/.local/lib/python3.11/site-packages/lark/parsers/lalr_parser.py", line 129, in feed_token
    raise UnexpectedToken(token, expected, state=self, interactive_parser=None)
lark.exceptions.UnexpectedToken: Unexpected token Token('__ANON_3', 'secondary_read_write_connection_string_id') at line 70, column 5.
Expected one of: 
        * STAR
        * COMMA
        * PERCENT
        * MINUS
        * __ANON_1
        * SLASH
        * __ANON_8
        * RBRACE
        * __ANON_5
        * __ANON_2
        * __ANON_4
        * __ANON_9
        * __ANON_7
        * LESSTHAN
        * PLUS
        * MORETHAN
        * __ANON_6
        * QMARK
        * __ANON_0

When parsing a file that has a conditional assignment in it. key = value == null ? "" : someothervalue

Any idea how I might fix or work around this? Or if a library fix is needed (or can even address this?)

Activity

  1. purajit commented on Feb 16, 2024

    @purajit

    I have this issue too, it seems like it's expecting parentheses.

  2. kkozik-amplify commented on Mar 7, 2024

    @kkozik-amplify
    Collaborator

    Hello, thanks for the report
    I'm not able to reproduce. Does the bug still occur? If so, could you provide some piece of config that's causing it?

  3. grahamhar commented on Mar 13, 2024

    @grahamhar

    Hi @kkozik-amplify ,

    I just hit the same and have managed to update the test case to show the failure (see this branch). I have been unable to find a solution so far as I am not that familiar with lark.

  4. kkozik-amplify commented on Mar 13, 2024

    @kkozik-amplify
    Collaborator

    @grahamhar Hi, thanks for the test case.
    It looks like the issue is caused by incorrect definition in the grammar file - we will look into this.
    As a workaround, wrapping conditional expression into parentheses should help:
    operator = (local.assertion == 1 ? local.yes : local.no)

  5. grahamhar commented on Mar 13, 2024

    @grahamhar

    It does appear that the files parse OK when we downgrade to 4.3.0

    I have been doing a little more testing and we have some conditionals that have embedded conditionals too.

    operator = local.assertion == 1 ? local.some_logic == 2 ? local.yes : "custom" : local.no

  6. Awlie commented on Apr 10, 2024

    @Awlie

    Hi there,
    we also had this issue.
    We currently downgraded to 4.3.0. Any higher version (4.3.1, 4.3.2, 4.3.3) didn't work

    We could only reproduce this error this way in our unit test:

    module "unittest" {
      nested = {
        nested_attribute = var.nested == null ? null : {
          publisher = var.nested.publisher
        }
        nested_after_conditional_object = var.variable
      }
    }
    

    and (basically the same)

    module "unittest" {
      nested = {
        nested_attribute = var.attr == null ? local.yes : local.no
        nested_after_conditional_object = var.variable
      }
    }
    

    which would fail with lark.exceptions.UnexpectedToken: Unexpected token Token('__ANON_3', 'nested_after_conditional_object')

    other conditionals wouldn't cause issues.

    The workaround with parentheses also worked, but is not a viable option for us

    These didn't fail:
    almost the same as above, but without the attribute after the conditional (nested_after_conditional_object)

    module "unittest" {
      nested = {
        nested_attribute = var.nested == null ? null : {
          publisher = var.nested.publisher
        }
      }
    }
    

    some other conditionals we tested (we also tested the failing one with parentheses, which passes)

    module "unittest" {
      conditional        = var.question ? one(azurerm_resource_group.rg[*].name) : var.no
      nested_conditional = var.question != null ? var.yes != null ? var.yesyes : local.yesno : var.no
      attribute = var.attribute == null ? null : {
        publisher = var.attribute.publisher
      }
      after_attribute = var.variable
    }
    

    (this module syntax is of course not correct, but it doesn't matter for the parser)
    This is pretty much the test-case that grahamhar added.

  7. kadigergo commented on May 22, 2024

    @kadigergo

    here is also an example:

    locals {
      a = {
        b = terraform.workspace == "production" ? "x" : "y"
        c = terraform.workspace == "production" ? "n" : "m"
      }
    }
    

    parsing fails only if it is nested and we have two with the ? : syntax

  8. RPitt commented on Jul 5, 2024

    @RPitt

    This seemingly is related to / the same root cause as
    #163
    #140
    In short parsing of expressions seems to be problematic in 4.3.1+

  9. kkozik-amplify commented on Mar 27, 2025

    @kkozik-amplify
    Collaborator

    Fixed in version 7.0.0

  10. ian-nicholls2-NHSD commented on Oct 17, 2025

    @ian-nicholls2-NHSD

    I've also just come across this with latest version - it was quite a complex bit of terraform - but it works with terraform and fails in tflocal - its where we need to add a tag to disable AWS Backup to an S3 bucket thats automatically provisioned by the AWS Admins so need to import the bucket and JUST add the new tag - ofc the data object doesn't give you the tags so needed to get those via aws cli :( then ignore all the global tags that Key and Value are the same and only set the ones where its diff + the new tag.

    I had to use { "${tag.Key}" = tag.Value } which is a linting no-no so need an exception for terraform_deprecated_interpolation

    In terraform only { tostring(tag.Key) = tag.Value } works and tflint is happy but tflocal gives

    Unable to parse "s3_audit.tf" as HCL file: Unexpected token Token('LPAR', '(') at line 40, column 17.
    Expected one of: 
    	* COLON
    	* DOT
    	* EQ
    

    Below works but needs a tflint disablement to pass the checks:

    # Get the existing S3 buckets info
    data "aws_s3_bucket" "corporate-s3-audit" {
      count  = local.same_account == false ? local.environment != "local" ? 1 : 0 : 0
      bucket = "${local.pipeline_role_name[local.environment]}-s3-audit"
    }
    
    # Get the existing S3 buckets tags - not gettable via data/resource :( so using aws script
    data "external" "s3_get_tags" {
      count   = length(data.aws_s3_bucket.corporate-s3-audit)
      program = ["bash", "../scripts/s3_get_tags.sh", data.aws_s3_bucket.corporate-s3-audit[0].id]
    }
    
    # import the buckets into terraform
    import {
      for_each = data.aws_s3_bucket.corporate-s3-audit
      identity = {
        bucket = each.value.id
      }
      to = aws_s3_bucket.corporate-s3-audit[0]
    }
    
    # Now set the buckets tags to be same as before with just the "DISABLE-BACKUP" = "true" added
    resource "aws_s3_bucket" "corporate-s3-audit" {
      ## Not our bucket (AWS Admins) so we are not altering anything bar adding a tag...
      count  = length(data.aws_s3_bucket.corporate-s3-audit)
      bucket = data.aws_s3_bucket.corporate-s3-audit[0].id
      # complex object/tuple/common_tags merge stuff to ONLY add the new tag and don't get rid of the rest - made harder by the s3 object not currently giving back the tags 
      tags = merge(
        concat([
          # loop through the S3 buckets existing tags
          for tag in jsondecode(data.external.s3_get_tags[0].result.tags) :
          # build a tuple of Key=Value  UNLESS the tag is in common tags and both the key and value are the same
          # tflint-ignore: terraform_deprecated_interpolation # - done as using tostring(tag.Key) instead works in terraform but has HCL issues in tflocal 0.24.1
          { "${tag.Key}" = tag.Value } if !(contains(keys(local.common_tags), tag.Key) && local.common_tags[tag.Key] == tag.Value)
          ],
          # now add the extra tag to disable backups - should be the only "new" tag 
          [
            { "DISABLE-BACKUP" = "true" }
          ]
          # the ... is important - fails without it...
        )...
      )
    }
    

    tflocal fails but terraform works:

    # Get the existing S3 buckets info
    data "aws_s3_bucket" "corporate-s3-audit" {
      count  = local.same_account == false ? local.environment != "local" ? 1 : 0 : 0
      bucket = "${local.pipeline_role_name[local.environment]}-s3-audit"
    }
    
    # Get the existing S3 buckets tags - not gettable via data/resource :( so using aws script
    data "external" "s3_get_tags" {
      count   = length(data.aws_s3_bucket.corporate-s3-audit)
      program = ["bash", "../scripts/s3_get_tags.sh", data.aws_s3_bucket.corporate-s3-audit[0].id]
    }
    
    # import the buckets into terraform
    import {
      for_each = data.aws_s3_bucket.corporate-s3-audit
      identity = {
        bucket = each.value.id
      }
      to = aws_s3_bucket.corporate-s3-audit[0]
    }
    
    # Now set the buckets tags to be same as before with just the "DISABLE-BACKUP" = "true" added
    resource "aws_s3_bucket" "corporate-s3-audit" {
      ## Not our bucket (AWS Admins) so we are not altering anything bar adding a tag...
      count  = length(data.aws_s3_bucket.corporate-s3-audit)
      bucket = data.aws_s3_bucket.corporate-s3-audit[0].id
      # complex object/tuple/common_tags merge stuff to ONLY add the new tag and don't get rid of the rest - made harder by the s3 object not currently giving back the tags 
      tags = merge(
        concat([
          # loop through the S3 buckets existing tags
          for tag in jsondecode(data.external.s3_get_tags[0].result.tags) :
          # build a tuple of Key=Value  UNLESS the tag is in common tags and both the key and value are the same
          { tostring(tag.Key) = tag.Value } if !(contains(keys(local.common_tags), tag.Key) && local.common_tags[tag.Key] == tag.Value)
          ],
          # now add the extra tag to disable backups - should be the only "new" tag 
          [
            { "DISABLE-BACKUP" = "true" }
          ]
          # the ... is important - fails without it...
        )...
      )
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions