DescribeIamInstanceProfileAssociations 搭配 AWS SDK或 使用 CLI - Amazon Elastic Compute Cloud

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

DescribeIamInstanceProfileAssociations 搭配 AWS SDK或 使用 CLI

下列程式碼範例示範如何使用 DescribeIamInstanceProfileAssociations

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/// <summary> /// Get the instance profile association data for an instance. /// </summary> /// <param name="instanceId">The Id of the instance.</param> /// <returns>Instance profile associations data.</returns> public async Task<IamInstanceProfileAssociation> GetInstanceProfile(string instanceId) { try { var response = await _amazonEc2.DescribeIamInstanceProfileAssociationsAsync( new DescribeIamInstanceProfileAssociationsRequest() { Filters = new List<Amazon.EC2.Model.Filter>() { new("instance-id", new List<string>() { instanceId }) }, }); return response.IamInstanceProfileAssociations[0]; } catch (AmazonEC2Exception ec2Exception) { if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound") { _logger.LogError(ec2Exception, $"Instance {instanceId} not found"); } throw; } catch (Exception ex) { _logger.LogError(ex, $"An error occurred while creating the template.: {ex.Message}"); throw; } }
CLI
AWS CLI

描述IAM執行個體設定檔關聯

此範例說明您的所有IAM執行個體設定檔關聯。

命令:

aws ec2 describe-iam-instance-profile-associations

輸出:

{ "IamInstanceProfileAssociations": [ { "InstanceId": "i-09eb09efa73ec1dee", "State": "associated", "AssociationId": "iip-assoc-0db249b1f25fa24b8", "IamInstanceProfile": { "Id": "AIPAJVQN4F5WVLGCJDRGM", "Arn": "arn:aws:iam::123456789012:instance-profile/admin-role" } }, { "InstanceId": "i-0402909a2f4dffd14", "State": "associating", "AssociationId": "iip-assoc-0d1ec06278d29f44a", "IamInstanceProfile": { "Id": "AGJAJVQN4F5WVLGCJABCM", "Arn": "arn:aws:iam::123456789012:instance-profile/user1-role" } } ] }
JavaScript
SDK 適用於 JavaScript (v3)
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

const ec2Client = new EC2Client({}); const { IamInstanceProfileAssociations } = await ec2Client.send( new DescribeIamInstanceProfileAssociationsCommand({ Filters: [ { Name: "instance-id", Values: [state.targetInstance.InstanceId] }, ], }), );
Python
SDK for Python (Boto3)
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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 get_instance_profile(self, instance_id: str) -> Dict[str, Any]: """ Gets data about the profile associated with an instance. :param instance_id: The ID of the instance to look up. :return: The profile data. """ try: response = self.ec2_client.describe_iam_instance_profile_associations( Filters=[{"Name": "instance-id", "Values": [instance_id]}] ) if not response["IamInstanceProfileAssociations"]: log.info(f"No instance profile found for instance {instance_id}.") profile_data = response["IamInstanceProfileAssociations"][0] log.info(f"Retrieved instance profile for instance {instance_id}.") return profile_data except ClientError as err: log.error( f"Failed to retrieve instance profile for instance {instance_id}." ) error_code = err.response["Error"]["Code"] if error_code == "InvalidInstanceID.NotFound": log.error(f"The instance ID '{instance_id}' does not exist.") log.error(f"Full error:\n\t{err}")

如需開發人員指南和程式碼範例的完整清單 AWS SDK,請參閱 使用 建立 Amazon EC2 資源 AWS SDK。本主題也包含有關入門的資訊,以及先前SDK版本的詳細資訊。