How to use list_policy_versions method in localstack

Best Python code snippet using localstack_python

iam_managed_policy.py

Source:iam_managed_policy.py Github

copy

Full Screen

...124 return policy125 return None126def delete_oldest_non_default_version(module, iam, policy):127 try:128 versions = [v for v in iam.list_policy_versions(PolicyArn=policy['Arn'])['Versions']129 if not v['IsDefaultVersion']]130 except botocore.exceptions.ClientError as e:131 module.fail_json(msg="Couldn't list policy versions: %s" % str(e),132 exception=traceback.format_exc(),133 **camel_dict_to_snake_dict(e.response))134 versions.sort(key=lambda v: v['CreateDate'], reverse=True)135 for v in versions[-1:]:136 try:137 iam.delete_policy_version(PolicyArn=policy['Arn'], VersionId=v['VersionId'])138 except botocore.exceptions.ClientError as e:139 module.fail_json(msg="Couldn't delete policy version: %s" % str(e),140 exception=traceback.format_exc(),141 **camel_dict_to_snake_dict(e.response))142# This needs to return policy_version, changed143def get_or_create_policy_version(module, iam, policy, policy_document):144 try:145 versions = iam.list_policy_versions(PolicyArn=policy['Arn'])['Versions']146 except botocore.exceptions.ClientError as e:147 module.fail_json(msg="Couldn't list policy versions: %s" % str(e),148 exception=traceback.format_exc(),149 **camel_dict_to_snake_dict(e.response))150 for v in versions:151 try:152 document = iam.get_policy_version(PolicyArn=policy['Arn'],153 VersionId=v['VersionId'])['PolicyVersion']['Document']154 except botocore.exceptions.ClientError as e:155 module.fail_json(msg="Couldn't get policy version %s: %s" % (v['VersionId'], str(e)),156 exception=traceback.format_exc(),157 **camel_dict_to_snake_dict(e.response))158 # If the current policy matches the existing one159 if not compare_policies(document, json.loads(to_native(policy_document))):160 return v, False161 # No existing version so create one162 # There is a service limit (typically 5) of policy versions.163 #164 # Rather than assume that it is 5, we'll try to create the policy165 # and if that doesn't work, delete the oldest non default policy version166 # and try again.167 try:168 version = iam.create_policy_version(PolicyArn=policy['Arn'], PolicyDocument=policy_document)['PolicyVersion']169 return version, True170 except botocore.exceptions.ClientError as e:171 if e.response['Error']['Code'] == 'LimitExceeded':172 delete_oldest_non_default_version(module, iam, policy)173 try:174 version = iam.create_policy_version(PolicyArn=policy['Arn'], PolicyDocument=policy_document)['PolicyVersion']175 return version, True176 except botocore.exceptions.ClientError as e:177 pass178 # Handle both when the exception isn't LimitExceeded or179 # the second attempt still failed180 module.fail_json(msg="Couldn't create policy version: %s" % str(e),181 exception=traceback.format_exc(),182 **camel_dict_to_snake_dict(e.response))183def set_if_default(module, iam, policy, policy_version, is_default):184 if is_default and not policy_version['IsDefaultVersion']:185 try:186 iam.set_default_policy_version(PolicyArn=policy['Arn'], VersionId=policy_version['VersionId'])187 except botocore.exceptions.ClientError as e:188 module.fail_json(msg="Couldn't set default policy version: %s" % str(e),189 exception=traceback.format_exc(),190 **camel_dict_to_snake_dict(e.response))191 return True192 return False193def set_if_only(module, iam, policy, policy_version, is_only):194 if is_only:195 try:196 versions = [v for v in iam.list_policy_versions(PolicyArn=policy['Arn'])[197 'Versions'] if not v['IsDefaultVersion']]198 except botocore.exceptions.ClientError as e:199 module.fail_json(msg="Couldn't list policy versions: %s" % str(e),200 exception=traceback.format_exc(),201 **camel_dict_to_snake_dict(e.response))202 for v in versions:203 try:204 iam.delete_policy_version(PolicyArn=policy['Arn'], VersionId=v['VersionId'])205 except botocore.exceptions.ClientError as e:206 module.fail_json(msg="Couldn't delete policy version: %s" % str(e),207 exception=traceback.format_exc(),208 **camel_dict_to_snake_dict(e.response))209 return len(versions) > 0210 return False211def detach_all_entities(module, iam, policy, **kwargs):212 try:213 entities = iam.list_entities_for_policy(PolicyArn=policy['Arn'], **kwargs)214 except botocore.exceptions.ClientError as e:215 module.fail_json(msg="Couldn't detach list entities for policy %s: %s" % (policy['PolicyName'], str(e)),216 exception=traceback.format_exc(),217 **camel_dict_to_snake_dict(e.response))218 for g in entities['PolicyGroups']:219 try:220 iam.detach_group_policy(PolicyArn=policy['Arn'], GroupName=g['GroupName'])221 except botocore.exceptions.ClientError as e:222 module.fail_json(msg="Couldn't detach group policy %s: %s" % (g['GroupName'], str(e)),223 exception=traceback.format_exc(),224 **camel_dict_to_snake_dict(e.response))225 for u in entities['PolicyUsers']:226 try:227 iam.detach_user_policy(PolicyArn=policy['Arn'], UserName=u['UserName'])228 except botocore.exceptions.ClientError as e:229 module.fail_json(msg="Couldn't detach user policy %s: %s" % (u['UserName'], str(e)),230 exception=traceback.format_exc(),231 **camel_dict_to_snake_dict(e.response))232 for r in entities['PolicyRoles']:233 try:234 iam.detach_role_policy(PolicyArn=policy['Arn'], RoleName=r['RoleName'])235 except botocore.exceptions.ClientError as e:236 module.fail_json(msg="Couldn't detach role policy %s: %s" % (r['RoleName'], str(e)),237 exception=traceback.format_exc(),238 **camel_dict_to_snake_dict(e.response))239 if entities['IsTruncated']:240 detach_all_entities(module, iam, policy, marker=entities['Marker'])241def main():242 argument_spec = ec2_argument_spec()243 argument_spec.update(dict(244 policy_name=dict(required=True),245 policy_description=dict(default=''),246 policy=dict(type='json'),247 make_default=dict(type='bool', default=True),248 only_version=dict(type='bool', default=False),249 fail_on_delete=dict(type='bool', default=True),250 state=dict(default='present', choices=['present', 'absent']),251 ))252 module = AnsibleModule(253 argument_spec=argument_spec,254 required_if=[['state', 'present', ['policy']]]255 )256 if not HAS_BOTO3:257 module.fail_json(msg='boto3 is required for this module')258 name = module.params.get('policy_name')259 description = module.params.get('policy_description')260 state = module.params.get('state')261 default = module.params.get('make_default')262 only = module.params.get('only_version')263 policy = None264 if module.params.get('policy') is not None:265 policy = json.dumps(json.loads(module.params.get('policy')))266 try:267 region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)268 iam = boto3_conn(module, conn_type='client', resource='iam',269 region=region, endpoint=ec2_url, **aws_connect_kwargs)270 except (botocore.exceptions.NoCredentialsError, botocore.exceptions.ProfileNotFound) as e:271 module.fail_json(msg="Can't authorize connection. Check your credentials and profile.",272 exceptions=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))273 p = get_policy_by_name(module, iam, name)274 if state == 'present':275 if p is None:276 # No Policy so just create one277 try:278 rvalue = iam.create_policy(PolicyName=name, Path='/',279 PolicyDocument=policy, Description=description)280 except Exception as e:281 module.fail_json(msg="Couldn't create policy %s: %s" % (name, to_native(e)),282 exception=traceback.format_exc(),283 **camel_dict_to_snake_dict(e.response))284 module.exit_json(changed=True, policy=camel_dict_to_snake_dict(rvalue['Policy']))285 else:286 policy_version, changed = get_or_create_policy_version(module, iam, p, policy)287 changed = set_if_default(module, iam, p, policy_version, default) or changed288 changed = set_if_only(module, iam, p, policy_version, only) or changed289 # If anything has changed we needto refresh the policy290 if changed:291 try:292 p = iam.get_policy(PolicyArn=p['Arn'])['Policy']293 except Exception as e:294 module.fail_json(msg="Couldn't get policy: %s" % to_native(e),295 exception=traceback.format_exc(),296 **camel_dict_to_snake_dict(e.response))297 module.exit_json(changed=changed, policy=camel_dict_to_snake_dict(p))298 else:299 # Check for existing policy300 if p:301 # Detach policy302 detach_all_entities(module, iam, p)303 # Delete Versions304 try:305 versions = iam.list_policy_versions(PolicyArn=p['Arn'])['Versions']306 except botocore.exceptions.ClientError as e:307 module.fail_json(msg="Couldn't list policy versions: %s" % to_native(e),308 exception=traceback.format_exc(),309 **camel_dict_to_snake_dict(e.response))310 for v in versions:311 if not v['IsDefaultVersion']:312 try:313 iam.delete_policy_version(PolicyArn=p['Arn'], VersionId=v['VersionId'])314 except botocore.exceptions.ClientError as e:315 module.fail_json(msg="Couldn't delete policy version %s: %s" %316 (v['VersionId'], to_native(e)),317 exception=traceback.format_exc(),318 **camel_dict_to_snake_dict(e.response))319 # Delete policy...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful