Uso de CreateInstanceProfile con un AWS SDK o la CLI - AWS Identity and Access Management

Uso de CreateInstanceProfile con un AWS SDK o la CLI

Los siguientes ejemplos de código muestran cómo utilizar CreateInstanceProfile.

Los ejemplos de acciones son extractos de código de programas más grandes y deben ejecutarse en contexto. Puede ver esta acción en contexto en el siguiente ejemplo de código:

.NET
AWS SDK for .NET
nota

Hay más información en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <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; }
  • Para obtener información acerca de la API, consulte CreateInstanceProfile en la Referencia de la API de AWS SDK for .NET.

CLI
AWS CLI

Cómo crear un perfil de instancia

El siguiente comando create-instance-profile crea un perfil de instancia denominado Webserver.

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

Salida:

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

Para añadir un rol a un perfil de instancia, utilice el comando add-role-to-instance-profile.

Para obtener más información, consulte Uso de un rol de IAM para conceder permisos a aplicaciones que se ejecutan en instancias de Amazon EC2 en la Guía del usuario de AWS IAM.

  • Para obtener información sobre la API, consulte CreateInstanceProfile en la Referencia de comandos de la AWS CLI.

JavaScript
SDK para JavaScript (v3)
nota

Hay más información en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

const { InstanceProfile } = await iamClient.send( new CreateInstanceProfileCommand({ InstanceProfileName: NAMES.ssmOnlyInstanceProfileName, }), ); await waitUntilInstanceProfileExists( { client: iamClient }, { InstanceProfileName: NAMES.ssmOnlyInstanceProfileName }, );
  • Para obtener información acerca de la API, consulte CreateInstanceProfile en la Referencia de la API de AWS SDK for JavaScript.

PowerShell
Herramientas para PowerShell

Ejemplo 1: en este ejemplo se crea un nuevo perfil de instancia de IAM denominado ProfileForDevEC2Instance. Debe ejecutar el comando Add-IAMRoleToInstanceProfile por separado para asociar el perfil de instancia a un rol de IAM existente que otorgue permisos a la instancia. Por último, adjuntar el perfil de instancia a una instancia de EC2 en el momento de iniciarla. Para ello, utilice el cmdlet de New-EC2Instance con el parámetro InstanceProfile_Arn o InstanceProfile_Name.

New-IAMInstanceProfile -InstanceProfileName ProfileForDevEC2Instance

Salida:

Arn : arn:aws:iam::123456789012:instance-profile/ProfileForDevEC2Instance CreateDate : 4/14/2015 11:31:39 AM InstanceProfileId : DYMFXL556EY46EXAMPLE1 InstanceProfileName : ProfileForDevEC2Instance Path : / Roles : {}
  • Para obtener información sobre la API, consulte CreateInstanceProfile en la Referencia de Cmdlet de AWS Tools for PowerShell.

Python
SDK para Python (Boto3)
nota

Hay más en GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

En este ejemplo, se crea una política, un rol y un perfil de instancia, luego, se vinculan todos entre sí.

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
  • Para obtener información acerca de la API, consulte CreateInstanceProfile en la Referencia de la API de AWS SDK para Python (Boto3).

Para obtener una lista completa de las guías para desarrolladores del AWS SDK y ejemplos de código, consulte Uso de IAM con un AWS SDK. En este tema también se incluye información sobre cómo comenzar a utilizar el SDK y detalles sobre sus versiones anteriores.