Terraform autocompletion not working on macOS with default zsh shell

Hi Everyone

I’m having trouble enabling autocompletion on a fresh MacOS terraform install.

At first running the command terraform -install-autocomplete would return:

Error executing CLI: Did not find any shells to install

I noticed that on a fresh OS install there was no .zshrc file in my home directory, so I created one with touch ~/.zshrc and re-ran terraform -install-autocomplete.

This resulted in adding the following to my ~/.zshrc file:

autoload -U +X bashcompinit && bashcompinit
complete -o nospace -C /usr/local/bin/terraform terraform

So I restarted my zsh session and autocomplete does not work. There is an error message that appears beneath the login banner:

complete:13: command not found: compdef

I can work around this by changing my default shell back to Bash, running terraform -uninstall-autocomplete, touching a ~/.profile file and running terraform -install-autocomplete again, but I’d like to use zsh since bash is now deprecated on MacOS.

Does anyone know how to get this working without having to install even more software like homebrew, oh-my-zsh etc.?

Here are the details of the versions I’m running:

OS: macOS Catalina Version 10.15.5
Terminal App: Terminal (default)
Shell: zsh 5.7.1 (x86_64-apple-darwin19.0) (default)
Terraform version: v0.12.28
Path to terraform binary: /usr/local/bin/terraform

Kind Regards,

Ben

Update:
Opened issue on Terraform Git: https://github.com/hashicorp/terraform/issues/25421

Problem solved thanks to the awesome @alisdair!

Looks like the install-autocorrect script could do with a check to see if the following line is present in .zshrc or not:

autoload -Uz compinit && compinit

Proposed a change to the zsh.go script in @posener 's complete library that Terraform depends on: posener/complete#124
Added check for the autoload -Uz compinit && compinit line in zsh.go.

For anyone else looking to solve this problem, here is my full working .zshrc :

autoload -U +X bashcompinit && bashcompinit
autoload -Uz compinit && compinit
complete -o nospace -C /usr/local/bin/terraform terraform
8 Likes

Thank you. It really helped me!

> Error executing CLI: Did not find any shells to install

If anyone is experiencing this on Mac and is using bash instead of zsh then note that you need a ~/.bash_profile file. Having a ~/.bashrc file is not sufficient as this tool only looks for bash_profile file on mac.

Fixed the command not found: compdef error.

Thank you!