Skip to content

Commit

Permalink
adding working tree for debugging purposes
Browse files Browse the repository at this point in the history
  • Loading branch information
JaylonmcShan03 committed Jul 22, 2024
1 parent a1c1f54 commit b62987a
Show file tree
Hide file tree
Showing 13 changed files with 1,421 additions and 1,049 deletions.

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion helm-framework/helm/data_template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func TestAccDataTemplate_basic(t *testing.T) {
datasourceAddress := fmt.Sprintf("data.helm_template.%s", testResourceName)

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
//PreCheck: func() { testAccPreCheck(t) },
ProtoV6ProviderFactories: protoV6ProviderFactories(),
Steps: []resource.TestStep{{
Config: testAccDataHelmTemplateConfigBasic(testResourceName, namespace, name, "1.2.3"),
Expand Down
225 changes: 186 additions & 39 deletions helm-framework/helm/kubeConfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ package helm

import (
"context"
"fmt"
"os"
"path/filepath"
"sync"

"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"

//"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/mitchellh/go-homedir"
"k8s.io/apimachinery/pkg/api/meta"
Expand All @@ -17,7 +20,7 @@ import (
"k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
//clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)

// Struct holding k8s client config, burst limit for api requests, and mutex for sync
Expand All @@ -29,7 +32,7 @@ type KubeConfig struct {

// Converting KubeConfig to a REST config, which will be used to create k8s clients
func (k *KubeConfig) ToRESTConfig() (*rest.Config, error) {
config, err := k.ClientConfig.ClientConfig()
config, err := k.ToRawKubeConfigLoader().ClientConfig()
return config, err
}

Expand Down Expand Up @@ -64,25 +67,64 @@ func (k *KubeConfig) ToRawKubeConfigLoader() clientcmd.ClientConfig {
}

// Generates a k8s client config, based on providers settings and namespace, which this config will be used to interact with the k8s cluster
func (m *Meta) newKubeConfig(ctx context.Context, namespace string) (*KubeConfig, error) {
func (m *Meta) NewKubeConfig(ctx context.Context, namespace string) (*KubeConfig, error) {
overrides := &clientcmd.ConfigOverrides{}
loader := &clientcmd.ClientConfigLoadingRules{}
configPaths := []string{}
if v := m.Data.Kubernetes.ConfigPath.ValueString(); v != "" {
configPaths = []string{v}
} else if !m.Data.Kubernetes.ConfigPaths.IsNull() {
configPaths = expandStringSlice(m.Data.Kubernetes.ConfigPaths.Elements())
} else if v := os.Getenv("KUBE_CONFIG_PATHS"); v != "" {
configPaths = filepath.SplitList(v)
if m == nil || m.Data == nil || m.Data.Kubernetes.IsNull() || m.Data.Kubernetes.IsUnknown() {
fmt.Println("Debug - One or more structural elements are nil")
return nil, fmt.Errorf("configuration error: missing required structural data")
}

// Extract the first element from the Kubernetes list
var kubernetesConfig KubernetesConfigModel
var kubernetesConfigs []KubernetesConfigModel
// TODO look into this next
diags := m.Data.Kubernetes.ElementsAs(ctx, &kubernetesConfigs, true)
if diags.HasError() {
fmt.Println("Error extracting Kubernetes config", diags[0])
return nil, fmt.Errorf("configuration error: unable to extract Kubernetes config %#v", diags[0])
}
if len(kubernetesConfigs) > 0 {
kubernetesConfig = kubernetesConfigs[0]
}

// Check ConfigPath
tflog.Debug(ctx, "Debug - m.Data.Kubernetes", map[string]interface{}{"Kubernetes": m.Data.Kubernetes})
if !kubernetesConfig.ConfigPath.IsNull() {
if v := kubernetesConfig.ConfigPath.ValueString(); v != "" {
configPaths = []string{v}
fmt.Println("Debug - ConfigPath:", kubernetesConfig.ConfigPath.ValueString())
tflog.Debug(ctx, "Debug - ConfigPath", map[string]interface{}{"ConfigPath": kubernetesConfig.ConfigPath.ValueString()})
}
}
if !kubernetesConfig.ConfigPaths.IsNull() {
additionalPaths := expandStringSlice(kubernetesConfig.ConfigPaths.Elements())
configPaths = append(configPaths, additionalPaths...)
}
if v := os.Getenv("KUBE_CONFIG_PATHS"); v != "" {
configPaths = filepath.SplitList(v)
}
fmt.Println("Initial configPaths:", configPaths)
tflog.Debug(ctx, "Initial configPaths", map[string]interface{}{"configPaths": configPaths})
fmt.Println("Debug - loader struct1:", loader)
if len(configPaths) > 0 {
fmt.Println("Processing config paths:", configPaths)
tflog.Debug(ctx, "Processing config paths", map[string]interface{}{
"configPaths": configPaths,
})
expandedPaths := []string{}
for _, p := range configPaths {
path, err := homedir.Expand(p)
if err != nil {
fmt.Println("Error expanding home directory:", p, "Error:", err)
tflog.Error(ctx, "Error expanding home directory", map[string]interface{}{
"path": p,
"error": err,
})
return nil, err
}
fmt.Println("Using kubeconfig path:", path)
tflog.Debug(ctx, "Using kubeconfig", map[string]interface{}{
"path": path,
})
Expand All @@ -93,60 +135,165 @@ func (m *Meta) newKubeConfig(ctx context.Context, namespace string) (*KubeConfig
} else {
loader.Precedence = expandedPaths
}
tflog.Debug(ctx, "Debug - loader struct2", map[string]interface{}{
"loader": loader,
})

overrides.CurrentContext = m.Data.Kubernetes.ConfigContext.ValueString()
overrides.Context.AuthInfo = m.Data.Kubernetes.ConfigContextAuthInfo.ValueString()
overrides.Context.Cluster = m.Data.Kubernetes.ConfigContextCluster.ValueString()

// Check ConfigContext
if !kubernetesConfig.ConfigContext.IsNull() {
overrides.CurrentContext = kubernetesConfig.ConfigContext.ValueString()
fmt.Println("Setting config context:", overrides.CurrentContext)
tflog.Debug(ctx, "Setting config context", map[string]interface{}{
"configContext": overrides.CurrentContext,
})
}
if !kubernetesConfig.ConfigContextAuthInfo.IsNull() {
overrides.Context.AuthInfo = kubernetesConfig.ConfigContextAuthInfo.ValueString()
fmt.Println("Setting config context auth info:", overrides.Context.AuthInfo)
tflog.Debug(ctx, "Setting config context auth info", map[string]interface{}{
"configContextAuthInfo": overrides.Context.AuthInfo,
})
}
if !kubernetesConfig.ConfigContextCluster.IsNull() {
overrides.Context.Cluster = kubernetesConfig.ConfigContextCluster.ValueString()
fmt.Println("Setting config context cluster:", overrides.Context.Cluster)
tflog.Debug(ctx, "Setting config context cluster", map[string]interface{}{
"configContextCluster": overrides.Context.Cluster,
})
}
}
overrides.ClusterInfo.InsecureSkipTLSVerify = m.Data.Kubernetes.Insecure.ValueBool()
overrides.ClusterInfo.TLSServerName = m.Data.Kubernetes.TlsServerName.ValueString()
overrides.ClusterInfo.CertificateAuthorityData = []byte(m.Data.Kubernetes.ClusterCaCertificate.ValueString())
overrides.AuthInfo.ClientCertificateData = []byte(m.Data.Kubernetes.ClientCertificate.ValueString())

//Sets the k8s api server urls, in considerations to the TLS settings
if v := m.Data.Kubernetes.Host.ValueString(); v != "" {
// Check and assign remaining fields
if !kubernetesConfig.Insecure.IsNull() {
overrides.ClusterInfo.InsecureSkipTLSVerify = kubernetesConfig.Insecure.ValueBool()
fmt.Println("Setting insecure skip TLS verify:", overrides.ClusterInfo.InsecureSkipTLSVerify)
tflog.Debug(ctx, "Setting insecure skip TLS verify", map[string]interface{}{
"insecureSkipTLSVerify": overrides.ClusterInfo.InsecureSkipTLSVerify,
})
}
if !kubernetesConfig.TlsServerName.IsNull() {
overrides.ClusterInfo.TLSServerName = kubernetesConfig.TlsServerName.ValueString()
fmt.Println("Setting TLS server name:", overrides.ClusterInfo.TLSServerName)
tflog.Debug(ctx, "Setting TLS server name", map[string]interface{}{
"tlsServerName": overrides.ClusterInfo.TLSServerName,
})
}
if !kubernetesConfig.ClusterCaCertificate.IsNull() {
overrides.ClusterInfo.CertificateAuthorityData = []byte(kubernetesConfig.ClusterCaCertificate.ValueString())
fmt.Println("Setting cluster CA certificate")
tflog.Debug(ctx, "Setting cluster CA certificate")
}
if !kubernetesConfig.ClientCertificate.IsNull() {
overrides.AuthInfo.ClientCertificateData = []byte(kubernetesConfig.ClientCertificate.ValueString())
fmt.Println("Setting client certificate")
tflog.Debug(ctx, "Setting client certificate")
}
if !kubernetesConfig.Host.IsNull() && kubernetesConfig.Host.ValueString() != "" {
hasCA := len(overrides.ClusterInfo.CertificateAuthorityData) != 0
hasCert := len(overrides.AuthInfo.ClientCertificateData) != 0
defaultTLS := hasCA || hasCert || overrides.ClusterInfo.InsecureSkipTLSVerify
host, _, err := rest.DefaultServerURL(v, "", schema.GroupVersion{}, defaultTLS)
host, _, err := rest.DefaultServerURL(kubernetesConfig.Host.ValueString(), "", schema.GroupVersion{}, defaultTLS)
if err != nil {
fmt.Println("Error setting host:", kubernetesConfig.Host.ValueString(), "Error:", err)
tflog.Error(ctx, "Error setting host", map[string]interface{}{
"host": kubernetesConfig.Host.ValueString(),
"error": err,
})
return nil, err
}
overrides.ClusterInfo.Server = host.String()
fmt.Println("Setting host:", overrides.ClusterInfo.Server)
tflog.Debug(ctx, "Setting host", map[string]interface{}{
"host": overrides.ClusterInfo.Server,
})
}
overrides.AuthInfo.Username = m.Data.Kubernetes.Username.ValueString()
overrides.AuthInfo.Password = m.Data.Kubernetes.Password.ValueString()
overrides.AuthInfo.ClientKeyData = []byte(m.Data.Kubernetes.ClientKey.ValueString())
overrides.AuthInfo.Token = m.Data.Kubernetes.Token.ValueString()
overrides.ClusterDefaults.ProxyURL = m.Data.Kubernetes.ProxyUrl.ValueString()

if v := m.Data.Kubernetes.Exec; v != nil {
args := v.Args.Elements()
env := v.Env.Elements()

exec := &clientcmdapi.ExecConfig{
APIVersion: v.ApiVersion.ValueString(),
Command: v.Command.ValueString(),
Args: expandStringSlice(args),
}
for k, v := range env {
exec.Env = append(exec.Env, clientcmdapi.ExecEnvVar{Name: k, Value: v.(types.String).ValueString()})
}
overrides.AuthInfo.Exec = exec
if !kubernetesConfig.Username.IsNull() {
overrides.AuthInfo.Username = kubernetesConfig.Username.ValueString()
fmt.Println("Setting username:", overrides.AuthInfo.Username)
tflog.Debug(ctx, "Setting username", map[string]interface{}{
"username": overrides.AuthInfo.Username,
})
}
if !kubernetesConfig.Password.IsNull() {
overrides.AuthInfo.Password = kubernetesConfig.Password.ValueString()
fmt.Println("Setting password")
tflog.Debug(ctx, "Setting password")
}
if !kubernetesConfig.ClientKey.IsNull() {
overrides.AuthInfo.ClientKeyData = []byte(kubernetesConfig.ClientKey.ValueString())
fmt.Println("Setting client key")
tflog.Debug(ctx, "Setting client key")
}
if !kubernetesConfig.Token.IsNull() {
overrides.AuthInfo.Token = kubernetesConfig.Token.ValueString()
fmt.Println("Setting token:", overrides.AuthInfo.Token)
tflog.Debug(ctx, "Setting token", map[string]interface{}{
"token": overrides.AuthInfo.Token,
})
}
if !kubernetesConfig.ProxyUrl.IsNull() {
overrides.ClusterDefaults.ProxyURL = kubernetesConfig.ProxyUrl.ValueString()
fmt.Println("Setting proxy URL:", overrides.ClusterDefaults.ProxyURL)
tflog.Debug(ctx, "Setting proxy URL", map[string]interface{}{
"proxyURL": overrides.ClusterDefaults.ProxyURL,
})
}

// Extract the first element from the Exec list
// var execConfig *ExecConfigModel
// if !kubernetesConfig.Exec.IsUnknown() {
// var execConfigs []ExecConfigModel
// diags := kubernetesConfig.Exec.ElementsAs(ctx, &execConfigs, false)
// if diags.HasError() {
// fmt.Println("Error extracting Exec config")
// return nil, fmt.Errorf("configuration error: unable to extract Exec config")
// }
// if len(execConfigs) > 0 {
// execConfig = &execConfigs[0]
// }
// }

// if execConfig != nil {
// args := execConfig.Args.Elements()
// env := execConfig.Env.Elements()

// exec := &clientcmdapi.ExecConfig{
// APIVersion: execConfig.ApiVersion.ValueString(),
// Command: execConfig.Command.ValueString(),
// Args: expandStringSlice(args),
// }
// for k, v := range env {
// exec.Env = append(exec.Env, clientcmdapi.ExecEnvVar{Name: k, Value: v.(basetypes.StringValue).ValueString()})
// }
// overrides.AuthInfo.Exec = exec
// fmt.Println("Setting exec configuration:", exec)
// tflog.Debug(ctx, "Setting exec configuration", map[string]interface{}{
// "execConfig": exec,
// })
// }

overrides.Context.Namespace = "default"
if namespace != "" {
overrides.Context.Namespace = namespace
fmt.Println("Setting namespace:", overrides.Context.Namespace)
tflog.Debug(ctx, "Setting namespace", map[string]interface{}{
"namespace": overrides.Context.Namespace,
})
}

// Creating the k8s client config, using the loaded and overrides.
burstLimit := int(m.Data.BurstLimit.ValueInt64())
client := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loader, overrides)
if client == nil {
fmt.Println("Failed to initialize kubernetes config")
tflog.Error(ctx, "Failed to initialize kubernetes config")
return nil, nil
return nil, fmt.Errorf("failed to initialize kubernetes config")
}
fmt.Println("Successfully initialized kubernetes config")
tflog.Info(ctx, "Successfully initialized kubernetes config")
fmt.Printf("ClientConfig: %+v\n", client)
fmt.Printf("BurstLimit: %d\n", burstLimit)
return &KubeConfig{ClientConfig: client, Burst: burstLimit}, nil
}

Expand Down
Loading

0 comments on commit b62987a

Please sign in to comment.