I'm trying to create an AWS policy to grant the kms:CreateKey
permission to a principal. I'm having trouble defining the Resource part of the policy.
By reading the docs I found out that I can specify something like this:
arn:AWS_partition_name:kms:AWS_region:AWS_account_ID:*
instead of the regular *
.
My question is, how can I achieve this using the Python CDK?
You can create an IAM policy like this:
iam.PolicyStatement(
# effect is optional. It can be DENY or ALLOW, and it defaults to ALLOW
effect=iam.Effect.ALLOW,
# Specifies a list of actions this principal is allowed/denied to call.
actions=[
# Specify a specific action
'kms:CreateKey',
# Or, you can specify all actions of a specific service:
'kms:*',
],
# Resources this principal can act on.
resources=[
# All keys in your account, in your region
'arn:aws:kms:<YOUR REGION>:<YOUR ACCOUNT ID>:key/*',
# All aliases in your account, in your region
'arn:aws:kms:<YOUR REGION>:<YOUR ACCOUNT ID>:alias/*',
],
)
I very highly recommend playing around in the interactive IAM Policy editor , which gives a fantastic view of all required/possible things you can do when creating a policy, including advanced ARN composition.
You can do it by using predefined env variables in Python related to AWS CLI/AWS CDK. in this case you can do it in a following way:
arn = f"arn:AWS_partition_name:kms:{os.getenv('CDK_DEFAULT_REGION')}:{os.getenv('CDK_DEFAULT_ACCOUNT')}:*"
here is the full picture how to add it role:
role = _iam.Role(self, "lambda_emr_launcher_role",
role_name="_trackit-emr-launcher-role",
description="Service role for self-titled Lamdbda",
assumed_by=_iam.ServicePrincipal("lambda.amazonaws.com"),
managed_policies=[_iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AWSLambdaBasicExecutionRole")],
inline_policies={
"Policy_KMS": _iam.PolicyDocument(statements=[
_iam.PolicyStatement(effect=_iam.Effect.ALLOW,
principals=["principal_example1"],
resources=[f"arn:AWS_partition_name:kms:{os.getenv('CDK_DEFAULT_REGION')}:{os.getenv('CDK_DEFAULT_ACCOUNT')}:*"],
actions=["kms:CreateKey"])])})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.