

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# Benutzen `DeleteInstanceProfile` mit einem AWS SDK oder CLI

Die folgenden Code-Beispiele zeigen, wie `DeleteInstanceProfile` verwendet wird.

Aktionsbeispiele sind Codeauszüge aus größeren Programmen und müssen im Kontext ausgeführt werden. Sie können diese Aktion in den folgenden Codebeispielen im Kontext sehen: 
+  [Erstellen und Verwalten eines ausfallsicheren Services](iam_example_cross_ResilientService_section.md) 
+  [Erste Schritte mit verwaltetem Streaming](iam_example_ec2_GettingStarted_057_section.md) 
+  [CPU-Stresstests auf VM-Instances mithilfe von Fault Injection ausführen](iam_example_iam_GettingStarted_069_section.md) 

------
#### [ .NET ]

**SDK für .NET**  
 Es gibt noch mehr GitHub. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das [AWS -Code-Beispiel-](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples) einrichten und ausführen. 

```csharp
    /// <summary>
    /// Detaches a role from an instance profile, detaches policies from the role,
    /// and deletes all the resources.
    /// </summary>
    /// <param name="profileName">The name of the profile to delete.</param>
    /// <param name="roleName">The name of the role to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteInstanceProfile(string profileName, string roleName)
    {
        try
        {
            await _amazonIam.RemoveRoleFromInstanceProfileAsync(
                new RemoveRoleFromInstanceProfileRequest()
                {
                    InstanceProfileName = profileName,
                    RoleName = roleName
                });
            await _amazonIam.DeleteInstanceProfileAsync(
                new DeleteInstanceProfileRequest() { InstanceProfileName = profileName });
            var attachedPolicies = await _amazonIam.ListAttachedRolePoliciesAsync(
                new ListAttachedRolePoliciesRequest() { RoleName = roleName });
            foreach (var policy in attachedPolicies.AttachedPolicies)
            {
                await _amazonIam.DetachRolePolicyAsync(
                    new DetachRolePolicyRequest()
                    {
                        RoleName = roleName,
                        PolicyArn = policy.PolicyArn
                    });
                // Delete the custom policies only.
                if (!policy.PolicyArn.StartsWith("arn:aws:iam::aws"))
                {
                    await _amazonIam.DeletePolicyAsync(
                        new Amazon.IdentityManagement.Model.DeletePolicyRequest()
                        {
                            PolicyArn = policy.PolicyArn
                        });
                }
            }

            await _amazonIam.DeleteRoleAsync(
                new DeleteRoleRequest() { RoleName = roleName });
        }
        catch (NoSuchEntityException)
        {
            Console.WriteLine($"Instance profile {profileName} does not exist.");
        }
    }
```
+  Einzelheiten zur API finden Sie unter [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteInstanceProfile) in *AWS SDK für .NET API-Referenz*. 

------
#### [ CLI ]

**AWS CLI**  
**So löschen Sie ein Instance-Profil**  
Folgendes `delete-instance-profile` Beispiel löscht das Instanzprofil mit dem Namen `ExampleInstanceProfile`.  

```
aws iam delete-instance-profile \
    --instance-profile-name {{ExampleInstanceProfile}}
```
Mit diesem Befehl wird keine Ausgabe zurückgegeben.  
Weitere Informationen finden Sie unter [Verwenden von Instance-Profilen](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html) im *AWS -IAM-Benutzerhandbuch*.  
+  Einzelheiten zur API finden Sie unter [DeleteInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-instance-profile.html) in *AWS CLI Befehlsreferenz*. 

------
#### [ JavaScript ]

**SDK für JavaScript (v3)**  
 Es gibt noch mehr GitHub. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das [AWS -Code-Beispiel-](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples) einrichten und ausführen. 

```javascript
      const client = new IAMClient({});
      await client.send(
        new DeleteInstanceProfileCommand({
          InstanceProfileName: NAMES.instanceProfileName,
        }),
      );
```
+  Einzelheiten zur API finden Sie unter [DeleteInstanceProfile](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteInstanceProfileCommand) in *AWS SDK für JavaScript API-Referenz*. 

------
#### [ PowerShell ]

**Werkzeuge für PowerShell V4**  
**Beispiel 1: In diesem Beispiel wird das EC2-Instance-Profil mit dem Namen `MyAppInstanceProfile` gelöscht. Mit dem ersten Befehl werden alle Rollen vom Instance-Profil getrennt, und mit dem zweiten Befehl wird das Instance-Profil gelöscht.**  

```powershell
(Get-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile).Roles | Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyAppInstanceProfile
Remove-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile
```
+  API-Details finden Sie unter [DeleteInstanceProfile](https://docs.aws.amazon.com/powershell/v4/reference) in *AWS -Tools für PowerShell Cmdlet-Referenz (V4)*. 

**Werkzeuge für PowerShell V5**  
**Beispiel 1: In diesem Beispiel wird das EC2-Instance-Profil mit dem Namen `MyAppInstanceProfile` gelöscht. Mit dem ersten Befehl werden alle Rollen vom Instance-Profil getrennt, und mit dem zweiten Befehl wird das Instance-Profil gelöscht.**  

```powershell
(Get-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile).Roles | Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyAppInstanceProfile
Remove-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile
```
+  API-Details finden Sie unter [DeleteInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference) in *AWS -Tools für PowerShell Cmdlet-Referenz (V5)*. 

------
#### [ Python ]

**SDK für Python (Boto3)**  
 Es gibt noch mehr GitHub. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das [AWS -Code-Beispiel-](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples) einrichten und ausführen. 
In diesem Beispiel wird die Rolle aus dem Instance-Profil entfernt, alle mit der Rolle verknüpften Richtlinien getrennt und alle Ressourcen gelöscht.  

```python
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def delete_instance_profile(self, profile_name: str, role_name: str) -> None:
        """
        Detaches a role from an instance profile, detaches policies from the role,
        and deletes all the resources.

        :param profile_name: The name of the profile to delete.
        :param role_name: The name of the role to delete.
        """
        try:
            self.iam_client.remove_role_from_instance_profile(
                InstanceProfileName=profile_name, RoleName=role_name
            )
            self.iam_client.delete_instance_profile(InstanceProfileName=profile_name)
            log.info("Deleted instance profile %s.", profile_name)
            attached_policies = self.iam_client.list_attached_role_policies(
                RoleName=role_name
            )
            for pol in attached_policies["AttachedPolicies"]:
                self.iam_client.detach_role_policy(
                    RoleName=role_name, PolicyArn=pol["PolicyArn"]
                )
                if not pol["PolicyArn"].startswith("arn:aws:iam::aws"):
                    self.iam_client.delete_policy(PolicyArn=pol["PolicyArn"])
                log.info("Detached and deleted policy %s.", pol["PolicyName"])
            self.iam_client.delete_role(RoleName=role_name)
            log.info("Deleted role %s.", role_name)
        except ClientError as err:
            log.error(
                f"Couldn't delete instance profile {profile_name} or detach "
                f"policies and delete role {role_name}: {err}"
            )
            if err.response["Error"]["Code"] == "NoSuchEntity":
                log.info(
                    "Instance profile %s doesn't exist, nothing to do.", profile_name
                )
```
+  Einzelheiten zur API finden Sie unter [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteInstanceProfile) in *AWS API-Referenz für das SDK für Python (Boto3)*. 

------

Für eine vollständige Liste von AWS SDK-Entwicklerhandbücher und Codebeispiele finden Sie unter [Verwenden Sie diesen Dienst mit einem AWS SDK](sdk-general-information-section.md). Dieses Thema enthält auch Informationen zu den ersten Schritten und Details zu früheren SDK-Versionen.