During our course of work as cloud infrastructure/DevOps engineers, we will have to manage multiple kubernetes clusters across different AWS accounts.

This article will briefly describe the steps for your to manage your different clusters with ease.

Pre-requisite

AWS CLI Named Profiles

We will need to create Credentials and Config profiles in AWS CLI before we can use the CLI across different AWS accounts. You can refer to the official AWS documentations here (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html).

First, we will create the credentials file in ~/.aws/credentials

[default]
aws_access_key_id=<access key>
aws_secret_access_key=<secret access key>

[account1]
aws_access_key_id=<access key>
aws_secret_access_key=<secret access key>

Next, we will create the config file in ~/.aws/config

[default]
region=ap-southeast-1

[account1]
region=ap-southeast-1

Kubectl Context

We will also need to create context in our kubeconfig file.

apiVersion: v1
kind: Config
preferences: {}

clusters:
- cluster:
    certificate-authority-data: <base64 encoded>
    server: <url>
  name: <name of eks cluster>
- cluster:
    certificate-authority-data: <base64 encoded>
    server: <url>
  name: <name of other eks cluster>

contexts:
- context:
    cluster: first-cluster
    user: first-cluster
  name: first-cluster
- context:
    cluster: second-cluster
    user: second-cluster
  name: second-cluster
  
current-context: first-cluster

users:
- name: first-cluster
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1alpha1
      args:
      - --region
      - ap-southeast-1
      - eks
      - get-token
      - --cluster-name
      - first-cluster
      command: aws
- name: second-cluster
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1alpha1
      args:
      - --region
      - ap-southeast-1
      - eks
      - get-token
      - --cluster-name
      - second-cluster
      command: aws
      env:
      - name: AWS_PROFILE
        value: dev

Check your available contexts

You can check your available contexts with the following command:

~# kubectl config get-contexts
CURRENT   NAME                 CLUSTER              AUTHINFO             NAMESPACE
*        first-cluster    first-cluster    first-cluster
         second-cluster    second-cluster    second-cluster

Change your context

You can change your current context to another cluster by using the following command:

kubectl config use-context <context name>