Anexar uma política do IAM a uma função usando um AWS SDK - AWS Identity and Access Management

Anexar uma política do IAM a uma função usando um AWS SDK

Os exemplos de código a seguir mostram como anexar uma política do IAM a uma função.

.NET
AWS SDK for .NET
dica

Para saber mais sobre como configurar e executar esse exemplo, consulte o GitHub.

/// <summary> /// Attach the policy to the role so that the user can assume it. /// </summary> /// <param name="client">The initialized IAM client object.</param> /// <param name="policyArn">The ARN of the policy to attach.</param> /// <param name="roleName">The name of the role to attach the policy to.</param> public static async Task AttachRoleAsync( AmazonIdentityManagementServiceClient client, string policyArn, string roleName) { var request = new AttachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName, }; var response = await client.AttachRolePolicyAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine("Successfully attached the policy to the role."); } else { Console.WriteLine("Could not attach the policy."); } }
  • Para obter detalhes da API, consulte AttachRolePolicy na Referência da API do AWS SDK for .NET.

Go
SDK for Go V2
dica

Para saber mais sobre como configurar e executar esse exemplo, consulte o GitHub.

// AttachRolePolicy _, err = service.AttachRolePolicy(context.Background(), &iam.AttachRolePolicyInput{ PolicyArn: aws.String(ExamplePolicyARN), RoleName: aws.String(ExampleRoleName), }) if err != nil { panic("Couldn't apply a policy to the role!") } fmt.Println("☑️ Attached policy " + ExamplePolicyARN + " to role " + ExampleRoleName)
  • Para obter detalhes da API, consulte AttachRolePolicy na Referência da API do AWS SDK for Go.

Java
SDK para Java 2.x
dica

Para saber mais sobre como configurar e executar esse exemplo, consulte o GitHub.

public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn ) { try { ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder() .roleName(roleName) .build(); ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request); List<AttachedPolicy> attachedPolicies = response.attachedPolicies(); // Ensure that the policy is not attached to this role String polArn = ""; for (AttachedPolicy policy: attachedPolicies) { polArn = policy.policyArn(); if (polArn.compareTo(policyArn)==0) { System.out.println(roleName + " policy is already attached to this role."); return; } } AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder() .roleName(roleName) .policyArn(policyArn) .build(); iam.attachRolePolicy(attachRequest); System.out.println("Successfully attached policy " + policyArn + " to role " + roleName); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } System.out.println("Done"); }
  • Para obter detalhes da API, consulte AttachRolePolicy na Referência da API do AWS SDK for Java 2.x.

JavaScript
SDK para JavaScript V3
dica

Para saber mais sobre como configurar e executar esse exemplo, consulte o GitHub.

Crie o cliente.

import { IAMClient } from "@aws-sdk/client-iam"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". // Create an IAM service client object. const iamClient = new IAMClient({ region: REGION }); export { iamClient };

Anexe a política.

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { ListAttachedRolePoliciesCommand, AttachRolePolicyCommand, } from "@aws-sdk/client-iam"; // Set the parameters. const ROLENAME = "ROLE_NAME"; const paramsRoleList = { RoleName: ROLENAME }; //ROLE_NAME export const params = { PolicyArn: "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess", RoleName: ROLENAME, }; export const run = async () => { try { const data = await iamClient.send( new ListAttachedRolePoliciesCommand(paramsRoleList) ); return data; const myRolePolicies = data.AttachedPolicies; myRolePolicies.forEach(function (val, index, array) { if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") { console.log( "AmazonDynamoDBFullAccess is already attached to this role." ); process.exit(); } }); try { const data = await iamClient.send(new AttachRolePolicyCommand(params)); console.log("Role attached successfully"); return data; } catch (err) { console.log("Error", err); } } catch (err) { console.log("Error", err); } }; run();
SDK para JavaScript V2
dica

Para saber mais sobre como configurar e executar esse exemplo, consulte o GitHub.

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create the IAM service object var iam = new AWS.IAM({apiVersion: '2010-05-08'}); var paramsRoleList = { RoleName: process.argv[2] }; iam.listAttachedRolePolicies(paramsRoleList, function(err, data) { if (err) { console.log("Error", err); } else { var myRolePolicies = data.AttachedPolicies; myRolePolicies.forEach(function (val, index, array) { if (myRolePolicies[index].PolicyName === 'AmazonDynamoDBFullAccess') { console.log("AmazonDynamoDBFullAccess is already attached to this role.") process.exit(); } }); var params = { PolicyArn: 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess', RoleName: process.argv[2] }; iam.attachRolePolicy(params, function(err, data) { if (err) { console.log("Unable to attach policy to role", err); } else { console.log("Role attached successfully"); } }); } });
Kotlin
SDK para Kotlin
nota

Essa documentação é de pré-lançamento para um recurso em versão de pré-visualização. Está sujeita a alteração.

dica

Para saber mais sobre como configurar e executar esse exemplo, consulte o GitHub.

suspend fun attachIAMRolePolicy(roleNameVal: String, policyArnVal: String) { val request = ListAttachedRolePoliciesRequest { roleName = roleNameVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.listAttachedRolePolicies(request) val attachedPolicies = response.attachedPolicies // Ensure that the policy is not attached to this role. val checkStatus: Int if (attachedPolicies != null) { checkStatus = checkList(attachedPolicies, policyArnVal) if (checkStatus == -1) return } val policyRequest = AttachRolePolicyRequest { roleName = roleNameVal policyArn = policyArnVal } iamClient.attachRolePolicy(policyRequest) println("Successfully attached policy $policyArnVal to role $roleNameVal") } } fun checkList(attachedPolicies: List<AttachedPolicy>, policyArnVal: String): Int { for (policy in attachedPolicies) { val polArn = policy.policyArn.toString() if (polArn.compareTo(policyArnVal) == 0) { println("The policy is already attached to this role.") return -1 } } return 0 }
  • Para obter detalhes da API, consulte AttachRolePolicy na Referência da API do AWS SDK for Kotlin.

PHP
SDK for PHP
dica

Para saber mais sobre como configurar e executar esse exemplo, consulte o GitHub.

$uuid = uniqid(); $service = new IamService(); $assumeRolePolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Principal\": {\"AWS\": \"{$user['Arn']}\"}, \"Action\": \"sts:AssumeRole\" }] }"; $assumeRoleRole = $service->createRole("iam_demo_role_$uuid", $assumeRolePolicyDocument); echo "Created role: {$assumeRoleRole['RoleName']}\n"; $listAllBucketsPolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Action\": \"s3:ListAllMyBuckets\", \"Resource\": \"arn:aws:s3:::*\"}] }"; $listAllBucketsPolicy = $service->createPolicy("iam_demo_policy_$uuid", $listAllBucketsPolicyDocument); echo "Created policy: {$listAllBucketsPolicy['PolicyName']}\n"; $service->attachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']); public function attachRolePolicy($roleName, $policyArn) { return $this->customWaiter(function () use ($roleName, $policyArn) { $this->iamClient->attachRolePolicy([ 'PolicyArn' => $policyArn, 'RoleName' => $roleName, ]); }); }
  • Para obter detalhes da API, consulte AttachRolePolicy na Referência da API do AWS SDK for PHP.

Python
SDK para Python (Boto3).
dica

Para saber mais sobre como configurar e executar esse exemplo, consulte o GitHub.

Anexar uma política a uma função usando o objeto Policy do Boto3.

def attach_to_role(role_name, policy_arn): """ Attaches a policy to a role. :param role_name: The name of the role. **Note** this is the name, not the ARN. :param policy_arn: The ARN of the policy. """ try: iam.Policy(policy_arn).attach_role(RoleName=role_name) logger.info("Attached policy %s to role %s.", policy_arn, role_name) except ClientError: logger.exception("Couldn't attach policy %s to role %s.", policy_arn, role_name) raise

Anexar uma política a uma função usando o objeto Role do Boto3.

def attach_policy(role_name, policy_arn): """ Attaches a policy to a role. :param role_name: The name of the role. **Note** this is the name, not the ARN. :param policy_arn: The ARN of the policy. """ try: iam.Role(role_name).attach_policy(PolicyArn=policy_arn) logger.info("Attached policy %s to role %s.", policy_arn, role_name) except ClientError: logger.exception("Couldn't attach policy %s to role %s.", policy_arn, role_name) raise
  • Para obter detalhes da API, consulte AttachRolePolicy na Referência da API do AWS SDK para Python (Boto3).

Ruby
SDK for Ruby
dica

Para saber mais sobre como configurar e executar esse exemplo, consulte o GitHub.

# Creates a policy that grants permission to list S3 buckets in the account, and # then attaches the policy to a role. # # @param policy_name [String] The name to give the policy. # @param role [Aws::IAM::Role] The role that the policy is attached to. # @return [Aws::IAM::Policy] The newly created policy. def create_and_attach_role_policy(policy_name, role) policy = @iam_resource.create_policy( policy_name: policy_name, policy_document: { Version: "2012-10-17", Statement: [{ Effect: "Allow", Action: "s3:ListAllMyBuckets", Resource: "arn:aws:s3:::*" }] }.to_json) role.attach_policy(policy_arn: policy.arn) puts("Created policy #{policy.policy_name} and attached it to role #{role.name}.") rescue Aws::Errors::ServiceError => e puts("Couldn't create a policy and attach it to role #{role.name}. Here's why: ") puts("\t#{e.code}: #{e.message}") raise else policy end
  • Para obter detalhes da API, consulte AttachRolePolicy na Referência da API do AWS SDK for Ruby.

Rust
SDK for Rust
nota

Esta documentação destina-se a um SDK na versão de previsualização. O SDK está sujeito a alterações e não deve ser usado em ambientes de produção.

dica

Para saber mais sobre como configurar e executar esse exemplo, consulte o GitHub.

pub async fn attach_role_policy( client: &iamClient, role: &Role, policy: &Policy, ) -> Result<AttachRolePolicyOutput, SdkError<AttachRolePolicyError>> { client .attach_role_policy() .role_name(role.role_name.as_ref().unwrap()) .policy_arn(policy.arn.as_ref().unwrap()) .send() .await }
  • Para obter detalhes da API, consulte AttachRolePolicy na Referência da API do AWS SDK for Rust.

Para obter uma lista completa dos Guias do desenvolvedor do SDK da AWS e exemplos de código, consulte Usar o IAM com um AWS SDK. Este tópico também inclui informações sobre como começar e detalhes sobre versões anteriores do SDK.