Criar uma política do IAM usando um AWS SDK - AWS Identity and Access Management

Criar uma política do IAM usando um AWS SDK

Os exemplos de código a seguir mostram como criar uma política do IAM.

.NET
AWS SDK for .NET
dica

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

/// <summary> /// Create a policy to allow a user to list the buckets in an account. /// </summary> /// <param name="client">The initialized IAM client object.</param> /// <param name="policyName">The name of the poicy to create.</param> /// <param name="policyDocument">The permissions policy document.</param> /// <returns>The newly created ManagedPolicy object.</returns> public static async Task<ManagedPolicy> CreatePolicyAsync( AmazonIdentityManagementServiceClient client, string policyName, string policyDocument) { var request = new CreatePolicyRequest { PolicyName = policyName, PolicyDocument = policyDocument, }; var response = await client.CreatePolicyAsync(request); return response.Policy; }
  • Para obter detalhes, consulte CreatePolicy 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.

// CreatePolicy fmt.Println("🔐 CreatePolicy") policyDocument := `{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Query", "dynamodb:Scan", "dynamodb:UpdateItem" ], "Resource": [ "arn:aws:dynamodb:us-west-2:123456789012:table/mytable", "arn:aws:dynamodb:us-west-2:123456789012:table/mytable/*" ] } ] }` createPolicyResult, err := service.CreatePolicy(context.Background(), &iam.CreatePolicyInput{ PolicyDocument: &policyDocument, PolicyName: aws.String(ExamplePolicyName), }) if err != nil { panic("Couldn't create policy!" + err.Error()) } fmt.Print("Created a new policy: " + *createPolicyResult.Policy.Arn)
  • Para obter detalhes, consulte CreatePolicy 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 String createIAMPolicy(IamClient iam, String policyName ) { try { // Create an IamWaiter object. IamWaiter iamWaiter = iam.waiter(); CreatePolicyRequest request = CreatePolicyRequest.builder() .policyName(policyName) .policyDocument(PolicyDocument) .build(); CreatePolicyResponse response = iam.createPolicy(request); // Wait until the policy is created. GetPolicyRequest polRequest = GetPolicyRequest.builder() .policyArn(response.policy().arn()) .build(); WaiterResponse<GetPolicyResponse> waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest); waitUntilPolicyExists.matched().response().ifPresent(System.out::println); return response.policy().arn(); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return "" ; }
  • Para obter detalhes, consulte CreatePolicy 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 };

Crie a política.

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { CreatePolicyCommand } from "@aws-sdk/client-iam"; // Set the parameters. const myManagedPolicy = { Version: "2012-10-17", Statement: [ { Effect: "Allow", Action: "logs:CreateLogGroup", Resource: "RESOURCE_ARN", // RESOURCE_ARN }, { Effect: "Allow", Action: [ "dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Scan", "dynamodb:UpdateItem", ], Resource: "DYNAMODB_POLICY_NAME", // DYNAMODB_POLICY_NAME; For example, "myDynamoDBName". }, ], }; export const params = { PolicyDocument: JSON.stringify(myManagedPolicy), PolicyName: "IAM_POLICY_NAME", }; export const run = async () => { try { const data = await iamClient.send(new CreatePolicyCommand(params)); console.log("Success", data); return data; } 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 myManagedPolicy = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "logs:CreateLogGroup", "Resource": "RESOURCE_ARN" }, { "Effect": "Allow", "Action": [ "dynamodb:DeleteItem", "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:Scan", "dynamodb:UpdateItem" ], "Resource": "RESOURCE_ARN" } ] }; var params = { PolicyDocument: JSON.stringify(myManagedPolicy), PolicyName: 'myDynamoDBPolicy', }; iam.createPolicy(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });
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 createIAMPolicy(policyNameVal: String?): String { val policyDocumentVal = "{" + " \"Version\": \"2012-10-17\"," + " \"Statement\": [" + " {" + " \"Effect\": \"Allow\"," + " \"Action\": [" + " \"dynamodb:DeleteItem\"," + " \"dynamodb:GetItem\"," + " \"dynamodb:PutItem\"," + " \"dynamodb:Scan\"," + " \"dynamodb:UpdateItem\"" + " ]," + " \"Resource\": \"*\"" + " }" + " ]" + "}" val request = CreatePolicyRequest { policyName = policyNameVal policyDocument = policyDocumentVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> val response = iamClient.createPolicy(request) return response.policy?.arn.toString() } }
  • Para obter detalhes da API, consulte CreatePolicy 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(); $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"; public function createPolicy(string $policyName, string $policyDocument) { $result = $this->customWaiter(function () use ($policyName, $policyDocument) { return $this->iamClient->createPolicy([ 'PolicyName' => $policyName, 'PolicyDocument' => $policyDocument, ]); }); return $result['Policy']; }
  • Para obter detalhes, consulte CreatePolicy 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.

def create_policy(name, description, actions, resource_arn): """ Creates a policy that contains a single statement. :param name: The name of the policy to create. :param description: The description of the policy. :param actions: The actions allowed by the policy. These typically take the form of service:action, such as s3:PutObject. :param resource_arn: The Amazon Resource Name (ARN) of the resource this policy applies to. This ARN can contain wildcards, such as 'arn:aws:s3:::my-bucket/*' to allow actions on all objects in the bucket named 'my-bucket'. :return: The newly created policy. """ policy_doc = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": actions, "Resource": resource_arn } ] } try: policy = iam.create_policy( PolicyName=name, Description=description, PolicyDocument=json.dumps(policy_doc)) logger.info("Created policy %s.", policy.arn) except ClientError: logger.exception("Couldn't create policy %s.", name) raise else: return policy
  • Para obter detalhes da API, consulte CreatePolicy 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, consulte CreatePolicy 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 create_policy( client: &iamClient, policy_name: &str, policy_document: &str, ) -> Result<Policy, iamError> { let policy = client .create_policy() .policy_name(policy_name) .policy_document(policy_document) .send() .await?; Ok(policy.policy.unwrap()) }
  • Para obter detalhes da API, consulte CreatePolicy 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.