Terraform Automation : Is there any way to interact with Terraform CLI using API (Golang)?

Terraform Automation
I’m Working on a Use case to create Personal UI for terraform.
For this I’ll host terraform service on one server and using APIs one can interact with it. (Like in terraform enterprise web UI)
For example , I want to run terraform plan/apply using REST APIs.

Revert ASAP
Thank You.

Hi @Mohitp98,

There is no supported in-process Go library API for Terraform. Terraform is a CLI tool and so its interface is via running CLI commands only. There are some parts of the CLI that are designed for programmatic consumption, such as terraform show -json to obtain JSON-formatted descriptions of the current state and of saved plans, or terraform output -json to retrieve the current root module output values.

Terraform Cloud and Enterprise interact with Terraform by running the CLI and, where appropriate, capturing the JSON-formatted output. For example, Terraform Cloud/Enterprise both save the result of terraform show -json planfile against each run so that other subsystems can consume that data.

1 Like

Thanks, @apparentlymart for this real quick reply.
I’m new to golang and such complex appications (terraform UI).
So you mean Terraform cloud is executing shell scripts( to run terraform) using Golang and the output is stored in the plan file and further represented in UI ?

Hi @Mohitp98,

If your application itself is written in Go then you’ll probably use the os/exec package to run Terraform, possibly capturing its output. There are some general examples of running programs in different ways in the documentation for that package.

You don’t generally need intermediate shell scripts; the Go program can just run Terraform’s executable directly itself, passing the necessary arguments to run the command you want to run.

1 Like

Thank you again @apparentlymart this is really helpful.
Looking forward to creating APIs for my use case using this method.