Automated IAM Policy Attachments for SageMaker Execution Roles
PythonTo automate IAM Policy Attachments for SageMaker Execution Roles, you need to create an IAM Role, define an IAM Policy that grants the permissions SageMaker requires, and then attach this policy to the role. SageMaker execution roles require permissions to access resources like S3 buckets for training data, ECR for Docker images, and more, depending on what services your ML application will interact with.
Pulumi allows you to define these resources in a declarative way using Python, and it takes care of provisioning and managing the cloud resources.
Here's a Pulumi Python program that does the following:
- Creates an IAM Policy with the necessary permissions for SageMaker to access S3.
- Creates an IAM Role for SageMaker services to assume.
- Attaches the policy to the role.
Before you can run this code, make sure you have installed Pulumi and configured it for AWS usage.
import pulumi import pulumi_aws as aws # Define the IAM policy for SageMaker execution that provides necessary permissions. sagemaker_policy = aws.iam.Policy("sagemakerPolicy", policy="""{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": [ "s3:GetObject", "s3:ListBucket", "s3:PutObject" ], "Resource": ["arn:aws:s3:::your-bucket-name/*"] }] }""") # Create an IAM role that SageMaker can assume. sagemaker_role = aws.iam.Role("sagemakerRole", assume_role_policy="""{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {"Service": "sagemaker.amazonaws.com"}, "Action": "sts:AssumeRole" }] }""") # Attach the policy to the role. sagemaker_policy_attachment = aws.iam.RolePolicyAttachment("sagemakerPolicyAttachment", role=sagemaker_role.name, policy_arn=sagemaker_policy.arn) # Export the name of the role and the ARN of the policy as stack outputs. pulumi.export('sagemaker_role_name', sagemaker_role.name) pulumi.export('sagemaker_policy_arn', sagemaker_policy.arn)
Let's walk through what each part of the program does:
- The
sagemaker_policy
is aPolicy
object that defines what actions on which resources are allowed. In this case, it provides access to S3 buckets. Replace'your-bucket-name'
with the actual S3 bucket the SageMaker service will use. - The
sagemaker_role
is anRole
object that defines an IAM role. Theassume_role_policy
specifies that the entity that can assume this role is the SageMaker service. - The
sagemaker_policy_attachment
is aRolePolicyAttachment
object that attaches the policy to the role. - The
pulumi.export
lines are there to output the role name and the policy ARN once the script is run. This can be useful for reference or for passing these values to other Pulumi stacks or scripts.
Remember to replace
'your-bucket-name'
with the S3 bucket name that your SageMaker service will use. Also, you may need to extend the permissions in the IAM policy based on what services and resources your SageMaker model requires access to.