Create EKS pod from another EKS pod

0

I am trying to create a pod from another pod which is running using python script.

When I do this:

# Load the in-cluster config
    config.load_incluster_config()

as well as

# Load the in-cluster config
    config.load_kube_config()

It says no config file found.

So I had to do get_caller_id() to generate bearer token and create my own config.

if not os.path.exists(KUBE_FILEPATH):
    
    kube_content = dict()
    # Get data from EKS API
    eks_api = boto3.client('eks',region_name=REGION)
    cluster_info = eks_api.describe_cluster(name=CLUSTER_NAME)
    certificate = cluster_info['cluster']['certificateAuthority']['data']
    endpoint = cluster_info['cluster']['endpoint']

    # Generating kubeconfig
    kube_content = dict()
    
    kube_content['apiVersion'] = 'v1'
    kube_content['clusters'] = [
        {
        'cluster':
            {
            'server': endpoint,
            'certificate-authority-data': certificate
            },
        'name':'kubernetes'
                
        }]

    kube_content['contexts'] = [
        {
        'context':
            {
            'cluster':'kubernetes',
            'user':'aws'
            },
        'name':'aws'
        }]

    kube_content['current-context'] = 'aws'
    kube_content['Kind'] = 'config'
    kube_content['users'] = [
    {
    'name':'aws',
    'user':'eks'
    }]


    # Write kubeconfig
    with open(KUBE_FILEPATH, 'w') as outfile:
        yaml.dump(kube_content, outfile, default_flow_style=False)

in this case I received error stating that str obj has no attribute as path so I made a change to kube_content['users'] having the value of

user: {
      token: bearer-token
}

This resolved it... Then I did this

config.load_kube_config(KUBE_FILEPATH)
    configuration = client.Configuration().get_default_copy()
    configuration.api_key['authorization'] = token
    configuration.api_key_prefix['authorization'] = 'Bearer'
    # API
    api = client.ApiClient(configuration)
    v1 = client.CoreV1Api(api)

    list_pod_gold(kwargs, v1)

but it says 401 error.... i checked the sa role, it has the necessary permissions...

Is there an easier way to do this? or ways to figure out if the token is failing etc?

1 Answer
0

Hello,

A 401 Unauthorized error indicates that the provided credentials are incorrect or insufficient. Given that you've verified the Service Account's role, the most likely culprits are the token generation or its usage.

I recommend the Service Account approach. It’s widely used and aligns with Kubernetes best practices.

1. Create a Service Account:

First, create a custom Service Account (let’s call it my-service-account) in your Kubernetes namespace. You can do this using a YAML file or directly via the command line:

$kubectl create sa my-service-account

2.Define RBAC Rules:

  • Next, define Role-Based Access Control (RBAC) rules for your Service Account. Create a Role or ClusterRole that specifies the permissions needed by your pods. For example:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: my-role
rules:
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "list"]  # Adjust permissions as needed

3.Bind Service Account to Role:

  • Bind the Service Account (my-service-account) to the Role (my-role) using a RoleBinding or ClusterRoleBinding:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: my-role-binding
subjects:
  - kind: ServiceAccount
    name: my-service-account
    namespace: my-namespace
roleRef:
  kind: Role
  name: my-role
  apiGroup: rbac.authorization.k8s.io

4. Create Your Pod:

  • Now create your new pod (let’s call it my-new-pod) that will use the my-service-account:
apiVersion: v1
kind: Pod
metadata:
  name: my-new-pod
spec:
  serviceAccountName: my-service-account
  containers:
    - name: my-container
      image: my-image

5. Access the Token Inside my-new-pod:

  • The Service Account token is automatically mounted as a file inside the pod at /var/run/secrets/kubernetes.io/serviceaccount/token.
  • Your application inside my-new-pod can read this token and use it for authentication when making requests to the Kubernetes API

Test and Verify:

  • Deploy my-new-pod and verify that it can access the Kubernetes API using the Service Account token.

Follow the link : https://stackoverflow.com/questions/62029424/how-can-i-create-a-new-kubernetes-pod-from-another-existing-pod

profile picture
EXPERT
answered 2 months ago
profile picture
EXPERT
Sandeep
reviewed 2 months ago
  • Even so, i need kubeconfig right, so that I can load it? in that kube config should I pass in the same token? in the kube config plus authorization bearer?

  • Yes, you'll need a kubeconfig file to interact with the Kubernetes API. This file contains information about the cluster, user credentials, and context.

    Example Kubeconfig Structure:

    apiVersion: v1 clusters:

    • cluster: certificate-authority-data: <base64_encoded_ca_cert> server: https://<cluster_endpoint> name: kubernetes contexts:
    • context: cluster: kubernetes user: aws name: aws current-context: aws kind: Config users:
    • name: aws user: token: <your_bearer_token>

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions