terraform

How do I get the Terraform version from inside a provider


I have a custom Terraform provider. When something goes wrong, I want to print a standard error message that includes the version of Terraform that ran the provider. This provides a copy and paste error message that can be sent to a support team.

How can I find the Terraform version from within a custom provider so it can be printed in an error message?


Solution

  • So I managed to get time to mock this up, and yes it is possible. Some of it will depend on the design of your provider. I have mocked this up with terraform framework plugin format which is the more modern way to write providers.

    This example consists of 3 files.

    provider.go Here we can get the terraform version from the provider configure request and store it as a var in helpers.go

    func (p *MyProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
        helpers.TerraformVersion = req.TerraformVersion
        ...
        ...
    

    helpers.go

    a package to hold the var (it cant be stored in the provider.go because of circular import cycles)

    var TerraformVersion string
    

    equipment.go

    
    func (d *EquipmentDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
        tflog.Info(ctx, "Running data source", map[string]interface{}{"terraformVersion": helpers.TerraformVersion})
        var data EquipmentDataSourceModel
        ...
        ...
    

    Now if i check my CLI for which version of terraform I am using

    $ terraform --version
    2025-02-17T16:39:42.417Z [INFO]  Terraform version: 1.8.2
    

    if I now run a terraform plan using the data source setting the log level to info

    $ TF_LOG=info terraform plan
    ...
    
    2025-02-17T16:40:32.553Z [INFO]  provider.terraform-provider-foobar.exe: Running data source: tf_req_id=b117bcae-3444-2178-9c9f-24c8e2eebbfe @caller=C:/Projects/GoLand/terraform-provider-foobar/
    internal/services/device-service/equipment_data_source.go:131 @module=foobarterraformVersion=1.8.2 tf_data_source_type=foobar_equipment tf_provider_addr=hashicorp.com/edu/foobartf_rpc=ReadDataSource timestamp=2025-02-17T16:40:32.553Z
    ...
    

    In the output we can see its logging the terraform version I am running this with

    terraformVersion=1.8.2