@@ -1730,12 +1730,67 @@ def _create_role(iam_client=None, **kwargs):
17301730 role_policy ,
17311731 role_name ,
17321732 )
1733+ instance_profiles = iam_client .list_instance_profiles_for_role (RoleName = role_name )[
1734+ "InstanceProfiles"
1735+ ]
1736+ for instance_profile in instance_profiles :
1737+ try :
1738+ iam_client .remove_role_from_instance_profile (
1739+ InstanceProfileName = instance_profile ["InstanceProfileName" ], RoleName = role_name
1740+ )
1741+ except Exception :
1742+ LOG .debug (
1743+ "Could not delete instance profile '%s' from '%s' during cleanup" ,
1744+ instance_profile ["InstanceProfileName" ],
1745+ role_name ,
1746+ )
17331747 try :
17341748 iam_client .delete_role (RoleName = role_name )
17351749 except Exception :
17361750 LOG .debug ("Could not delete role '%s' during cleanup" , role_name )
17371751
17381752
1753+ @pytest .fixture
1754+ def create_instance_profile (aws_client ):
1755+ profile_names = []
1756+
1757+ def _create_instance_profile (** kwargs ):
1758+ if not kwargs .get ("InstanceProfileName" ):
1759+ kwargs ["InstanceProfileName" ] = f"instance-profile-{ short_uid ()} "
1760+ result = aws_client .iam .create_instance_profile (** kwargs )
1761+ profile_names .append (result ["InstanceProfile" ]["InstanceProfileName" ])
1762+ return result
1763+
1764+ yield _create_instance_profile
1765+
1766+ for profile_name in profile_names :
1767+ # Remove any attached roles before deleting
1768+ try :
1769+ profile = aws_client .iam .get_instance_profile (InstanceProfileName = profile_name )
1770+ for role in profile ["InstanceProfile" ].get ("Roles" , []):
1771+ try :
1772+ aws_client .iam .remove_role_from_instance_profile (
1773+ InstanceProfileName = profile_name , RoleName = role ["RoleName" ]
1774+ )
1775+ except Exception :
1776+ LOG .debug (
1777+ "Could not remove role '%s' from instance profile '%s' during cleanup" ,
1778+ role ["RoleName" ],
1779+ profile_name ,
1780+ )
1781+ except ClientError as e :
1782+ LOG .debug (
1783+ "Cannot get instance profile: %s. Instance profile %s probably already deleted..." ,
1784+ e ,
1785+ profile_name ,
1786+ )
1787+ continue
1788+ try :
1789+ aws_client .iam .delete_instance_profile (InstanceProfileName = profile_name )
1790+ except Exception :
1791+ LOG .debug ("Could not delete instance profile '%s' during cleanup" , profile_name )
1792+
1793+
17391794@pytest .fixture
17401795def create_group (aws_client ):
17411796 group_names = []
0 commit comments