Reputation: 1016
For the sake of the automation, I want my IAM policies to be generic.
I am aware that ${aws:username}
fetches username of the policy to whom it is applied to.
Is it possible to do the same for AWS Account number arn:aws:iam::1234567890:user/${aws:username}
with something like this arn:aws:iam::${aws:accountnumber}:user/${aws:username}
inside an IAM policy.
Edited: Allowed variables are listed in the document linked below. https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html
Upvotes: 8
Views: 8648
Reputation: 293
It is possible to test the principal making the request using the ${AWS:PrincipalAccount}
variable. For example, say you have an S3 bucket which stores data for many accounts, and each data object is prefixed with the account ID; you could grant access to read those objects from the relevant account with this statement in an IAM policy:
{
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::your-bucket/per-account-data/${AWS:PrincipalAccount}/*"
}
Upvotes: 0
Reputation: 1016
AWS IAM Policy Variables does not allow references for AWS Account Names. Hence there is no way to dynamically refer to the account number in the IAM policy.
Upvotes: 10
Reputation: 92
In AWS CDK documentation we find the following predefined variables:
Aws.accountId
Aws.region
Aws.stackName
Therefore, you can use the following variables in cloudformation:
${AWS::Region}
${AWS::AccountId}
${AWS::StackName}
Upvotes: 3
Reputation: 2574
The best way to get account number that I found is via STS. Here's Java code that I use to get the account number that works with credentials from AssumeRole as well,
String awsRegion = Regions.US_EAST_1;
AWSCredentials cred = new BasicAWSCredentials("access_key_id", "secret_key_id");
// AWSCredentials cred = BasicSessionCredentials(sessionCredentials.getAccessKeyId(),sessionCredentials.getSecretAccessKey(), sessionCredentials.getSessionToken());
AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(cred))
.withRegion(awsRegion)
.build();
String awsAccountNumber = stsClient.getCallerIdentity(new GetCallerIdentityRequest())
.getAccount();
Upvotes: 0