Why tf local-exec fail with 'X was unexpected at this time'?

I’m trying to copy the contents of files to a single file on all my ec2 instances as seen below.

  provisioner "local-exec" {
    command = <<EOF
                for file in $(ls ${path.module}/temp/*) ; do
                  cat $file | ssh -i ${var.ssh_private_key_path} -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ec2-user@${aws_instance.instance[count.index].public_dns} 'tee -a /home/ec2-user/FILE'
                rm -f ${path.module}/temp/*

but it fails as follows.

module.ec2.null_resource.deploy-files[0] (local-exec): file was unexpected at this time.

Can anyone suggest what the cause might be?
Note: I am running tf v1.6.6 in git bash on Windows11.

Update: This seems to be an issue with windows as I don’t see it if deploying from a linux box. ​Can it be resolved for git bash on windows???

Hi @mick_a_thompson,

This error is not familiar to me, but after some searching I’ve come to suspect that this is a syntax error from the Windows command interpreter (cmd.exe), rather than from Terraform itself. It seems that “[token] is unexpected at this time” is how the parser reports that it found an invalid token.

Since you are running on Windows, the default behavior for local-exec is to try to run the command with cmd.exe. Your script seems to be written for a Unix-style shell rather than for the Windows command interpreter, and so I suppose it’s fair for the Windows command interpreter to complain about it.

You can specify explicitly which interpreter to use using the interpreter argument. In your case, it might work to set that as follows, assuming you have a bash.exe somewhere in your command search paths.

  interpreter = ["bash", "-e"]

Terraform will then construct a command line with bash -e followed by the entire contents of command, which should hopefully achieve the behavior you wanted.

1 Like

Inclusion of above using “-c” worked. Thank you!

Can it be specfied in root or must it be in each local-exec?

This is an argument of the local-exec provisioner itself, so you will need to specify it in each provisioner "local-exec" block.

1 Like