Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add --import command to add terraform import syntax #34

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

- Support resources using generateName
- Add option to remove quotes from object/map keys when not needed
- Add option to add a comment with the import syntax

# 0.1.7

Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,12 @@ export PATH=$PATH:$(go env GOPATH)/bin
```
Usage of tfk8s:
-f, --file string Input file containing Kubernetes YAML manifests (default "-")
-I, --import Add a comment above each resource with the terraform import command
-M, --map-only Output only an HCL map structure
-o, --output string Output file to write Terraform config (default "-")
-p, --provider provider Provider alias to populate the provider attribute
-s, --strip Strip out server side fields - use if you are piping from kubectl get
-Q, --strip-key-quotes Strip out quotes from HCL map keys unless they are required.
-Q, --strip-key-quotes Strip out quotes from HCL map keys unless they are required
-V, --version Show tool version
```

Expand Down
19 changes: 14 additions & 5 deletions tfk8s.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func escapeShellVars(s string) string {
// yamlToHCL converts a single YAML document Terraform HCL
func yamlToHCL(
doc cty.Value, providerAlias string,
stripServerSide bool, mapOnly bool, stripKeyQuotes bool) (string, error) {
stripServerSide bool, mapOnly bool, stripKeyQuotes bool, importComment bool) (string, error) {
m := doc.AsValueMap()
docs := []cty.Value{doc}
if strings.HasSuffix(m["kind"].AsString(), "List") {
Expand All @@ -108,6 +108,7 @@ func yamlToHCL(
for i, doc := range docs {
mm := doc.AsValueMap()
kind := mm["kind"].AsString()
apiVersion := mm["apiVersion"].AsString()
metadata := mm["metadata"].AsValueMap()
var namespace string
if v, ok := metadata["namespace"]; ok {
Expand Down Expand Up @@ -140,6 +141,13 @@ func yamlToHCL(
if mapOnly {
hcl += fmt.Sprintf("%v\n", s)
} else {
if importComment {
importID := fmt.Sprintf("apiVersion=%s,kind=%s,name=%s", apiVersion, kind, name)
if namespace != "" {
importID += ",namespace=" + namespace
}
hcl += fmt.Sprintf("# terraform import %s.%s %q\n", resourceType, resourceName, importID)
}
hcl += fmt.Sprintf("resource %q %q {\n", resourceType, resourceName)
if providerAlias != "" {
hcl += fmt.Sprintf(" provider = %v\n\n", providerAlias)
Expand All @@ -163,7 +171,7 @@ var yamlSeparator = "\n---"
// FIXME this function has too many arguments now, use functional options instead
func YAMLToTerraformResources(
r io.Reader, providerAlias string, stripServerSide bool,
mapOnly bool, stripKeyQuotes bool) (string, error) {
mapOnly bool, stripKeyQuotes bool, importComment bool) (string, error) {
hcl := ""

buf := bytes.Buffer{}
Expand Down Expand Up @@ -206,7 +214,7 @@ func YAMLToTerraformResources(
return "", fmt.Errorf("the manifest must be a YAML document")
}

formatted, err := yamlToHCL(doc, providerAlias, stripServerSide, mapOnly, stripKeyQuotes)
formatted, err := yamlToHCL(doc, providerAlias, stripServerSide, mapOnly, stripKeyQuotes, importComment)
if err != nil {
return "", fmt.Errorf("error converting YAML to HCL: %s", err)
}
Expand Down Expand Up @@ -244,7 +252,8 @@ func main() {
stripServerSide := flag.BoolP("strip", "s", false, "Strip out server side fields - use if you are piping from kubectl get")
version := flag.BoolP("version", "V", false, "Show tool version")
mapOnly := flag.BoolP("map-only", "M", false, "Output only an HCL map structure")
stripKeyQuotes := flag.BoolP("strip-key-quotes", "Q", false, "Strip out quotes from HCL map keys unless they are required.")
stripKeyQuotes := flag.BoolP("strip-key-quotes", "Q", false, "Strip out quotes from HCL map keys unless they are required")
importComment := flag.BoolP("import", "I", false, "Add a comment above each resource with the terraform import command")
flag.Parse()

if *version {
Expand All @@ -265,7 +274,7 @@ func main() {
}

hcl, err := YAMLToTerraformResources(
file, *providerAlias, *stripServerSide, *mapOnly, *stripKeyQuotes)
file, *providerAlias, *stripServerSide, *mapOnly, *stripKeyQuotes, *importComment)
if err != nil {
fmt.Println("error:", err)
os.Exit(1)
Expand Down
53 changes: 44 additions & 9 deletions tfk8s_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ data:
TEST: test`

r := strings.NewReader(yaml)
output, err := YAMLToTerraformResources(r, "", false, false, false)
output, err := YAMLToTerraformResources(r, "", false, false, false, false)

if err != nil {
t.Fatal("Converting to HCL failed:", err)
Expand Down Expand Up @@ -50,7 +50,7 @@ data:
TEST: test`

r := strings.NewReader(yaml)
output, err := YAMLToTerraformResources(r, "", false, false, false)
output, err := YAMLToTerraformResources(r, "", false, false, false, false)

if err != nil {
t.Fatal("Converting to HCL failed:", err)
Expand All @@ -73,6 +73,41 @@ resource "kubernetes_manifest" "configmap_test_name" {
assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(output))
}

func TestYAMLToTerraformResourcesImportComment(t *testing.T) {
yaml := `---
apiVersion: v1
kind: ConfigMap
metadata:
name: test
namespace: test-ns
data:
TEST: test`

r := strings.NewReader(yaml)
output, err := YAMLToTerraformResources(r, "", false, false, false, true)

if err != nil {
t.Fatal("Converting to HCL failed:", err)
}

expected := `# terraform import kubernetes_manifest.configmap_test_ns_test "apiVersion=v1,kind=ConfigMap,name=test,namespace=test-ns"
resource "kubernetes_manifest" "configmap_test_ns_test" {
manifest = {
"apiVersion" = "v1"
"data" = {
"TEST" = "test"
}
"kind" = "ConfigMap"
"metadata" = {
"name" = "test"
"namespace" = "test-ns"
}
}
}`

assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(output))
}

func TestYAMLToTerraformResourcesEscapeShell(t *testing.T) {
yaml := `---
apiVersion: v1
Expand All @@ -84,7 +119,7 @@ data:
echo Hello, ${USER} your homedir is ${HOME}`

r := strings.NewReader(yaml)
output, err := YAMLToTerraformResources(r, "", false, false, false)
output, err := YAMLToTerraformResources(r, "", false, false, false, false)

if err != nil {
t.Fatal("Converting to HCL failed:", err)
Expand Down Expand Up @@ -129,7 +164,7 @@ data:
TEST: two`

r := strings.NewReader(yaml)
output, err := YAMLToTerraformResources(r, "", false, false, false)
output, err := YAMLToTerraformResources(r, "", false, false, false, false)

if err != nil {
t.Fatal("Converting to HCL failed:", err)
Expand Down Expand Up @@ -192,7 +227,7 @@ items:
`

r := strings.NewReader(yaml)
output, err := YAMLToTerraformResources(r, "", false, false, false)
output, err := YAMLToTerraformResources(r, "", false, false, false, false)

if err != nil {
t.Fatal("Converting to HCL failed:", err)
Expand Down Expand Up @@ -252,7 +287,7 @@ data:
TEST: test`

r := strings.NewReader(yaml)
output, err := YAMLToTerraformResources(r, "kubernetes-alpha", false, false, false)
output, err := YAMLToTerraformResources(r, "kubernetes-alpha", false, false, false, false)

if err != nil {
t.Fatal("Converting to HCL failed:", err)
Expand Down Expand Up @@ -297,7 +332,7 @@ metadata:
- test`

r := strings.NewReader(yaml)
output, err := YAMLToTerraformResources(r, "", true, false, false)
output, err := YAMLToTerraformResources(r, "", true, false, false, false)

if err != nil {
t.Fatal("Converting to HCL failed:", err)
Expand Down Expand Up @@ -334,7 +369,7 @@ metadata:
uid: bea6500b-0637-4d2d-b726-e0bda0b595dd`

r := strings.NewReader(yaml)
output, err := YAMLToTerraformResources(r, "", true, true, false)
output, err := YAMLToTerraformResources(r, "", true, true, false, false)

if err != nil {
t.Fatal("Converting to HCL failed:", err)
Expand Down Expand Up @@ -381,7 +416,7 @@ metadata:
uid: bea6500b-0637-4d2d-b726-e0bda0b595dd`

r := strings.NewReader(yaml)
output, err := YAMLToTerraformResources(r, "", true, false, false)
output, err := YAMLToTerraformResources(r, "", true, false, false, false)

if err != nil {
t.Fatal("Converting to HCL failed:", err)
Expand Down