vscode-terraform: Cannot get autoformatting (format on save) working - VS Code

Hi There,

After ensuring my VSCode terraform extension was up to date (running 2.5.0 released an hour ago) and adding the proper settings to my settings.json vscode config file:

{
    "git.autofetch": true,
    "git.confirmSync": false,
    "editor.renderControlCharacters": true,
    "terraform.languageServer": {
        "[terraform]": {
            "editor.formatOnSave": true
        },
        "terraform-ls.experimentalFeatures": {
        },
        "external": true,
        "pathToBinary": "",
        "args": [
            "serve"
        ],
        "maxNumberOfProblems": 100,
        "trace.server": "off"
    },
}

I’m not able to get formatting to occur on a save. Is there something I’m missing? I’ve also added the terraform format on save settings block outside of the terraform.languageserver block, but get the same result (nothing happening to intentionally poorly formatted code with no indentions or spaces).

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 21
  • Comments: 34 (8 by maintainers)

Most upvoted comments

Hi folks, I have a hunch that one of the reasons for the functionality to be “flipping” is due to VS Code’s handling of conflicts when multiple extensions claim formatting support for the same file.

In other words: If you have any other extensions supporting Terraform files - have you tried disabling those?

We plan to investigate these conflicts also as part of https://github.com/hashicorp/vscode-terraform/issues/692

You can also explicitly tell VS Code to use this extension for formatting Terraform files using the following snippet of config:

    "[terraform]": {
        "editor.defaultFormatter": "hashicorp.terraform",
        "editor.formatOnSave": true
    }

With all that in mind, can anyone reproduce the issue on the latest version (2.13.1) with the latest LS version (0.19.0) and with other Terraform extensions (if any are installed) disabled? If so I’d be interested in setting up a debugging session with you or gathering more details.

I will leave this open for a few more weeks and then close unless I receive any confirmation of the above.

Thanks!

Hello all, thank you for your continued feedback. I am writing a shorter update than I wanted to due to the end of year holidays, but did want to keep you all in the loop and summarize some of what we are seeing.

Most of you are using the settings as documented in our readme. For those not following those settings, please review that section and try those. We have to specify this extension as the editor.defaultFormatter because there are other extensions that advertise the ability to format Terraform files and VS Code chooses which one depending on activation order (something outside of our control) and which is non-deterministic in general and complicated in specific cases.

For those trying to use editor.formatOnSaveMode, you will have to use file for now. The file setting works because terrafrom fmt was written to format an entire file, not ranges. The modifications or modificationsIfAvailable settings use the currently configured SCM to detect file line ranges that have changed and send those ranges to the formatter and expect only those ranges returned. In addition, if you don’t have a SCM enabled for the files you are editing, modifications won’t work at all. The modificationsIfAvailable setting will fall back to file if there is no SCM and will appear to work sometimes.

In summary, if you want to automatically format your entire Terraform file on save, us the following configuration:

"[terraform]": {
  "editor.defaultFormatter": "hashicorp.terraform",
  "editor.formatOnSave": true,
  "editor.formatOnSaveMode": "file"
},

I did not see it mentioned here, but if you are using editor.codeActionsOnSave and versions of terraform-ls older than 0.24.0 there is a known issue. If you had editor.codeActionsOnSave configured with source.fixAll there was a bug in our implementation that was fixed in the 0.24.0 release. If you pin your terraform-ls version with terrafrom.langaugeServer.requiredVersion, please update to the latest as there are fixes you are missing.

If you want to use editor.codeActionsOnSave with source.formatAll.terraform and editor.FormatOnSave, then I have an explanation and a recommendation for you. VS Code runs editor.codeActionsOnSave and editor.FormatOnSave separately and will not determine if a codeAction is performing the same operation as a formatter. This means you can format a file more than once on save if both are configured at the same time. This is part of VS Code, not just our extension, so we don’t have much control here.

So, if you want to use editor.codeActionsOnSave with source.formatAll.terraform and editor.FormatOnSave please use the following configuration. This will keep the global editor.formatOnSave for other languages you use, and configure the terraform extension to only format during a codeAction sweep.

"editor.formatOnSave": true,
"[terraform]": {
  "editor.defaultFormatter": "hashicorp.terraform",
  "editor.formatOnSave": false,
  "editor.codeActionsOnSave": {
    "source.formatAll.terraform": true
  },
},

I plan to write some more detailed documentation in an official place after the holidays. Hope this helps in the interim.

The file setting works because terrafrom fmt was written to format an entire file, not ranges.

Now that I see that in writing, it makes perfect sense and is obvious. Fantastic update! Thanks!

Hi all, I was able to fix it in my case. I found the an error in the logs, that you need to have the terraform CLI installed. Setting this to point to terraform binary fixed the formatting

"terraform-ls.terraformExecPath":"your path here for /bin/darwin/terraform""

I also added the option to format for the file not only modifications

"[terraform]": {
        "editor.formatOnSaveMode": "file",
  }

In my case autoformatting stops working (for both modified and unmodified lines) if "editor.formatOnSaveMode": "modifications" presents in settings.json and working if I commenting this setting.

@radeksimko Done: https://github.com/hashicorp/vscode-terraform/issues/744

And you’re right, seems like it’s back to normal now after my VS Code crashed trying to submit that LS output.

@radeksimko Believe it or not, I think this actually fixed it.

  • I did the code /usr/local/bin as you stated
  • VS Code opens, and prompts me to trust the workspace/directory
  • I went ahead and trusted it, tested a tf file save with that window in another directory, and it did the format
  • Restarted VSCode completely, and now other windows are formatting on save as well.

@ToniCipriani thank you for the report - that is useful.

I didn’t realize that in this edge case we don’t surface the error anywhere in the UI - we should.

Relatedly I expect we could do more in helping folks troubleshoot this by printing the whole $PATH somewhere somehow on demand.

Given that you’re on macOS I suspect that this may be related to how VS Code gets launched. An application which gets launched from Spotlight or the Dock doesn’t necessarily inherit the same ENV variables as one which is launched from the Terminal. Can you try launching VS Code via code /path/to/tf/dir from the same Terminal where you confirmed $PATH is set correctly?

It stopped working for me too.

Terraform extension version: 2.14.0 Language server version is: 0.19.1

No other Terraform extensions are installed.

settings.json:

    "terraform.languageServer": {
        "external": true,
        "args": [
            "serve"
        ],
        "maxNumberOfProblems": 100,
        "trace.server": "off"
    },
    "[terraform]": {
        "editor.defaultFormatter": "hashicorp.terraform",
        "editor.formatOnSave": true
    },

Thank you, Claudio

Hi @aeschright .

I opened a .tf file and removed some spaces in front of an aligned equal sign, and hit save. Here’s the output I received:

2021/04/14 10:28:05 server.go:581: Received 1 new requests
2021/04/14 10:28:05 server.go:174: Processing 1 requests
2021/04/14 10:28:05 server.go:265: Checking request for "workspace/executeCommand": {"command":"7.terraform-ls.rootmodules","arguments":["uri=file:///Users/davedash/Projects/terraform-config/modules/tome-backend-service/lb.tf"]}
2021/04/14 10:28:05 rpc_logger.go:29: Incoming request for "workspace/executeCommand" (ID 13): {"command":"7.terraform-ls.rootmodules","arguments":["uri=file:///Users/davedash/Projects/terraform-config/modules/tome-backend-service/lb.tf"]}
2021/04/14 10:28:05 rpc_logger.go:50: Response to "workspace/executeCommand" (ID 13): {"responseVersion":0,"doneLoading":true,"rootModules":[{"uri":"file:///Users/davedash/Projects/terraform-config/modules/tome-backend-service","name":"modules/tome-backend-service"}]}
2021/04/14 10:28:05 server.go:246: Completed 1 requests [443.057µs elapsed]
2021/04/14 10:28:06 server.go:581: Received 1 new requests
2021/04/14 10:28:06 server.go:174: Processing 1 requests
2021/04/14 10:28:06 server.go:265: Checking request for "textDocument/codeLens": {"textDocument":{"uri":"file:///Users/davedash/Projects/terraform-config/modules/tome-backend-service/lb.tf"}}
2021/04/14 10:28:06 server.go:297: Task error: [-32601] no such method "textDocument/codeLens"
2021/04/14 10:28:06 rpc_logger.go:45: Error for "textDocument/codeLens" (ID 14): [-32601] no such method "textDocument/codeLens"
2021/04/14 10:28:06 server.go:246: Completed 1 requests [265.017µs elapsed]
[Error - 10:28:06 AM] Request textDocument/codeLens failed.
  Message: no such method "textDocument/codeLens"
  Code: -32601 

Hope this helps.

Ultimately no formatting seemed to be run by doing this. This was v2.10.0