I'm trying to itterate over the 'Resource' key to determine if it satisfies a condition.
I have a use case where I have to itterate over each of the resource keys to determine if it's equal to a particular value. Essentially, I am just validating the policy has the correct permissions.
{'Action': ['s3:PutObject', 'kms:GenerateKey'],
'Effect': 'Allow'
'Resource': ['arn:aws:kms:us-west-2:<account_id>:key/*',
'arn:aws:s3:::bucket]}
Is there a way I can iterate over each value in the list for Resource?
So far I have this
for value in policy:
Resource = value['Resource']
for resource in Resources:
if resource == 'arn:aws:s3:::bucket'
return True
However, I just realized this does not work as expected.
CodePudding user response:
You can simply get the array corresponding to 'Response' key in dictionary and iterate over it.
dct = {'Action': ['s3:PutObject', 'kms:GenerateKey'],
'Effect': 'Allow'
'Resource': ['arn:aws:kms:us-west-2:<account_id>:key/*',
'arn:aws:s3:::bucket']}
resource = dct.get('Resource')
for array_element in resource:
# do stuff as you wish with each array_element
CodePudding user response:
I have a feeling you actually want to do this:
bucket_policies = [
each for each in policy
if 'arn:aws:s3:::bucket' in each['Resource']
]
This will get you a list of the policies in policy that has that key in resource.
CodePudding user response:
Are you wanting this:
dct ={'Action': ['s3:PutObject', 'kms:GenerateKey'],'Effect':'Allow',
'Resource': ['arn:aws:kms:us-west-2:<account_id>:key/*','arn:aws:s3:::bucket']}
for r in dct.get('Resource'):
print(r)
Output:
arn:aws:kms:us-west-2:<account_id>:key/*
arn:aws:s3:::bucket
You can use in
and dct.get('Resource')
like below:
>>> print('arn:aws:s3:::bucket' in dct.get('Resource'))
True
>>> print('arn:aws:kms:us-west-2:<account_id>:key/*' in dct.get('Resource'))
True
>>> print('lara lara ' in dct.get('Resource'))
False
CodePudding user response:
Is this what you need:
for value in policy:
Resource = value['Resource']
if 'arn:aws:s3:::bucket' in Resource:
return True
If you still want to iterate through the list:
for value in policy:
Resource = value['Resource']
for resource in Resource:
if resource == 'arn:aws:s3:::bucket':
return True
Pls note the typo in your code: for resource in Resources:
should be for resource in Resource:
You have added extra s in your variable name Resource