Vikas Rathore
Vikas Rathore

Reputation: 8821

How can an IAM role assume another IAM role to access an resource

How to assume a role from another role in the same account.

Below is my first IAM role(roleA) to access sagemaker. one statement to allow access to sagemaker and another to allow assumerole.

statement {
    actions = [
      "sagemaker:*",
    ]
    resources = [
      "arn:aws:sagemaker:eu-west-1:1111111111:endpoint/ep",
    ]
  }

statement {
    actions = ["sts:AssumeRole"]

    principals {
      type        = "AWS"
      identifiers = ["*"]
    }
  }

Now I have another IAM in the same AWS account(roleB).

    {
        "Sid": "",
        "Effect": "Allow",
        "Action": "sts:AssumeRole",
        "Resource": "arn:aws:iam::1111111111:role/roleA"
    }

Now I assigned roleB to a Microservice. My understanding is Microservice should have access to sagemaker endpoint ep. But I am getting error that I don't have permission. where I am going wrong?

Upvotes: 0

Views: 1468

Answers (1)

samtoddler
samtoddler

Reputation: 9665

To make this work, you have to do something like the below in your microservice. As @jarmod already explained, you need to use the credentials and create clients.

source_credentials = sts_client.assume_role(
        RoleArn=roleB_ARN,
        RoleSessionName=`session_name`,
    )
dest_sts_client = boto3.client(
    'sts',
    aws_access_key_id=source_credentials.get('Credentials').get('AccessKeyId'),
    aws_secret_access_key=source_credentials.get('Credentials').get('SecretAccessKey'),
    aws_session_token=source_credentials.get('Credentials').get('SessionToken')
)
dest_credentials = sts_client.assume_role(
        RoleArn=roleA_ARN,
        RoleSessionName=`session_name`,
    )

sagemaker_client = boto3.client(
    'sagemaker',
    aws_access_key_id=dest_credentials.get('Credentials').get('AccessKeyId'),
    aws_secret_access_key=dest_credentials.get('Credentials').get('SecretAccessKey'),
    aws_session_token=dest_credentials.get('Credentials').get('SessionToken')
)

AWS STS Role Chaining

Roles terms and concepts

Upvotes: 0

Related Questions