agent: |
p4r1jjCNaqoP2IR7xMcDCreate AWS IAM Role for EKS Worker nodes
Create AWS IAM Role for EKS Worker nodes
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
inputs
outputs
import boto3
import time
# Initialize session and IAM client
session = boto3.Session(
aws_access_key_id=getEnvVar('AWS_ACCESS_KEY_ID'),
aws_secret_access_key=getEnvVar('AWS_SECRET_ACCESS_KEY')
)
iam_client = session.client('iam')
# Set role and instance profile names
#worker_role_name = "EKSWORKERNODEROLE"
instance_profile_name = worker_role_name + "-InstanceProfile"
# 1. Trust policy so EC2 instances can assume the role
trust_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"ec2.amazonaws.com",
"eks.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
# 2. Create the IAM role
try:
role_response = iam_client.create_role(
RoleName=worker_role_name,
AssumeRolePolicyDocument=json.dumps(trust_policy),
Description="EKS Worker Node Role"
)
print(f" Created role: {worker_role_name}")
except iam_client.exceptions.EntityAlreadyExistsException:
print(f" Role {worker_role_name} already exists.")
role_response = iam_client.get_role(RoleName=worker_role_name)
role_arn = role_response['Role']['Arn']
# 3. Attach required managed policies
managed_policies = [
"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",
"arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy",
"arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy"
]
for policy_arn in managed_policies:
iam_client.attach_role_policy(RoleName=worker_role_name, PolicyArn=policy_arn)
print(f" Attached policy: {policy_arn}")
# 4. Create instance profile and attach role
try:
iam_client.create_instance_profile(InstanceProfileName=instance_profile_name)
print(f" Created instance profile: {instance_profile_name}")
except iam_client.exceptions.EntityAlreadyExistsException:
print(f" Instance profile {instance_profile_name} already exists.")
# Add role to instance profile (wait to ensure profile is ready)
time.sleep(5)
try:
iam_client.add_role_to_instance_profile(
InstanceProfileName=instance_profile_name,
RoleName=worker_role_name
)
print(f" Added role to instance profile.")
except iam_client.exceptions.LimitExceededException:
print(" Role already associated with instance profile.")
# Final output
print(f" Role ARN: {role_arn}")
worker_role_arn = role_arn
copied