agent: |
kIYpsCx57bUkSIrNvCSYCreate an IAM role with the necessary permissions for EKS and attach it to the EC2 instances
Create an IAM role with the necessary permissions for EKS and attach it to the EC2 instances
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
This script creates an IAM role with the necessary permissions for EKS and attaches it to EC2 instances.
inputs
outputs
import boto3
import json
# Define role and instance profile names
# role_name = "MyEKSClusterRole"
instance_profile_name = f"{role_name}-InstanceProfile"
# Policy ARNs
eks_cluster_policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
# Custom inline policy
custom_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"iam:ListRoles",
"eks:*"
],
"Resource": "*"
}
]
}
# Updated trust policy for both EC2 and EKS
trust_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"ec2.amazonaws.com",
"eks.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}
# Initialize session and 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')
# Create the IAM Role
role_response = iam_client.create_role(
RoleName=role_name,
AssumeRolePolicyDocument=json.dumps(trust_policy),
Description="EKS Cluster Role with EC2 and EKS trust"
)
role_arn = role_response['Role']['Arn']
# Attach AWS managed policy
iam_client.attach_role_policy(
RoleName=role_name,
PolicyArn=eks_cluster_policy_arn
)
# Attach custom inline policy
iam_client.put_role_policy(
RoleName=role_name,
PolicyName="EKSCustomPolicy",
PolicyDocument=json.dumps(custom_policy_document)
)
# Create instance profile if it doesn't exist
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
iam_client.add_role_to_instance_profile(
InstanceProfileName=instance_profile_name,
RoleName=role_name
)
print('Role ARN:', role_arn)
copied