Files
kubevela/references/appfile/addon.go
AshvinBambhaniya2003 10b45d3a8f Fix(references/appfile): Fix namespace check and Terraform output parsing (#6915)
* fix(references/appfile): correct namespace existence check in addon

The `generateSecretFromTerraformOutput` function was using an incorrect logic to check for namespace existence. It was trying to create the namespace and if it succeeded, it would return an error.

This commit corrects the logic to use `k8sClient.Get` and checks for a `NotFound` error to accurately determine if the namespace exists.

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

* fix(references/appfile): make terraform output parsing robust

The previous implementation for parsing `terraform output` was fragile and could lead to data corruption or errors. It would incorrectly remove all spaces from values and would fail to parse values that contained an equals sign.

This commit refactors the parsing logic to be more robust:
- It no longer removes spaces from output values, preserving them correctly.
- It correctly parses `key=value` pairs by splitting only on the first equals sign in a line.
- It properly handles quoted string values from Terraform.

The corresponding tests in `addon_test.go` have been updated to align with the refactored function signature and verify the new, robust behavior.

Fixes #6916

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>

---------

Signed-off-by: Ashvin Bambhaniya <ashvin.bambhaniya@improwised.com>
2025-10-06 11:57:37 -07:00

208 lines
6.3 KiB
Go

/*
Copyright 2021 The KubeVela Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package appfile
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
commontypes "github.com/oam-dev/kubevela/apis/core.oam.dev/common"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/cue/process"
util2 "github.com/oam-dev/kubevela/pkg/oam/util"
"github.com/oam-dev/kubevela/pkg/utils/common"
"github.com/oam-dev/kubevela/pkg/utils/util"
)
const (
// TerraformBaseLocation is the base directory to store all Terraform JSON files
TerraformBaseLocation = ".vela/terraform/"
// TerraformLog is the logfile name for terraform
TerraformLog = "terraform.log"
)
// ApplyTerraform deploys addon resources
func ApplyTerraform(app *v1beta1.Application, k8sClient client.Client, ioStream util.IOStreams, namespace string, _ common.Args) ([]commontypes.ApplicationComponent, error) {
// TODO(zzxwill) Need to check whether authentication credentials of a specific cloud provider are exported as environment variables, like `ALICLOUD_ACCESS_KEY`
var nativeVelaComponents []commontypes.ApplicationComponent
// parse template
appParser := appfile.NewApplicationParser(k8sClient)
ctx := util2.SetNamespaceInCtx(context.Background(), namespace)
appFile, err := appParser.GenerateAppFile(ctx, app)
if err != nil {
return nil, fmt.Errorf("failed to parse appfile: %w", err)
}
if appFile == nil {
return nil, fmt.Errorf("failed to parse appfile")
}
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
for i, wl := range appFile.ParsedComponents {
switch wl.CapabilityCategory {
case types.TerraformCategory:
name := wl.Name
ioStream.Infof("\nApplying cloud resources %s\n", name)
tf, err := getTerraformJSONFiles(wl, appfile.GenerateContextDataFromAppFile(appFile, wl.Name))
if err != nil {
return nil, fmt.Errorf("failed to get Terraform JSON files from workload %s: %w", name, err)
}
tfJSONDir := filepath.Join(TerraformBaseLocation, name)
if _, err = os.Stat(tfJSONDir); err != nil && os.IsNotExist(err) {
if err = os.MkdirAll(tfJSONDir, 0750); err != nil {
return nil, fmt.Errorf("failed to create directory for %s: %w", tfJSONDir, err)
}
}
if err := os.WriteFile(filepath.Join(tfJSONDir, "main.tf.json"), tf, 0600); err != nil {
return nil, fmt.Errorf("failed to convert Terraform template: %w", err)
}
outputs, err := callTerraform(tfJSONDir)
if err != nil {
return nil, err
}
if err := os.Chdir(cwd); err != nil {
return nil, err
}
if err := generateSecretFromTerraformOutput(k8sClient, string(outputs), name, namespace); err != nil {
return nil, err
}
default:
nativeVelaComponents = append(nativeVelaComponents, app.Spec.Components[i])
}
}
return nativeVelaComponents, nil
}
func callTerraform(tfJSONDir string) ([]byte, error) {
if err := os.Chdir(tfJSONDir); err != nil {
return nil, err
}
var cmd *exec.Cmd
cmd = exec.Command("bash", "-c", "terraform init")
if err := common.RealtimePrintCommandOutput(cmd, TerraformLog); err != nil {
return nil, err
}
cmd = exec.Command("bash", "-c", "terraform apply --auto-approve")
if err := common.RealtimePrintCommandOutput(cmd, TerraformLog); err != nil {
return nil, err
}
// Get output from Terraform
cmd = exec.Command("bash", "-c", "terraform output")
outputs, err := cmd.Output()
if err != nil {
return nil, err
}
return outputs, nil
}
// generateSecretFromTerraformOutput generates secret from Terraform output
func generateSecretFromTerraformOutput(k8sClient client.Client, rawOutput string, name, namespace string) error {
ctx := context.TODO()
// Check if namespace exists
var ns v1.Namespace
if err := k8sClient.Get(ctx, client.ObjectKey{Name: namespace}, &ns); err != nil {
if errors.IsNotFound(err) {
return fmt.Errorf("namespace %s doesn't exist", namespace)
}
return fmt.Errorf("failed to get namespace %s: %w", namespace, err)
}
var cmData = make(map[string]string)
outputList := strings.Split(rawOutput, "\n")
for _, i := range outputList {
if strings.TrimSpace(i) == "" {
continue
}
line := strings.SplitN(i, "=", 2)
if len(line) != 2 {
return fmt.Errorf("terraform output isn't in the right format: %q", i)
}
k := strings.TrimSpace(line[0])
// Terraform string outputs are quoted, remove them.
v := strings.Trim(strings.TrimSpace(line[1]), "\"")
if k != "" {
cmData[k] = v
}
}
objectKey := client.ObjectKey{
Namespace: namespace,
Name: name,
}
var secret v1.Secret
if err := k8sClient.Get(ctx, objectKey, &secret); err != nil && !errors.IsNotFound(err) {
return fmt.Errorf("retrieving the secret from cloud resource %s hit an issue: %w", name, err)
} else if err == nil {
if err := k8sClient.Delete(ctx, &secret); err != nil {
return fmt.Errorf("failed to store cloud resource %s output to secret: %w", name, err)
}
}
secret = v1.Secret{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Secret",
},
ObjectMeta: metav1.ObjectMeta{
Namespace: namespace,
Name: name,
},
StringData: cmData,
}
if err := k8sClient.Create(ctx, &secret); err != nil {
return fmt.Errorf("failed to store cloud resource %s output to secret: %w", name, err)
}
return nil
}
// getTerraformJSONFiles gets Terraform JSON files or modules from workload
func getTerraformJSONFiles(comp *appfile.Component, ctxData process.ContextData) ([]byte, error) {
pCtx, err := appfile.PrepareProcessContext(comp, ctxData)
if err != nil {
return nil, err
}
base, _ := pCtx.Output()
tf, err := base.Compile()
if err != nil {
return nil, err
}
return tf, nil
}