How to use disassociate_iam_instance_profile method in localstack

Best Python code snippet using localstack_python

test_iam_already_associated.py

Source:test_iam_already_associated.py Github

copy

Full Screen

...62s3_client = boto3.client('s3')63sns_client = boto3.client('sns')64sts_client = boto3.client('sts')65ec2_client = boto3.client('ec2')66def disassociate_iam_instance_profile(association_id):67 return ec2_client.disassociate_iam_instance_profile(68 AssociationId=association_id69 )70def remove_role_from_instance_profile(profile_name, role_name):71 return iam_client.remove_role_from_instance_profile(72 InstanceProfileName=profile_name,73 RoleName=role_name74 )75def delete_instance_profile(profile_name):76 return iam_client.delete_instance_profile(77 InstanceProfileName=profile_name78 )79def verify_role_created(role_arn):80 LOGGER.info("Verifying that role exists: " + role_arn)81 # For what ever reason assuming a role that got created too fast fails, so we just wait until we can.82 retry_count = 1283 while True:84 try:85 sts_client.assume_role(RoleArn=role_arn, RoleSessionName="checking_assume")86 break87 except Exception as e:88 retry_count -= 189 if retry_count == 0:90 raise e91 LOGGER.info("Unable to assume role... trying again in 5 sec")92 time.sleep(5)93class DocumentTest(unittest.TestCase):94 def test_update_document(self):95 cfn_client = boto3.client('cloudformation', region_name=REGION)96 ssm_client = boto3.client('ssm', region_name=REGION)97 test_cf_stack = ssm_testing.CFNTester(98 cfn_client=cfn_client,99 template_filename=os.path.abspath(os.path.join(100 DOC_DIR,101 "Tests/CloudFormationTemplates/TestAssociated.yml")),102 stack_name=TEST_CFN_STACK_NAME103 )104 LOGGER.info('Creating Test Stack')105 test_cf_stack.create_stack([106 {107 'ParameterKey': 'AMI',108 'ParameterValue': LINUX_AMI_ID109 },110 {111 'ParameterKey': 'INSTANCETYPE',112 'ParameterValue': LINUX_INSTANCE_TYPE113 },114 {115 'ParameterKey': 'UserARN',116 'ParameterValue': sts_client.get_caller_identity().get('Arn')117 }118 ])119 LOGGER.info('Test Stack has been created')120 # Verify role exists121 role_arn = test_cf_stack.stack_outputs['AutomationAssumeRoleARN']122 verify_role_created(role_arn)123 # Crete the lambda124 ssm_doc = ssm_testing.SSMTester(125 ssm_client=ssm_client,126 doc_filename=os.path.join(DOC_DIR,127 'Output/aws-AttachIAMToInstance.json'),128 doc_name=SSM_DOC_NAME,129 doc_type='Automation'130 )131 LOGGER.info("Creating automation document")132 self.assertEqual(ssm_doc.create_document(), 'Active')133 try:134 instance_id = test_cf_stack.stack_outputs['InstanceId']135 test_role_name = test_cf_stack.stack_outputs['TestRoleName']136 execution = ssm_doc.execute_automation(137 params={'InstanceId': [instance_id],138 'RoleName': [test_role_name],139 'AutomationAssumeRole': [role_arn]})140 self.assertEqual(ssm_doc.automation_execution_status(ssm_client, execution, False), 'Success')141 LOGGER.info('automation executed successfully')142 response = ssm_client.get_automation_execution(AutomationExecutionId=execution)143 str_payload = response['AutomationExecution']['Outputs']['attachIAMToInstance.Payload'][0]144 payload = json.loads(str_payload)145 association_id = payload['AssociationId']146 profile_name = payload['InstanceProfileName']147 self.assertEqual(test_role_name, payload['RoleName'])148 LOGGER.info('Verify that the instance has a profile')149 profile_instance_response = ec2_client.describe_iam_instance_profile_associations(Filters=[{150 'Name': 'instance-id',151 'Values': [instance_id]152 }])153 self.assertEqual(len(profile_instance_response['IamInstanceProfileAssociations']), 1)154 iam_instance_profile_association = profile_instance_response['IamInstanceProfileAssociations'][0]155 self.assertEqual(len(profile_instance_response['IamInstanceProfileAssociations']), 1)156 self.assertEqual(iam_instance_profile_association['AssociationId'], association_id)157 self.assertEqual(iam_instance_profile_association['InstanceId'], instance_id)158 LOGGER.info('Verify that the instance profile has the role')159 instance_profile_response = iam_client.get_instance_profile(160 InstanceProfileName=profile_name161 )162 self.assertEqual(instance_profile_response['InstanceProfile']['InstanceProfileName'], profile_name)163 role_count = 0164 for role in instance_profile_response['InstanceProfile']['Roles']:165 if role['RoleName'] == test_role_name:166 role_count += 1167 self.assertEqual(role_count, 1)168 LOGGER.info('Tests successful. Cleaning up')169 remove_role_from_instance_profile(profile_name, test_role_name)170 delete_instance_profile(profile_name)171 disassociate_iam_instance_profile(association_id)172 LOGGER.info('Clean up successful')173 finally:174 try:175 ssm_doc.destroy()176 except Exception:177 pass178 test_cf_stack.delete_stack()179if __name__ == '__main__':...

Full Screen

Full Screen

test_iam_not_associated.py

Source:test_iam_not_associated.py Github

copy

Full Screen

...62s3_client = boto3.client('s3')63sns_client = boto3.client('sns')64sts_client = boto3.client('sts')65ec2_client = boto3.client('ec2')66def disassociate_iam_instance_profile(association_id):67 return ec2_client.disassociate_iam_instance_profile(68 AssociationId=association_id69 )70def remove_role_from_instance_profile(profile_name, role_name):71 return iam_client.remove_role_from_instance_profile(72 InstanceProfileName=profile_name,73 RoleName=role_name74 )75def delete_instance_profile(profile_name):76 return iam_client.delete_instance_profile(77 InstanceProfileName=profile_name78 )79def verify_role_created(role_arn):80 LOGGER.info("Verifying that role exists: " + role_arn)81 # For what ever reason assuming a role that got created too fast fails, so we just wait until we can.82 retry_count = 1283 while True:84 try:85 sts_client.assume_role(RoleArn=role_arn, RoleSessionName="checking_assume")86 break87 except Exception as e:88 retry_count -= 189 if retry_count == 0:90 raise e91 LOGGER.info("Unable to assume role... trying again in 5 sec")92 time.sleep(5)93class DocumentTest(unittest.TestCase):94 def test_update_document(self):95 cfn_client = boto3.client('cloudformation', region_name=REGION)96 ssm_client = boto3.client('ssm', region_name=REGION)97 test_cf_stack = ssm_testing.CFNTester(98 cfn_client=cfn_client,99 template_filename=os.path.abspath(os.path.join(100 DOC_DIR,101 "Tests/CloudFormationTemplates/TestNotAssociated.yml")),102 stack_name=TEST_CFN_STACK_NAME103 )104 LOGGER.info('Creating Test Stack')105 test_cf_stack.create_stack([106 {107 'ParameterKey': 'AMI',108 'ParameterValue': LINUX_AMI_ID109 },110 {111 'ParameterKey': 'INSTANCETYPE',112 'ParameterValue': LINUX_INSTANCE_TYPE113 },114 {115 'ParameterKey': 'UserARN',116 'ParameterValue': sts_client.get_caller_identity().get('Arn')117 }118 ])119 LOGGER.info('Test Stack has been created')120 # Verify role exists121 role_arn = test_cf_stack.stack_outputs['AutomationAssumeRoleARN']122 verify_role_created(role_arn)123 # Crete the lambda124 ssm_doc = ssm_testing.SSMTester(125 ssm_client=ssm_client,126 doc_filename=os.path.join(DOC_DIR,127 'Output/aws-AttachIAMToInstance.json'),128 doc_name=SSM_DOC_NAME,129 doc_type='Automation'130 )131 LOGGER.info("Creating automation document")132 self.assertEqual(ssm_doc.create_document(), 'Active')133 try:134 instance_id = test_cf_stack.stack_outputs['InstanceId']135 role_name = test_cf_stack.stack_outputs['AutomationAssumeRoleName']136 execution = ssm_doc.execute_automation(137 params={'InstanceId': [instance_id],138 'RoleName': [role_name],139 'AutomationAssumeRole': [role_arn]})140 self.assertEqual(ssm_doc.automation_execution_status(ssm_client, execution, False), 'Success')141 LOGGER.info('automation executed successfully')142 response = ssm_client.get_automation_execution(AutomationExecutionId=execution)143 str_payload = response['AutomationExecution']['Outputs']['attachIAMToInstance.Payload'][0]144 payload = json.loads(str_payload)145 association_id = payload['AssociationId']146 profile_name = payload['InstanceProfileName']147 self.assertEqual(role_name, payload['RoleName'])148 LOGGER.info('Verify that the instance has a profile')149 profile_instance_response = ec2_client.describe_iam_instance_profile_associations(Filters=[{150 'Name': 'instance-id',151 'Values': [instance_id]152 }])153 self.assertEqual(len(profile_instance_response['IamInstanceProfileAssociations']), 1)154 iam_instance_profile_association = profile_instance_response['IamInstanceProfileAssociations'][0]155 self.assertEqual(len(profile_instance_response['IamInstanceProfileAssociations']), 1)156 self.assertEqual(iam_instance_profile_association['AssociationId'], association_id)157 self.assertEqual(iam_instance_profile_association['InstanceId'], instance_id)158 LOGGER.info('Verify that the instance profile has the role')159 instance_profile_response = iam_client.get_instance_profile(160 InstanceProfileName=profile_name161 )162 self.assertEqual(instance_profile_response['InstanceProfile']['InstanceProfileName'], profile_name)163 role_count = 0164 for role in instance_profile_response['InstanceProfile']['Roles']:165 if role['RoleName'] == role_name:166 role_count += 1167 self.assertEqual(role_count, 1)168 LOGGER.info('Tests successful. Cleaning up')169 remove_role_from_instance_profile(profile_name, role_name)170 delete_instance_profile(profile_name)171 disassociate_iam_instance_profile(association_id)172 LOGGER.info('Clean up successful')173 finally:174 try:175 ssm_doc.destroy()176 except Exception:177 pass178 test_cf_stack.delete_stack()179if __name__ == '__main__':...

Full Screen

Full Screen

teardown.py

Source:teardown.py Github

copy

Full Screen

...9image = config.image10cluster_name = config.cluster_name11family_name = config.family_name12family_version = config.family_version13def disassociate_iam_instance_profile():14 print(ec2.describe_iam_instance_profile_associations())15def delete_instance_profile():16 response = iam_client.delete_instance_profile(17 InstanceProfileName=config.ec2_instance_profile18 )19 return response20def deregister_task_definition(task_definition, version):21 response = ecs.deregister_task_definition(22 taskDefinition=task_definition + ':' + version23 )24 return response25def delete_cluster():26 response = ecs.delete_cluster(27 cluster=cluster_name28 )29 return response30def remove_role_from_instance_profile():31 iam_client.remove_role_from_instance_profile(32 InstanceProfileName=config.ec2_instance_profile,33 RoleName=config.ec2_container_service_role34 )35def delete_security_group():36 ec2.delete_security_group(37 GroupName=config.security_group_name38 )39def detach_policy():40 role = iam_resource.Role(config.ec2_container_service_role)41 role.detach_policy(PolicyArn=config.aws_ec2_container_service_role)42def delete_role():43 role = iam_resource.Role(config.ec2_container_service_role)44 role.delete()45def teardown():46 print(delete_cluster())47 print(deregister_task_definition(family_name, family_version))48 delete_security_group()49 detach_policy()50 remove_role_from_instance_profile()51 time.sleep(3)52 delete_role()53 print(disassociate_iam_instance_profile())54 print(delete_instance_profile())55if __name__ == "__main__":...

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