github.com/rstandt/terraform@v0.12.32-0.20230710220336-b1063613405c/tools/terraform-bundle/config.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  
     7  	"github.com/hashicorp/hcl"
     8  	"github.com/hashicorp/terraform/plugin/discovery"
     9  )
    10  
    11  var zeroTwelve = discovery.ConstraintStr(">= 0.12.0").MustParse()
    12  
    13  type Config struct {
    14  	Terraform TerraformConfig                      `hcl:"terraform"`
    15  	Providers map[string][]discovery.ConstraintStr `hcl:"providers"`
    16  }
    17  
    18  type TerraformConfig struct {
    19  	Version discovery.VersionStr `hcl:"version"`
    20  }
    21  
    22  func LoadConfig(src []byte, filename string) (*Config, error) {
    23  	config := &Config{}
    24  	err := hcl.Decode(config, string(src))
    25  	if err != nil {
    26  		return config, err
    27  	}
    28  
    29  	err = config.validate()
    30  	return config, err
    31  }
    32  
    33  func LoadConfigFile(filename string) (*Config, error) {
    34  	src, err := ioutil.ReadFile(filename)
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  
    39  	return LoadConfig(src, filename)
    40  }
    41  
    42  func (c *Config) validate() error {
    43  	if c.Terraform.Version == "" {
    44  		return fmt.Errorf("terraform.version is required")
    45  	}
    46  
    47  	var v discovery.Version
    48  	var err error
    49  	if v, err = c.Terraform.Version.Parse(); err != nil {
    50  		return fmt.Errorf("terraform.version: %s", err)
    51  	}
    52  	if !zeroTwelve.Allows(v) {
    53  		return fmt.Errorf("this version of terraform-bundle can only build bundles for Terraform v0.12 and later; build terraform-bundle from the v0.11 branch or a v0.11.* tag to construct bundles for earlier versions")
    54  	}
    55  
    56  	if c.Providers == nil {
    57  		c.Providers = map[string][]discovery.ConstraintStr{}
    58  	}
    59  
    60  	for k, cs := range c.Providers {
    61  		for _, c := range cs {
    62  			if _, err := c.Parse(); err != nil {
    63  				return fmt.Errorf("providers.%s: %s", k, err)
    64  			}
    65  		}
    66  	}
    67  
    68  	return nil
    69  }