https://pulumi.com logo
#aws
Title
# aws
p

polite-ambulance-86642

08/04/2023, 8:41 AM
Hi Guys, am trying to setup eks cluster using pulumi python but getting some error with kubeconfig i am sharing the details below *******************error*******************
Copy code
pulumi:pulumi:Stack (eks-dev):
    /Users/saurabhmishra/Documents/iac/pluang_eks/venv/lib/python3.9/site-packages/urllib3/__init__.py:34: NotOpenSSLWarning: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: <https://github.com/urllib3/urllib3/issues/3020>

    Creating EKS Cluster
    Cluster created: Calling __str__ on an Output[T] is not supported.

    To get the value of an Output[T] as an Output[str] consider:
    1. o.apply(lambda v: f"prefix{v}suffix")

    See <https://www.pulumi.com/docs/concepts/inputs-outputs> for more details.
    This function may throw in a future version of Pulumi.
    error: Program failed with an unhandled exception:
    Traceback (most recent call last):
      File "/opt/homebrew/bin/pulumi-language-python-exec", line 197, in <module>
        loop.run_until_complete(coro)
      File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
        return future.result()
      File "/Users/saurabhmishra/Documents/iac/pluang_eks/venv/lib/python3.9/site-packages/pulumi/runtime/stack.py", line 137, in run_in_stack
        await run_pulumi_func(lambda: Stack(func))
      File "/Users/saurabhmishra/Documents/iac/pluang_eks/venv/lib/python3.9/site-packages/pulumi/runtime/stack.py", line 51, in run_pulumi_func
        await wait_for_rpcs()
      File "/Users/saurabhmishra/Documents/iac/pluang_eks/venv/lib/python3.9/site-packages/pulumi/runtime/stack.py", line 121, in wait_for_rpcs
        raise exception
      File "/Users/saurabhmishra/Documents/iac/pluang_eks/venv/lib/python3.9/site-packages/pulumi/output.py", line 174, in run
        value = await self._future
      File "/Users/saurabhmishra/Documents/iac/pluang_eks/venv/lib/python3.9/site-packages/pulumi/output.py", line 199, in run
        transformed: Input[U] = func(value)
      File "/Users/saurabhmishra/Documents/iac/pluang_eks/venv/lib/python3.9/site-packages/pulumi/output.py", line 263, in lift
        return UNKNOWN if isinstance(v, Unknown) else cast(Any, v)[key]
      File "/Users/saurabhmishra/Documents/iac/pluang_eks/venv/lib/python3.9/site-packages/pulumi_aws/eks/outputs.py", line 380, in __getitem__
        return super().__getitem__(key)
    KeyError: 0
****************************pulumi verion**************************** v3.76.1 ****************************pulumi plugin version **************************** NAME KIND VERSION SIZE INSTALLED LAST USED aws resource 5.42.0 542 MB 2 weeks ago 2 weeks ago kubernetes resource 4.0.3 89 MB 21 hours ago 15 minutes ago ******************************************************************************* I am trying to setup eks cluster by using pulumi python getting above Error KeyError: 0 sharing the code file you as well
Copy code
import pulumi
import pulumi_aws as aws
import pulumi_kubernetes as k8s
import base64

def create_eks_cluster():
    # Replace with your existing VPC ID and subnet IDs
    existing_vpc_id = "vpc-XXXXXXXXX"
    existing_subnet_ids = ["subnet-XXXXXXX", "subnet-XXXXX", "subnet-XXXXX"]

    # Create an IAM role for EKS
    eks_role = aws.iam.Role("eks-cluster-role",
        assume_role_policy="""{
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Action": "sts:AssumeRole",
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "<http://eks.amazonaws.com|eks.amazonaws.com>"
                    }
                }
            ]
        }""",
    )

    # Attach necessary policies to the IAM role
    policy_arns = [
        "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy",
        "arn:aws:iam::aws:policy/AmazonEKSServicePolicy",
    ]
    for policy_arn in policy_arns:
        aws.iam.RolePolicyAttachment(f"eks-cluster-policy-{policy_arn[-10:]}",
            policy_arn=policy_arn,
            role=eks_role,
        )
    # Add debug statement
    <http://pulumi.log.info|pulumi.log.info>("Creating EKS Cluster")
    # Create an Amazon EKS cluster with the existing VPC and subnet IDs
    eks_cluster = aws.eks.Cluster("eks-cluster",
        role_arn=eks_role.arn,
        vpc_config={
            "subnet_ids": existing_subnet_ids,
        },
        tags={
            "Environment": "production",
        },
    )
    # Add another debug statement
    <http://pulumi.log.info|pulumi.log.info>(f"Cluster created: {eks_cluster.arn}")
    # Use apply() to access the values of eks_cluster.endpoint and eks_cluster.certificate_authority
    eks_cluster_endpoint = eks_cluster.endpoint.apply(lambda endpoint: endpoint)
    eks_cluster_certificate_authority = eks_cluster.certificate_authority.apply(lambda ca: ca[0]["data"])

    # Generate the kubeconfig content
    kubeconfig = pulumi.Output.all(eks_cluster_endpoint, eks_cluster_certificate_authority).apply(
        lambda args: generate_kubeconfig(args[0], args[1], eks_cluster.name)
    )



    pulumi.export("kubeconfig", kubeconfig)

    return eks_cluster

def generate_kubeconfig(endpoint, certificate_authority, cluster_name):
    if not endpoint or not certificate_authority or not certificate_authority[0]["data"]:
        return ""

    ca_data_base64 = base64.b64encode(certificate_authority[0]["data"].encode()).decode()
    return f"""
    apiVersion: v1
    clusters:
    - cluster:
        server: {endpoint}
        certificate-authority-data: {ca_data_base64}
      name: kubernetes
    contexts:
    - context:
        cluster: kubernetes
        user: kubernetes-admin
      name: kubernetes-admin@kubernetes
    current-context: kubernetes-admin@kubernetes
    users:
    - name: kubernetes-admin
      user:
        exec:
          apiVersion: <http://client.authentication.k8s.io/v1alpha1|client.authentication.k8s.io/v1alpha1>
          command: aws-iam-authenticator
          args:
          - "token"
          - "-i"
          - "{cluster_name}"
    """

def create_node_group(eks_cluster):
    # Create the worker node IAM role with the necessary policies
    worker_node_role = aws.iam.Role("eks-nodegroup-role",
        assume_role_policy="""{
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Action": "sts:AssumeRole",
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "<http://ec2.amazonaws.com|ec2.amazonaws.com>"
                    }
                }
            ]
        }""",
    )

    # Attach the AmazonEKSWorkerNodePolicy policy
    aws.iam.RolePolicyAttachment("eks-nodegroup-policy",
        policy_arn="arn:aws:iam::aws:policy/AmazonEKSCWorkerNodePolicy",
        role=worker_node_role,
    )

    # Attach the AmazonEKS_CNI_Policy policy
    aws.iam.RolePolicyAttachment("eks-cni-policy",
        policy_arn="arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy",
        role=worker_node_role,
    )

    # Create a Kubernetes node group to run worker nodes
    eks_node_group = aws.eks.NodeGroup("eks-node-group",
        cluster_name=eks_cluster.name,
        node_group_name="example-nodegroup",
        node_role_arn=worker_node_role.arn,
        subnet_ids=eks_cluster.vpc_config[0].subnet_ids,  # Use the same subnets as the EKS cluster
        instance_types=["t3.medium"],  # Replace with your desired instance types
        scaling_config={
            "desired_size": 2,  # Replace with the desired number of nodes
            "max_size": 5,      # Replace with the maximum number of nodes
            "min_size": 1,      # Replace with the minimum number of nodes
        },
    )

    return eks_node_group

# Create the EKS cluster
eks_cluster = create_eks_cluster()

# Create the node group for the EKS cluster
eks_node_group = create_node_group(eks_cluster)
s

stocky-restaurant-98004

08/11/2023, 5:04 PM
Not sure if this is the cause of the issue, but you shouldn't need to call
apply
before
pulumi.Output.all
.
all
is
apply
when you want to wait for multiple values to become available and then do something with the raw values.
I believe that
eks_cluster.name
is also not a raw string - it's probably Input[Str]
2 Views