Skip to content

Commit

Permalink
import: add support for import blocks
Browse files Browse the repository at this point in the history
In Terraform 1.5+, there is now the option to import resources using a HCL block alongside your resources code[1]. This commit updates the `import` command to support that conditional generation if the `—modern-import-block` flag is used.

CLI compatible output

```
terraform import cloudflare_ruleset.terraform_managed_resource_c311c194ead8414c985c44eb4710d435 zone/0d555506aec9767e661a2e19e6d4e711/c311c194ead8414c985c44eb4710d435
terraform import cloudflare_ruleset.terraform_managed_resource_64a2203f3c0246bebc2f39b886d54982 zone/0d555506aec9767e661a2e19e6d4e711/64a2203f3c0246bebc2f39b886d54982
```

HCL block import output

```
import {
  to = cloudflare_ruleset.terraform_managed_resource_c311c194ead8414c985c44eb4710d435
  id = "zone/0d555506aec9767e661a2e19e6d4e711/c311c194ead8414c985c44eb4710d435"
}

import {
  to = cloudflare_ruleset.terraform_managed_resource_64a2203f3c0246bebc2f39b886d54982
  id = "zone/0d555506aec9767e661a2e19e6d4e711/64a2203f3c0246bebc2f39b886d54982"
}
```

[1]: https://developer.hashicorp.com/terraform/language/import
  • Loading branch information
jacobbednarz committed Oct 26, 2023
1 parent b9c3de5 commit f2d7beb
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 9 deletions.
43 changes: 35 additions & 8 deletions internal/app/cf-terraforming/cmd/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import (
"time"

"github.com/cloudflare/cloudflare-go"
"github.com/hashicorp/hcl/v2/hclwrite"
"github.com/spf13/cobra"
"github.com/zclconf/go-cty/cty"
)

// resourceImportStringFormats contains a mapping of the resource type to the
Expand Down Expand Up @@ -483,16 +485,43 @@ func runImport() func(cmd *cobra.Command, args []string) {
return
}

importFile := hclwrite.NewEmptyFile()
importBody := importFile.Body()

for _, data := range jsonStructData {
fmt.Fprint(cmd.OutOrStdout(), buildCompositeID(resourceType, data.(map[string]interface{})["id"].(string)))
id := data.(map[string]interface{})["id"].(string)

if useModernImportBlock {
idvalue := buildRawImportAddress(resourceType, id)
imp := importBody.AppendNewBlock("import", []string{}).Body()
imp.SetAttributeRaw("to", hclwrite.TokensForIdentifier(fmt.Sprintf("%s.%s", resourceType, fmt.Sprintf("%s_%s", terraformResourceNamePrefix, id))))
imp.SetAttributeValue("id", cty.StringVal(idvalue))
importFile.Body().AppendNewline()
} else {
fmt.Fprint(cmd.OutOrStdout(), buildTerraformImportCommand(resourceType, id))
}
}

if useModernImportBlock {
// don't format the output; there is a bug in hclwrite.Format that
// splits incorrectly on certain characters. instead, manually
// insert new lines on the block.
fmt.Fprint(cmd.OutOrStdout(), string(importFile.Bytes()))
}
}
}

// buildCompositeID takes the resourceType and resourceID in order to lookup the
// resource type import string and then return a suitable composite value that
// is compatible with `terraform import`.
func buildCompositeID(resourceType, resourceID string) string {
// buildTerraformImportCommand takes the resourceType and resourceID in order to
// lookup the resource type import string and then return a suitable composite
// value that is compatible with `terraform import`.
func buildTerraformImportCommand(resourceType, resourceID string) string {
resourceImportAddress := buildRawImportAddress(resourceType, resourceID)
return fmt.Sprintf("%s %s.%s_%s %s\n", terraformImportCmdPrefix, resourceType, terraformResourceNamePrefix, resourceID, resourceImportAddress)
}

// buildRawImportAddress takes the resourceType and resourceID in order to lookup
// the resource type import string and then return a suitable address.
func buildRawImportAddress(resourceType, resourceID string) string {
if _, ok := resourceImportStringFormats[resourceType]; !ok {
log.Fatalf("%s does not have an import format defined", resourceType)
}
Expand All @@ -508,16 +537,14 @@ func buildCompositeID(resourceType, resourceID string) string {
identiferValue = zoneID
}

s := ""
s += fmt.Sprintf("%s %s.%s_%s %s", terraformImportCmdPrefix, resourceType, terraformResourceNamePrefix, resourceID, resourceImportStringFormats[resourceType])
s := resourceImportStringFormats[resourceType]
replacer := strings.NewReplacer(
":identifier_type", identiferType,
":identifier_value", identiferValue,
":zone_id", zoneID,
":account_id", accountID,
":id", resourceID,
)
s += "\n"

return replacer.Replace(s)
}
4 changes: 3 additions & 1 deletion internal/app/cf-terraforming/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

var log = logrus.New()
var cfgFile, zoneID, hostname, apiEmail, apiKey, apiToken, accountID, terraformInstallPath, terraformBinaryPath string
var verbose bool
var verbose, useModernImportBlock bool
var api *cloudflare.API
var terraformImportCmdPrefix = "terraform import"
var terraformResourceNamePrefix = "terraform_managed_resource"
Expand Down Expand Up @@ -118,6 +118,8 @@ func init() {
if err = viper.BindEnv("terraform-install-path", "CLOUDFLARE_TERRAFORM_INSTALL_PATH"); err != nil {
log.Fatal(err)
}

rootCmd.PersistentFlags().BoolVarP(&useModernImportBlock, "modern-import-block", "", false, "Whether to generate HCL import blocks for generated resources instead of `terraform import` compatible CLI commands. This is only compatible with Terraform 1.5+")
}

// initConfig reads in config file and ENV variables if set.
Expand Down

0 comments on commit f2d7beb

Please sign in to comment.