Kubeconf builder to return single cluster kubeconf

Now if clusterName is specified for kubebuilder, Build() method
will return kubeconfig containing only context for that cluster.
If no clusterName is specified kubeconfig will have contexts of
all clusters that builder can build. This behaviour is similar
to `kubeconfig get` command.

Relates-To: #460

Change-Id: Ib3bebf61bc60430d347ded41b2e31249b11126eb
This commit is contained in:
Kostiantyn Kalynovskyi 2021-03-09 18:11:00 +00:00
parent 442f9965fb
commit e2d2607586
3 changed files with 27 additions and 16 deletions

View File

@ -97,8 +97,29 @@ func (b *Builder) Build() Interface {
}
func (b *Builder) build() ([]byte, error) {
// Set current context to clustername if it was provided
var result *api.Config
var err error
var kubeContext string
if b.clusterName != "" {
kubeContext, result, err = b.buildOne(b.clusterName)
if err != nil {
return nil, err
}
} else {
result, err = b.builtSiteKubeconf()
if err != nil {
return nil, err
}
}
b.siteKubeconf.CurrentContext = kubeContext
return clientcmd.Write(*result)
}
func (b *Builder) builtSiteKubeconf() (*api.Config, error) {
log.Debugf("Getting site kubeconfig")
for _, clusterID := range b.clusterMap.AllClusters() {
log.Printf("Getting kubeconfig for cluster '%s'", clusterID)
log.Debugf("Getting kubeconfig for cluster '%s' to build site kubeconfig", clusterID)
// buildOne merges context into site kubeconfig
_, _, err := b.buildOne(clusterID)
if IsErrAllSourcesFailedErr(err) {
@ -109,15 +130,7 @@ func (b *Builder) build() ([]byte, error) {
return nil, err
}
}
// Set current context to clustername if it was provided
if b.clusterName != "" {
kubeContext, err := b.clusterMap.ClusterKubeconfigContext(b.clusterName)
if err != nil {
return nil, err
}
b.siteKubeconf.CurrentContext = kubeContext
}
return clientcmd.Write(*b.siteKubeconf)
return b.siteKubeconf, nil
}
func (b *Builder) buildOne(clusterID string) (string, *api.Config, error) {

View File

@ -100,11 +100,10 @@ func TestBuilderClusterctl(t *testing.T) {
fs fs.FileSystem
}{
{
name: "success cluster-api not reachable",
requestedClusterName: childClusterID,
expectedContexts: []string{parentClusterID},
expectedClusters: []string{parentParentCluster},
expectedAuthInfos: []string{parentParentUser},
name: "success cluster-api not reachable",
expectedContexts: []string{parentClusterID},
expectedClusters: []string{parentParentCluster},
expectedAuthInfos: []string{parentParentUser},
clusterMap: clustermap.NewClusterMap(&v1alpha1.ClusterMap{
Map: map[string]*v1alpha1.Cluster{
childClusterID: {

View File

@ -102,7 +102,6 @@ func (p *phase) Executor() (ifc.Executor, error) {
kubeconf := kubeconfig.NewBuilder().
WithBundle(p.helper.PhaseBundleRoot()).
WithClusterMap(cMap).
WithClusterName(p.apiObj.ClusterName).
WithTempRoot(wd).
WithClusterctClient(cctlClient).
Build()