def updateModelRoles(ctx, targetRegion, targetEnv, targetRole, constrainToModel): ctxRoles = ctx.model['roles'] for region in ctxRoles: if targetRegion != None and region != targetRegion: continue for env in ctxRoles[region]: #defaults = None if targetEnv != None and env != targetEnv: continue for role in ctxRoles[region][env]: if targetRole != None and role != targetRole: continue if not aws_roles.isRoleInAWS(ctx, role): ctx.vlog('Adding missing role to AWS: %s' % role) aws_roles.createRole(ctx, role) if ctx.dry_run: # Since we are not actually creating the role in # dry_run mode, we can't try to attach policies. continue else: ctx.log('Model role found in AWS: ' + role) policies = set(ctxRoles[region][env][role]) attached = set(aws_roles.getAttachedPolicies(ctx, role)) missing = policies.difference(attached) if len(missing) > 0: for policyName in missing: ctx.log('-- Attaching policy: %s' % policyName) aws_roles.attachPolicy(ctx, role, policyName) if not constrainToModel: continue # Remove attached policies that are not in the model extra = attached.difference(policies) if len(extra) > 0: for policyName in extra: ctx.log('-- Unattaching policy: %s' % policyName) aws_roles.detachPolicy(ctx, role, policyName)
def deletePolicy(ctx, policyName): iam = ctx.iam meta = getPolicyMeta(ctx, policyName) if meta == None: # Nothing to do ctx.vlog('deletePolicy: policy %s does not exist' % policyName) return policyArn = meta['Arn'] defaultVersionId = meta['DefaultVersionId'] #detach from Roles #try: mps = iam.list_entities_for_policy(PolicyArn=policyArn, EntityFilter='Role') # {'PolicyUsers': [], 'ResponseMetadata': {'HTTPStatusCode': 200, 'RequestId': '15a1da6e-83eb-11e5-95da-2d6fbedc8b89'}, 'PolicyGroups': [], 'IsTruncated': False, 'PolicyRoles': [{'RoleName': 'us-west-2-dev-mongo'}]} for policyRole in mps['PolicyRoles']: roleName = policyRole['RoleName'] aws_roles.detachPolicy(ctx, roleName, policyName) while mps['IsTruncated']: mps = iam.list_entities_for_policy(PolicyArn=policyArn, EntityFilter='Role', Marker=mps['Marker']) for policyRole in mps['PolicyRoles']: aws_roles.detachPolicy(ctx, policyRole['RoleName'], policyName) #except: # pass # delete all Versions except Default versions = getPolicyVersions(ctx, policyArn) for versionId in versions: if versionId != defaultVersionId: deletePolicyVersion(ctx, policyArn, versionId) # delete the policy if ctx.dry_run: ctx.log('delete_policy(PolicyArn=%s)' % (policyArn)) return iam.delete_policy(PolicyArn=policyArn) ctx.audit('Deleted policy %s' % (policyName))