func generateAutoTFVarsFile()

in custom-targets/infrastructure-manager/im-deployer/render.go [212:286]


func generateAutoTFVarsFile(autoTFVarsPath string, params *params) error {
	// Check whether clouddeploy.auto.tfvars file exists. If it does then fail the render, otherwise create it.
	if _, err := os.Stat(autoTFVarsPath); !os.IsNotExist(err) {
		return fmt.Errorf("cloud deploy auto.tfvars file %q already exists, failing render to avoid overwriting any configuration", autoTFVarsPath)
	}
	autoTFVarsFile, err := os.Create(autoTFVarsPath)
	if err != nil {
		return fmt.Errorf("error creating cloud deploy auto.tfvars file: %v", err)
	}
	defer autoTFVarsFile.Close()

	if len(params.variablePath) > 0 {
		varsPath := path.Join(path.Dir(autoTFVarsPath), params.variablePath)
		fmt.Printf("Attempting to copy contents from %s to %s so the variables are automatically consumed by Terraform\n", varsPath, autoTFVarsPath)
		varsFile, err := os.Open(varsPath)
		if err != nil {
			return fmt.Errorf("unable to open variable file provided at %s: %v", varsPath, err)
		}
		defer varsFile.Close()

		autoTFVarsFile.Write([]byte(fmt.Sprintf("# Sourced from %s.\n", params.variablePath)))
		if _, err := io.Copy(autoTFVarsFile, varsFile); err != nil {
			return fmt.Errorf("unable to copy contents from %s to %s: %v", varsPath, autoTFVarsPath, err)
		}
		autoTFVarsFile.Write([]byte("\n"))
		fmt.Printf("Finished copying contents from %s to %s\n", varsPath, autoTFVarsPath)
	}

	hclFile := hclwrite.NewEmptyFile()
	rootBody := hclFile.Body()

	// Track whether we found any relevant environment variables to determine if we write to the file.
	found := false
	var keys []string
	kv := make(map[string]cty.Value)
	envVars := os.Environ()
	for _, rawEV := range envVars {
		if !strings.HasPrefix(rawEV, imVarEnvKeyPrefix) {
			continue
		}
		found = true
		fmt.Printf("Found infrastucture manager environment variable %s, will add to corresponding variable to %s\n", rawEV, autoTFVarsPath)

		// Remove the prefix so we can get the variable name.
		ev := strings.TrimPrefix(rawEV, imVarEnvKeyPrefix)
		eqIdx := strings.Index(ev, "=")
		// Invalid.
		if eqIdx == -1 {
			continue
		}
		name := ev[:eqIdx]
		rawVal := ev[eqIdx+1:]

		val, err := parseCtyValue(rawVal, name)
		if err != nil {
			return err
		}
		keys = append(keys, name)
		kv[name] = val
	}

	// We sort the entries so the ordering is consistent between Cloud Deploy Releases.
	sort.Strings(keys)
	for _, k := range keys {
		rootBody.SetAttributeValue(k, kv[k])
	}

	if found {
		autoTFVarsFile.Write([]byte(fmt.Sprintf("# Sourced from %s prefixed deploy parameters.\n", imVarDeployParamKeyPrefix)))
		if _, err = autoTFVarsFile.Write(hclFile.Bytes()); err != nil {
			return fmt.Errorf("error writing to cloud deploy auto.tfvars file: %v", err)
		}
	}
	return nil
}