How to require users to set their role_session_name with scp

Viewed 138

Using scp, I would like to require role_session_name to users who assume roles in my organization accounts when running terraform template. The role_session_name value need to be equals to their iam username. I have attached below scp in my organization

    {
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Deny",
      "Action": "sts:AssumeRole",
      "Resource": "*",
      "Condition": {
        "StringNotLike": {
          "sts:RoleSessionName": [
            "${aws:username}"
          ]
        }
      }
    }
  ]
}

Below the ~/.aws/config file content

[profile my_profile]
region = us-west-3
role_arn = arn:aws:iam:ACOUNT_ID:role/role_name
output = json

below provider section of terraform template

provider "aws" {
  shared_credentials = "~/.aws/credentials"
  region  = "eu-west-3"
  profile = "my_profile"
}

Without specifying role_session_name = my_aws_user_name` inside the config file, I am able to run the template without being blocked by the scp.

How to achieve this please ?

Thanks

2 Answers

EDIT

I finally setup an AWS organization to test. The SCP as you now have is working fine. Role is in account A. SCP attached to account B:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Deny",
      "Action": "sts:AssumeRole",
      "Resource": "*",
      "Condition": {
        "StringNotLike": {
          "sts:RoleSessionName": [
            "${aws:username}"
          ]
        }
      }
    }
  ]
}

Using a user in account B, I tried to assume a Role in Account A using a random session name. Got access denied.

>aws sts assume-role --profile accountB --role-arn arn:aws:iam::<account-A>:role/<rolename> --role-session-name abc

An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::<account-B>:user/<username> is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::<account-A>:role/<rolename>

But when I use a session name that is same as my username, I am able to.

>aws sts assume-role --profile accountB --role-arn arn:aws:iam::<account-A>:role/<rolename> --role-session-name username

{
    "Credentials": {
        "AccessKeyId": "xxx",
        "SecretAccessKey": "xxx",
        "SessionToken": "xxx",
        "Expiration": "2022-03-23T10:31:52Z"
    },
    "AssumedRoleUser": {
        "AssumedRoleId": "xxx:username",
        "Arn": "arn:aws:sts::xxx:assumed-role/xxx/yyy"
    }
}

An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam:::user/ is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam:::role/T this issue is your profile account doesnt has permission attach policy for other account, so I give the IAM full access of role then run fine.

Related