将 CreateInstanceProfile 与 Amazon SDK 或命令行工具配合使用 - Amazon Identity and Access Management
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

CreateInstanceProfile 与 Amazon SDK 或命令行工具配合使用

以下代码示例演示如何使用 CreateInstanceProfile

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

/// <summary> /// Create a policy, role, and profile that is associated with instances with a specified name. /// An instance's associated profile defines a role that is assumed by the /// instance.The role has attached policies that specify the AWS permissions granted to /// clients that run on the instance. /// </summary> /// <param name="policyName">Name to use for the policy.</param> /// <param name="roleName">Name to use for the role.</param> /// <param name="profileName">Name to use for the profile.</param> /// <param name="ssmOnlyPolicyFile">Path to a policy file for SSM.</param> /// <param name="awsManagedPolicies">AWS Managed policies to be attached to the role.</param> /// <returns>The Arn of the profile.</returns> public async Task<string> CreateInstanceProfileWithName( string policyName, string roleName, string profileName, string ssmOnlyPolicyFile, List<string>? awsManagedPolicies = null) { var assumeRoleDoc = "{" + "\"Version\": \"2012-10-17\"," + "\"Statement\": [{" + "\"Effect\": \"Allow\"," + "\"Principal\": {" + "\"Service\": [" + "\"ec2.amazonaws.com\"" + "]" + "}," + "\"Action\": \"sts:AssumeRole\"" + "}]" + "}"; var policyDocument = await File.ReadAllTextAsync(ssmOnlyPolicyFile); var policyArn = ""; try { var createPolicyResult = await _amazonIam.CreatePolicyAsync( new CreatePolicyRequest { PolicyName = policyName, PolicyDocument = policyDocument }); policyArn = createPolicyResult.Policy.Arn; } catch (EntityAlreadyExistsException) { // The policy already exists, so we look it up to get the Arn. var policiesPaginator = _amazonIam.Paginators.ListPolicies( new ListPoliciesRequest() { Scope = PolicyScopeType.Local }); // Get the entire list using the paginator. await foreach (var policy in policiesPaginator.Policies) { if (policy.PolicyName.Equals(policyName)) { policyArn = policy.Arn; } } if (policyArn == null) { throw new InvalidOperationException("Policy not found"); } } try { await _amazonIam.CreateRoleAsync(new CreateRoleRequest() { RoleName = roleName, AssumeRolePolicyDocument = assumeRoleDoc, }); await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest() { RoleName = roleName, PolicyArn = policyArn }); if (awsManagedPolicies != null) { foreach (var awsPolicy in awsManagedPolicies) { await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest() { PolicyArn = $"arn:aws:iam::aws:policy/{awsPolicy}", RoleName = roleName }); } } } catch (EntityAlreadyExistsException) { Console.WriteLine("Role already exists."); } string profileArn = ""; try { var profileCreateResponse = await _amazonIam.CreateInstanceProfileAsync( new CreateInstanceProfileRequest() { InstanceProfileName = profileName }); // Allow time for the profile to be ready. profileArn = profileCreateResponse.InstanceProfile.Arn; Thread.Sleep(10000); await _amazonIam.AddRoleToInstanceProfileAsync( new AddRoleToInstanceProfileRequest() { InstanceProfileName = profileName, RoleName = roleName }); } catch (EntityAlreadyExistsException) { Console.WriteLine("Policy already exists."); var profileGetResponse = await _amazonIam.GetInstanceProfileAsync( new GetInstanceProfileRequest() { InstanceProfileName = profileName }); profileArn = profileGetResponse.InstanceProfile.Arn; } return profileArn; }
CLI
Amazon CLI

要创建实例配置文件

以下 create-instance-profile 命令将创建名为 Webserver 的实例配置文件。

aws iam create-instance-profile \ --instance-profile-name Webserver

输出:

{ "InstanceProfile": { "InstanceProfileId": "AIPAJMBYC7DLSPEXAMPLE", "Roles": [], "CreateDate": "2015-03-09T20:33:19.626Z", "InstanceProfileName": "Webserver", "Path": "/", "Arn": "arn:aws:iam::123456789012:instance-profile/Webserver" } }

要将角色添加到实例配置文件,请使用 add-role-to-instance-profile 命令。

有关更多信息,请参阅《Amazon IAM 用户指南》中的使用 IAM 角色为 Amazon EC2 实例上运行的应用程序授予权限

JavaScript
SDK for JavaScript (v3)
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

const { InstanceProfile } = await iamClient.send( new CreateInstanceProfileCommand({ InstanceProfileName: NAMES.ssmOnlyInstanceProfileName, }), ); await waitUntilInstanceProfileExists( { client: iamClient }, { InstanceProfileName: NAMES.ssmOnlyInstanceProfileName }, );
  • 有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 CreateInstanceProfile

PowerShell
适用于 PowerShell 的工具

示例 1:此示例创建了一个名为 ProfileForDevEC2Instance 的新 IAM 实例配置文件。您必须单独运行 Add-IAMRoleToInstanceProfile 命令,以将实例配置文件与为该实例提供权限的现有 IAM 角色相关联。最后,在启动 EC2 实例时将实例配置文件附加到该实例。为此,请使用带有 InstanceProfile_ArnInstanceProfile_Name 参数的 New-EC2Instance cmdlet。

New-IAMInstanceProfile -InstanceProfileName ProfileForDevEC2Instance

输出:

Arn : arn:aws:iam::123456789012:instance-profile/ProfileForDevEC2Instance CreateDate : 4/14/2015 11:31:39 AM InstanceProfileId : DYMFXL556EY46EXAMPLE1 InstanceProfileName : ProfileForDevEC2Instance Path : / Roles : {}
  • 有关 API 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet 参考》中的 CreateInstanceProfile

Python
SDK for Python(Boto3)
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

此示例将创建一个策略、角色和实例配置文件,并将其全部关联起来。

class AutoScaler: """ Encapsulates Amazon EC2 Auto Scaling and EC2 management actions. """ def __init__( self, resource_prefix, inst_type, ami_param, autoscaling_client, ec2_client, ssm_client, iam_client, ): """ :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 self.launch_template_name = f"{resource_prefix}-template" self.group_name = f"{resource_prefix}-group" self.instance_policy_name = f"{resource_prefix}-pol" self.instance_role_name = f"{resource_prefix}-role" self.instance_profile_name = f"{resource_prefix}-prof" 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" self.key_pair_name = f"{resource_prefix}-key-pair" def create_instance_profile( self, policy_file, policy_name, role_name, profile_name, aws_managed_policies=() ): """ Creates a policy, role, and profile that is associated with instances created by this class. An instance's associated profile defines a role that is assumed by the instance. The role has attached policies that specify the AWS permissions granted to clients that run on the instance. :param policy_file: The name of a JSON file that contains the policy definition to create and attach to the role. :param policy_name: The name to give the created policy. :param role_name: The name to give the created role. :param profile_name: The name to the created profile. :param aws_managed_policies: Additional AWS-managed policies that are attached to the role, such as AmazonSSMManagedInstanceCore to grant use of Systems Manager to send commands to the instance. :return: The ARN of the profile that is created. """ assume_role_doc = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"Service": "ec2.amazonaws.com"}, "Action": "sts:AssumeRole", } ], } with open(policy_file) as file: instance_policy_doc = file.read() policy_arn = None try: pol_response = self.iam_client.create_policy( PolicyName=policy_name, PolicyDocument=instance_policy_doc ) policy_arn = pol_response["Policy"]["Arn"] log.info("Created policy with ARN %s.", policy_arn) except ClientError as err: if err.response["Error"]["Code"] == "EntityAlreadyExists": log.info("Policy %s already exists, nothing to do.", policy_name) list_pol_response = self.iam_client.list_policies(Scope="Local") for pol in list_pol_response["Policies"]: if pol["PolicyName"] == policy_name: policy_arn = pol["Arn"] break if policy_arn is None: raise AutoScalerError(f"Couldn't create policy {policy_name}: {err}") try: self.iam_client.create_role( RoleName=role_name, AssumeRolePolicyDocument=json.dumps(assume_role_doc) ) self.iam_client.attach_role_policy(RoleName=role_name, PolicyArn=policy_arn) for aws_policy in aws_managed_policies: self.iam_client.attach_role_policy( RoleName=role_name, PolicyArn=f"arn:aws:iam::aws:policy/{aws_policy}", ) log.info("Created role %s and attached policy %s.", role_name, policy_arn) except ClientError as err: if err.response["Error"]["Code"] == "EntityAlreadyExists": log.info("Role %s already exists, nothing to do.", role_name) else: raise AutoScalerError(f"Couldn't create role {role_name}: {err}") try: profile_response = self.iam_client.create_instance_profile( InstanceProfileName=profile_name ) waiter = self.iam_client.get_waiter("instance_profile_exists") waiter.wait(InstanceProfileName=profile_name) time.sleep(10) # wait a little longer profile_arn = profile_response["InstanceProfile"]["Arn"] self.iam_client.add_role_to_instance_profile( InstanceProfileName=profile_name, RoleName=role_name ) log.info("Created profile %s and added role %s.", profile_name, role_name) except ClientError as err: if err.response["Error"]["Code"] == "EntityAlreadyExists": prof_response = self.iam_client.get_instance_profile( InstanceProfileName=profile_name ) profile_arn = prof_response["InstanceProfile"]["Arn"] log.info( "Instance profile %s already exists, nothing to do.", profile_name ) else: raise AutoScalerError( f"Couldn't create profile {profile_name} and attach it to role\n" f"{role_name}: {err}" ) return profile_arn
  • 有关 API 详细信息,请参阅《适用于 Python(Boto3)的 Amazon SDK API 参考》中的 CreateInstanceProfile

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。