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

login-add-eks-cluster-support #1102

Merged
merged 11 commits into from
Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project's packages adheres to [Semantic Versioning](http://semver.org/s

## [Unreleased]

### Added

- Adding `opsctl login` support for EKS clusters.

## [2.40.0] - 2023-08-09

### Added
Expand Down
158 changes: 158 additions & 0 deletions cmd/login/aws.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
package login

import (
"context"
"fmt"

"github.com/giantswarm/k8sclient/v7/pkg/k8sclient"
"github.com/giantswarm/microerror"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
eks "sigs.k8s.io/cluster-api-provider-aws/controlplane/eks/api/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"

"github.com/giantswarm/kubectl-gs/v2/pkg/kubeconfig"
)

type eksClusterConfig struct {
clusterName string
certCA []byte
controlPlaneEndpoint string
filePath string
loginOptions LoginOptions
region string

awsProfileName string
}

// storeWCClientCertCredentials saves the created client certificate credentials into the kubectl config.
func storeWCAWSIAMKubeconfig(k8sConfigAccess clientcmd.ConfigAccess, c eksClusterConfig, mcContextName string) (string, bool, error) {
config, err := k8sConfigAccess.GetStartingConfig()
if err != nil {
return "", false, microerror.Mask(err)
}

if mcContextName == "" {
mcContextName = config.CurrentContext
}
contextName := kubeconfig.GenerateWCAWSIAMKubeContextName(mcContextName, c.clusterName)
userName := fmt.Sprintf("%s-user", contextName)
clusterName := contextName

contextExists := false

{
// Create authenticated user.
user, exists := config.AuthInfos[userName]
if !exists {
user = clientcmdapi.NewAuthInfo()
}

user.Exec = &clientcmdapi.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1beta1",
Command: "aws",
Args: []string{"--region", c.region, "eks", "get-token", "--cluster-name", c.clusterName, "--output", "json"},
}

if c.awsProfileName != "" {
user.Exec.Env = []clientcmdapi.ExecEnvVar{
{
Name: "AWS_PROFILE",
Value: c.awsProfileName,
},
}
}
// Add user information to config.
config.AuthInfos[userName] = user
}

{
// Create authenticated cluster.
cluster, exists := config.Clusters[clusterName]
if !exists {
cluster = clientcmdapi.NewCluster()
}

cluster.Server = c.controlPlaneEndpoint
cluster.CertificateAuthority = ""
cluster.CertificateAuthorityData = c.certCA

// Add cluster configuration to config.
config.Clusters[clusterName] = cluster
}

{
// Create authenticated context.
var context *clientcmdapi.Context
context, contextExists = config.Contexts[contextName]
if !contextExists {
context = clientcmdapi.NewContext()
}

context.Cluster = clusterName
context.AuthInfo = userName

// Add context configuration to config.
config.Contexts[contextName] = context

// Select newly created context as current or revert to origin context if that is desired
if c.loginOptions.switchToWCContext {
config.CurrentContext = contextName
} else if c.loginOptions.originContext != "" {
config.CurrentContext = c.loginOptions.originContext
}
}

err = clientcmd.ModifyConfig(k8sConfigAccess, *config, false)
if err != nil {
return "", contextExists, microerror.Mask(err)
}

return contextName, contextExists, nil
}

type kubeconfigFile struct {
Clusters []kubeCluster `json:"clusters"`
}

type kubeCluster struct {
Cluster kubeClusterSpec `json:"cluster"`
}

type kubeClusterSpec struct {
CertificateAuthorityData []byte `json:"certificate-authority-data"`
}

func fetchEKSCAData(ctx context.Context, c k8sclient.Interface, clusterName string, clusterNamespace string) ([]byte, error) {
var secret v1.Secret
err := c.CtrlClient().Get(ctx, client.ObjectKey{Name: eksKubeconfigSecretName(clusterName), Namespace: clusterNamespace}, &secret)
if err != nil {
return nil, microerror.Mask(err)
}

secretData := secret.Data["value"]

kConfig := &kubeconfigFile{}

err = yaml.Unmarshal(secretData, kConfig)
if err != nil {
return nil, microerror.Mask(err)
}
return kConfig.Clusters[0].Cluster.CertificateAuthorityData, err
}

func fetchEKSRegion(ctx context.Context, c k8sclient.Interface, clusterName string, clusterNamespace string) (string, error) {
var eksCluster eks.AWSManagedControlPlane
err := c.CtrlClient().Get(ctx, client.ObjectKey{Name: clusterName, Namespace: clusterNamespace}, &eksCluster)
if err != nil {
return "", microerror.Mask(err)
}

return eksCluster.Spec.Region, nil
}

func eksKubeconfigSecretName(clusterName string) string {
return fmt.Sprintf("%s-user-kubeconfig", clusterName)
}
4 changes: 2 additions & 2 deletions cmd/login/clientcert.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ func getPrivKey(keyPEM []byte) (*rsa.PrivateKey, error) {
}

// storeWCClientCertCredentials saves the created client certificate credentials into the kubectl config.
func storeWCClientCertCredentials(k8sConfigAccess clientcmd.ConfigAccess, fs afero.Fs, c credentialConfig, mcContextName string) (string, bool, error) {
func storeWCClientCertCredentials(k8sConfigAccess clientcmd.ConfigAccess, c credentialConfig, mcContextName string) (string, bool, error) {
config, err := k8sConfigAccess.GetStartingConfig()
if err != nil {
return "", false, microerror.Mask(err)
Expand Down Expand Up @@ -332,7 +332,7 @@ func storeWCClientCertCredentials(k8sConfigAccess clientcmd.ConfigAccess, fs afe
config.Contexts[contextName] = context

// Select newly created context as current or revert to origin context if that is desired
if c.loginOptions.switchToClientCertContext {
if c.loginOptions.switchToWCContext {
config.CurrentContext = contextName
} else if c.loginOptions.originContext != "" {
config.CurrentContext = c.loginOptions.originContext
Expand Down
2 changes: 1 addition & 1 deletion cmd/login/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (r *runner) loginWithKubeContextName(ctx context.Context, contextName strin

if contextAlreadySelected {
fmt.Fprintf(r.stdout, "Context '%s' is already selected.\n", contextName)
} else if !r.loginOptions.isWCClientCert && r.loginOptions.switchToContext {
} else if r.loginOptions.switchToContext {
fmt.Fprintf(r.stdout, "Switched to context '%s'.\n", contextName)
}

Expand Down
36 changes: 19 additions & 17 deletions cmd/login/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ type runner struct {
}

type LoginOptions struct {
isWCClientCert bool
selfContained bool
selfContainedClientCert bool
switchToContext bool
switchToClientCertContext bool
originContext string
contextOverride string
selfContained bool
selfContainedWC bool
isWC bool
switchToContext bool
switchToWCContext bool
originContext string
contextOverride string
}

func (r *runner) Run(cmd *cobra.Command, args []string) error {
Expand Down Expand Up @@ -100,9 +100,11 @@ func (r *runner) run(ctx context.Context, cmd *cobra.Command, args []string) err
return microerror.Maskf(invalidConfigError, "Invalid number of arguments.")
}

// Clientcert creation if desired
if r.loginOptions.isWCClientCert {
return r.handleWCClientCert(ctx)
if r.loginOptions.isWC {
err := r.handleWCKubeconfig(ctx)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, the function being called is specifically for handling client certs on a workload cluster. (We are planning to move this to a different command so it'll be helpful to keep the name)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the function for handling clientcert is still there it just moved later to avoid code duplication
https://github.com/giantswarm/kubectl-gs/pull/1102/files#diff-1f160945410f9311805f9b1ff5284e4cbb59cdd8934057db5bd7b3e40049979fR199-R271

if err != nil {
return microerror.Mask(err)
}
}

return nil
Expand Down Expand Up @@ -137,13 +139,13 @@ func (r *runner) setLoginOptions(ctx context.Context, args *[]string) {
shouldSwitchToWCContextInConfig := hasWCNameFlag && !(hasSelfContainedFlag || r.flag.KeepContext)

r.loginOptions = LoginOptions{
originContext: originContext,
contextOverride: contextOverride,
isWCClientCert: hasWCNameFlag,
selfContained: hasSelfContainedFlag && !hasWCNameFlag,
selfContainedClientCert: hasSelfContainedFlag && hasWCNameFlag,
switchToContext: shouldSwitchContextInConfig,
switchToClientCertContext: shouldSwitchToWCContextInConfig,
originContext: originContext,
contextOverride: contextOverride,
isWC: hasWCNameFlag,
selfContained: hasSelfContainedFlag && !hasWCNameFlag,
selfContainedWC: hasSelfContainedFlag && hasWCNameFlag,
switchToContext: shouldSwitchContextInConfig,
switchToWCContext: shouldSwitchToWCContextInConfig,
}
}

Expand Down
Loading