使用软件开发工具包的 IAM 示例 JavaScript V3 - AWS SDK for JavaScript

帮助我们改进AWS SDK for JavaScript版本 3 (V3) 文档,方法是使用反馈链接,或者在上创建议题或拉取请求GitHub.

这些区域有:AWS SDK for JavaScriptV3 API 参考指南详细描述了所有的 API 操作AWS SDK for JavaScript版本 3 (V3)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用软件开发工具包的 IAM 示例 JavaScript V3

以下代码示例显示如何使用AWS SDK for JavaScript使用 IAM 的 V3。

操作展示如何调用具体的 IAM 函数的代码节选。

方案展示如何通过调用多个 IAAAM 函数来完成特定任务的代码示例。

每个示例都包含一个指向以下内容的链接 GitHub其中包含了有关如何在上下文中设置和运行代码的说明。

操作

以下代码示例显示如何将 IAM policy 附加到角色。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

附加策略。

// 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();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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"); } }); } });

以下代码示例显示如何创建 IAM policy。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

创建策略。

// 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();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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); } });

以下代码示例显示如何创建 IAM 角色。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

创建角色。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { CreateRoleCommand } from "@aws-sdk/client-iam"; // Sample assume role policy JSON. const role_json = { Version: "2012-10-17", Statement: [ { Effect: "Allow", Principal: { AWS: "USER_ARN", // The ARN of the user. }, Action: "sts:AssumeRole", }, ], }; // Stringify the assume role policy JSON. const myJson = JSON.stringify(role_json); // Set the parameters. const params = { AssumeRolePolicyDocument: myJson, Path: "/", RoleName: "ROLE_NAME" }; const run = async () => { try { const data = await iamClient.send(new CreateRoleCommand(params)); console.log("Success. Role created. Role Arn: ", data.Role.RoleName); } catch (err) { console.log("Error", err); } }; run();
  • 有关API,请参阅。CreateRoleAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何创建 IAM 服务相关角色。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

创建服务相关角色。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { CreateServiceLinkedRoleCommand } from "@aws-sdk/client-iam"; // Set the parameters. const params = { AWSServiceName: "AWS_SERVICE_NAME" /* required */, }; const run = async () => { try { const data = await iamClient.send( new CreateServiceLinkedRoleCommand(params) ); console.log("Success", data); } catch (err) { console.log("Error", err); } }; run();

以下代码示例显示如何创建 IAM 用户。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

创建用户。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { GetUserCommand, CreateUserCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { UserName: "USER_NAME" }; //USER_NAME export const run = async () => { try { const data = await iamClient.send(new GetUserCommand(params)); console.log( "User " + "USER_NAME" + " already exists", data.User.UserId ); return data; } catch (err) { try { const results = await iamClient.send(new CreateUserCommand(params)); console.log("Success", results); return results; } catch (err) { console.log("Error", err); } } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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 params = { UserName: process.argv[2] }; iam.getUser(params, function(err, data) { if (err && err.code === 'NoSuchEntity') { iam.createUser(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } }); } else { console.log("User " + process.argv[2] + " already exists", data.User.UserId); } });

以下代码示例显示如何创建 IAM 访问密钥。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

创建访问密钥。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { CreateAccessKeyCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = {UserName: "IAM_USER_NAME"}; //IAM_USER_NAME export const run = async () => { try { const data = await iamClient.send(new CreateAccessKeyCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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'}); iam.createAccessKey({UserName: 'IAM_USER_NAME'}, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.AccessKey); } });

以下代码示例显示如何为 IAM 账户创建别名。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

创建账户别名。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { CreateAccountAliasCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { AccountAlias: "ACCOUNT_ALIAS" }; //ACCOUNT_ALIAS export const run = async () => { try { const data = await iamClient.send(new CreateAccountAliasCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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'}); iam.createAccountAlias({AccountAlias: process.argv[2]}, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

以下代码示例显示如何删除 IAM policy。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

删除策略。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { DeletePolicyCommand } from "@aws-sdk/client-iam"; // Set the parameters. const params = { PolicyArn: "POLICY_ARN"}; const run = async () => { try { const data = await iamClient.send(new DeletePolicyCommand(params)); console.log("Success. Policy deleted.", data); } catch (err) { console.log("Error", err); } }; run();
  • 有关API,请参阅。DeletePolicyAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何删除 IAM 角色。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

删除角色。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { DeleteRoleCommand } from "@aws-sdk/client-iam"; // Set the parameters. const params = { RoleName: "ROLE_NAME" } const run = async () => { try { const data = await iamClient.send(new DeleteRoleCommand(params)); console.log("Success. Role deleted.", data); } catch (err) { console.log("Error", err); } }; run();
  • 有关API,请参阅。DeleteRoleAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何删除 IAM 服务器证书。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

删除服务器证书。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { DeleteServerCertificateCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { ServerCertificateName: "CERTIFICATE_NAME" }; // CERTIFICATE_NAME export const run = async () => { try { const data = await iamClient.send( new DeleteServerCertificateCommand(params) ); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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'}); iam.deleteServerCertificate({ServerCertificateName: 'CERTIFICATE_NAME'}, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

以下代码示例显示如何删除 IAM 用户。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

请删除用户。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { DeleteUserCommand, GetUserCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { UserName: "USER_NAME" }; //USER_NAME export const run = async () => { try { const data = await iamClient.send(new GetUserCommand(params)); return data; try { const results = await iamClient.send(new DeleteUserCommand(params)); console.log("Success", results); return results; } catch (err) { console.log("Error", err); } } catch (err) { console.log("User " + "USER_NAME" + " does not exist."); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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 params = { UserName: process.argv[2] }; iam.getUser(params, function(err, data) { if (err && err.code === 'NoSuchEntity') { console.log("User " + process.argv[2] + " does not exist."); } else { iam.deleteUser(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } }); } });

以下代码示例显示如何删除 IAM 访问密钥。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

删除访问密钥。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { DeleteAccessKeyCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { AccessKeyId: "ACCESS_KEY_ID", // ACCESS_KEY_ID UserName: "USER_NAME", // USER_NAME }; export const run = async () => { try { const data = await iamClient.send(new DeleteAccessKeyCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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 params = { AccessKeyId: 'ACCESS_KEY_ID', UserName: 'USER_NAME' }; iam.deleteAccessKey(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

以下代码示例显示如何删除 IAM 账户别名。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

删除账户别名。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { DeleteAccountAliasCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { AccountAlias: "ALIAS" }; // ALIAS export const run = async () => { try { const data = await iamClient.send(new DeleteAccountAliasCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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'}); iam.deleteAccountAlias({AccountAlias: process.argv[2]}, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

以下代码示例显示如何从角色分离 IAM policy。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

分离策略。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { ListAttachedRolePoliciesCommand, DetachRolePolicyCommand, } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { RoleName: "ROLE_NAME" }; //ROLE_NAME export const run = async () => { try { const data = await iamClient.send( new ListAttachedRolePoliciesCommand(params) ); return data; const myRolePolicies = data.AttachedPolicies; myRolePolicies.forEach(function (val, index, array) { if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") { const params = { PolicyArn: "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess", paramsRoleList, }; try { const results = iamClient.send( new DetachRolePolicyCommand(paramsRoleList) ); console.log("Policy detached from role successfully"); process.exit(); } catch (err) { console.log("Unable to detach policy from role", err); } } else { } }); } catch (err) { console.log("User " + "USER_NAME" + " does not exist."); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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') { var params = { PolicyArn: 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess', RoleName: process.argv[2] }; iam.detachRolePolicy(params, function(err, data) { if (err) { console.log("Unable to detach policy from role", err); } else { console.log("Policy detached from role successfully"); process.exit(); } }); } }); } });

以下代码示例显示如何获取 IAM policy。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

获取策略。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { GetPolicyCommand } from "@aws-sdk/client-iam"; // Set the parameters. const params = { PolicyArn: "POLICY_ARN" /* required */, }; const run = async () => { try { const data = await iamClient.send(new GetPolicyCommand(params)); console.log("Success", data.Policy); } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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 params = { PolicyArn: 'arn:aws:iam::aws:policy/AWSLambdaExecute' }; iam.getPolicy(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Policy.Description); } });

以下代码示例显示如何获取 IAM 角色。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

获取角色。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { GetRoleCommand } from "@aws-sdk/client-iam"; // Set the parameters. const params = { RoleName: "ROLE_NAME" /* required */ }; const run = async () => { try { const data = await iamClient.send(new GetRoleCommand(params)); console.log("Success", data.Role); } catch (err) { console.log("Error", err); } }; run();
  • 有关API,请参阅。GetRoleAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何获取 IAM 服务器证书。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

获取服务器证书。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { GetServerCertificateCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { ServerCertificateName: "CERTIFICATE_NAME" }; //CERTIFICATE_NAME export const run = async () => { try { const data = await iamClient.send(new GetServerCertificateCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } };
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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'}); iam.getServerCertificate({ServerCertificateName: 'CERTIFICATE_NAME'}, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

以下代码示例显示如何获取有关上次使用 IAM 访问密钥的数据。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

获取访问密钥。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { GetAccessKeyLastUsedCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { AccessKeyId: "ACCESS_KEY_ID" }; //ACCESS_KEY_ID export const run = async () => { try { const data = await iamClient.send(new GetAccessKeyLastUsedCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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'}); iam.getAccessKeyLastUsed({AccessKeyId: 'ACCESS_KEY_ID'}, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.AccessKeyLastUsed); } });

以下代码示例显示如何获取 IAM 账户密码策略。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

获取账户密码策略。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { GetAccountPasswordPolicyCommand } from "@aws-sdk/client-iam"; const run = async () => { try { const data = await iamClient.send(new GetAccountPasswordPolicyCommand({})); console.log("Success", data.PasswordPolicy); } catch (err) { console.log("Error", err); } }; run();

以下代码示例显示如何列出 IAM 的 SAML 提供商。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

列出 SAML 提供商。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import {ListSAMLProvidersCommand} from "@aws-sdk/client-iam"; export const run = async () => { try { const results = await iamClient.send(new ListSAMLProvidersCommand({})); console.log("Success", results); return results; } catch (err) { console.log("Error", err); } } run();
  • 有关 API 详细信息,请参阅《AWS SDK for JavaScript API 参考》中的 ListSAMLProviders

以下代码示例显示如何列出用户的 IAM 访问密钥。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

列出访问密钥。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { ListAccessKeysCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { MaxItems: 5, UserName: "IAM_USER_NAME", //IAM_USER_NAME }; export const run = async () => { try { const data = await iamClient.send(new ListAccessKeysCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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 params = { MaxItems: 5, UserName: 'IAM_USER_NAME' }; iam.listAccessKeys(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

以下代码示例显示如何列出 IAM 账户别名。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

列出账户别名。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { ListAccountAliasesCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { MaxItems: 5 }; export const run = async () => { try { const data = await iamClient.send(new ListAccountAliasesCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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'}); iam.listAccountAliases({MaxItems: 10}, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

以下代码示例显示如何列出 IAM 组。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

列出组。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import {ListGroupsCommand} from "@aws-sdk/client-iam"; // Set the parameters. export const params = { RoleName: 'ROLE_NAME', /* This is a number value. Required */ Marker: 'MARKER', /* This is a string value. Optional */ MaxItems: 'MAX_ITEMS' /* This is a number value. Optional */ }; export const run = async () => { try { const data = await iamClient.send(new ListGroupsCommand({})); console.log("Success", data.Groups); } catch (err) { console.log("Error", err); } } run();
  • 有关API,请参阅。ListGroupsAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何列出 IAM 角色的内联策略。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

列出策略。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import {ListRolePoliciesCommand} from "@aws-sdk/client-iam"; // Set the parameters. export const params = { RoleName: 'ROLE_NAME', /* This is a number value. Required */ Marker: 'MARKER', /* This is a string value. Optional */ MaxItems: 'MAX_ITEMS' /* This is a number value. Optional */ }; export const run = async () => { try { const results = await iamClient.send(new ListRolePoliciesCommand(params)); console.log("Success", results); return results; } catch (err) { console.log("Error", err); } } run();

以下代码示例显示如何列出 IAM policy。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

列出策略。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import {ListPoliciesCommand} from "@aws-sdk/client-iam"; // Set the parameters. export const params = { Marker: 'MARKER', MaxItems: 'MAX_ITEMS', OnlyAttached: "ONLY_ATTACHED", /* Options are "true" or "false"*/ PathPrefix: 'PATH_PREFIX', PolicyUsageFilter: "POLICY_USAGE_FILTER", /* Options are "PermissionsPolicy" or "PermissionsBoundary"*/ Scope: "SCOPE" /* Options are "All", "AWS", "Local"*/ }; export const run = async () => { try { const results = await iamClient.send(new ListPoliciesCommand(params)); console.log("Success", results); return results; } catch (err) { console.log("Error", err); } }; run();
  • 有关API,请参阅。ListPoliciesAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何列出附加到 IAM 角色的策略。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

列出附加到角色的策略。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import {ListAttachedRolePoliciesCommand} from "@aws-sdk/client-iam"; // Set the parameters. export const params = { RoleName: 'ROLE_NAME' /* required */ }; export const run = async () => { try { const data = await iamClient.send(new ListAttachedRolePoliciesCommand(params)); console.log("Success", data.AttachedPolicies); } catch (err) { console.log("Error", err); } } run();

以下代码示例演示如何列出 IAM 角色。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

列出角色。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { ListRolesCommand } from "@aws-sdk/client-iam"; // Set the parameters. const params = { Marker: 'MARKER', // This is a string value. MaxItems: 'MAX_ITEMS' // This is a number value. }; const run = async () => { try { const results = await iamClient.send(new ListRolesCommand(params)); console.log("Success", results); return results; } catch (err) { console.log("Error", err); } }; run();
  • 有关API,请参阅。ListRolesAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何列出 IAM 服务器证书。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

列出证书。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { ListServerCertificatesCommand } from "@aws-sdk/client-iam"; export const run = async () => { try { const data = await iamClient.send(new ListServerCertificatesCommand({})); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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'}); iam.listServerCertificates({}, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

以下代码示例演示如何列出 IAM 用户。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

列出用户。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { ListUsersCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { MaxItems: 10 }; export const run = async () => { try { const data = await iamClient.send(new ListUsersCommand(params)); return data; const users = data.Users || []; users.forEach(function (user) { console.log("User " + user.UserName + " created", user.CreateDate); }); } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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 params = { MaxItems: 10 }; iam.listUsers(params, function(err, data) { if (err) { console.log("Error", err); } else { var users = data.Users || []; users.forEach(function(user) { console.log("User " + user.UserName + " created", user.CreateDate); }); } });

以下代码示例演示了如何更新 IAM 服务器证书。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

更新服务器证书。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { UpdateServerCertificateCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { ServerCertificateName: "CERTIFICATE_NAME", //CERTIFICATE_NAME NewServerCertificateName: "NEW_CERTIFICATE_NAME", //NEW_CERTIFICATE_NAME }; export const run = async () => { try { const data = await iamClient.send( new UpdateServerCertificateCommand(params) ); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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 params = { ServerCertificateName: 'CERTIFICATE_NAME', NewServerCertificateName: 'NEW_CERTIFICATE_NAME' }; iam.updateServerCertificate(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

以下代码示例演示如何更新 IAM 用户。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

更新用户。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { UpdateUserCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { UserName: "ORIGINAL_USER_NAME", //ORIGINAL_USER_NAME NewUserName: "NEW_USER_NAME", //NEW_USER_NAME }; export const run = async () => { try { const data = await iamClient.send(new UpdateUserCommand(params)); console.log("Success, username updated"); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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 params = { UserName: process.argv[2], NewUserName: process.argv[3] }; iam.updateUser(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

以下代码示例演示如何更新 IAM 访问密钥。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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 };

更新访问密钥。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { UpdateAccessKeyCommand } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { AccessKeyId: "ACCESS_KEY_ID", //ACCESS_KEY_ID Status: "Active", UserName: "USER_NAME", //USER_NAME }; export const run = async () => { try { const data = await iamClient.send(new UpdateAccessKeyCommand(params)); console.log("Success", data); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅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 params = { AccessKeyId: 'ACCESS_KEY_ID', Status: 'Active', UserName: 'USER_NAME' }; iam.updateAccessKey(params, function(err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

场景

以下代码示例显示了如何:

  • 创建一个没有权限的用户。

  • 创建授予列出账户的 Amazon S3 存储桶的权限的角色

  • 添加策略以允许用户代入该角色。

  • 代入角色并使用临时凭证列出 Amazon S3 存储桶。

  • 删除策略、角色和用户。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

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

创建 IAM 用户和授予列出 Amazon S3 存储桶的权限的角色。用户仅具有代入该角色的权限。代入该角色后,使用临时凭证列出该账户的存储桶。

// Import required AWS SDK clients and commands for Node.js. import { iamClient, REGION } from "../libs/iamClient.js"; // Helper function that creates an IAM service client module. import { CreateUserCommand, CreateAccessKeyCommand, CreatePolicyCommand, CreateRoleCommand, AttachRolePolicyCommand, AttachUserPolicyCommand, DeleteAccessKeyCommand, DeleteUserCommand, DeleteRoleCommand, DeletePolicyCommand, DetachUserPolicyCommand, DetachRolePolicyCommand, } from "@aws-sdk/client-iam"; import { ListBucketsCommand, S3Client } from "@aws-sdk/client-s3"; import { AssumeRoleCommand, STSClient } from "@aws-sdk/client-sts"; if (process.argv.length < 6) { console.log( "Usage: node iam_basics.js <user name> <s3 policy name> <role name> <assume policy name>\n" + "Example: node iam_basics.js test-user my-s3-policy my-iam-role my-assume-role" ); } // Set the parameters. const region = REGION; const userName = process.argv[2]; const s3_policy_name = process.argv[3]; const role_name = process.argv[4]; const assume_policy_name = process.argv[5]; // Helper function to delay running the code while the AWS service calls wait for responses. function wait(ms) { var start = Date.now(); var end = start while (end < start + ms){ end = Date.now() } } export const run = async ( userName, s3_policy_name, role_name, assume_policy_name ) => { try { // Create a new user. const user_params = { UserName: userName }; console.log("\nCreating a user name " + user_params.UserName + "...\n"); const data = await iamClient.send( new CreateUserCommand({ UserName: userName }) ); const user_arn = data.User.Arn; const user_name = data.User.UserName; console.log( "User with name" + user_name + " and ARN " + user_arn + " created." ); try { // Create access keys for the new user. console.log( "\nCreating access keys for " + user_params.UserName + "...\n" ); const access_key_params = { UserName: user_name }; const data = await iamClient.send( new CreateAccessKeyCommand(access_key_params) ); console.log("Success. Access key created: ", data.AccessKey.AccessKeyId); var myAccessKey = data.AccessKey.AccessKeyId; var mySecretAccessKey = data.AccessKey.SecretAccessKey; try { // Attempt to list S3 buckets. console.log( "\nWaiting 10 seconds for user and access keys to be created...\n" ); wait(10000); console.log( "Attempt to list S3 buckets with the new user (without permissions)...\n" ); // Use the credentials for the new user that you created. var user_creds = { accessKeyId: myAccessKey, secretAccessKey: mySecretAccessKey, }; const s3Client = new S3Client({ credentials: user_creds, region: region, }); await s3Client.send(new ListBucketsCommand({})); } catch (err) { console.log( "Error. As expected the new user has no permissions to list buckets. ", err.stack ); console.log( "\nCreating policy to allow the new user to list all buckets, and to assume an STS role...\n" ); const myManagedPolicy = { Version: "2012-10-17", Statement: [ { Effect: "Allow", Action: ["s3:ListAllMyBuckets", "sts:AssumeRole"], Resource: "*", }, ], }; const policy_params = { PolicyDocument: JSON.stringify(myManagedPolicy), PolicyName: s3_policy_name, // Name of the new policy. }; const data = await iamClient.send( new CreatePolicyCommand(policy_params) ); console.log( "Success. Policy created that allows listing of all S3 buckets.\n" + "Policy ARN: " + data.Policy.Arn + "\n" + "Policy name: " + data.Policy.PolicyName + "\n" ); var s3_policy_arn = data.Policy.Arn; try { console.log( "\nCreating a role with a trust policy that lets the user assume the role....\n" ); const role_json = { Version: "2012-10-17", Statement: [ { Effect: "Allow", Principal: { AWS: user_arn, // The ARN of the user. }, Action: "sts:AssumeRole", }, ], }; const myJson = JSON.stringify(role_json); const role_params = { AssumeRolePolicyDocument: myJson, // Trust relationship policy document. Path: "/", RoleName: role_name // The name of the new role. }; const data = await iamClient.send(new CreateRoleCommand(role_params)); console.log("Success. Role created. Role Arn: ", data.Role.Arn); const role_arn = data.Role.Arn; try { console.log( "\nAttaching to the role the policy with permissions to list all buckets....\n" ); const params = { PolicyArn: s3_policy_arn, RoleName: role_name, }; await iamClient.send(new AttachRolePolicyCommand(params)); console.log("Success. Policy attached successfully to role."); try { console.log( "\nCreate a policy that enables the user to assume the role ....\n" ); const myNewPolicy = { Version: "2012-10-17", Statement: [ { Effect: "Allow", Action: ["sts:AssumeRole"], Resource: role_arn, }, ], }; const policy_params = { PolicyDocument: JSON.stringify(myNewPolicy), PolicyName: assume_policy_name, }; const data = await iamClient.send( new CreatePolicyCommand(policy_params) ); console.log( "Success. Policy created. Policy ARN: " + data.Policy.Arn ); const assume_policy_arn = data.Policy.Arn; try { console.log("\nAttaching the policy to the user.....\n"); const attach_policy_to_user_params = { PolicyArn: assume_policy_arn, UserName: user_name, }; const data = await iamClient.send( new AttachUserPolicyCommand(attach_policy_to_user_params) ); console.log( "\nWaiting 10 seconds for policy to be attached...\n" ); wait(10000); console.log( "Success. Policy attached to user " + user_name + "." ); try { console.log( "\nAssume for the user the role with permission to list all buckets....\n" ); const assume_role_params = { RoleArn: role_arn, //ARN_OF_ROLE_TO_ASSUME RoleSessionName: "session1", DurationSeconds: 900, }; // Create an AWS STS client with the credentials for the user. Remember, the user has permissions to assume roles using AWS STS. const stsClientWithUsersCreds = new STSClient({ credentials: user_creds, region: REGION, }); const data = await stsClientWithUsersCreds.send( new AssumeRoleCommand(assume_role_params) ); console.log( "Success assuming role. Access key id is " + data.Credentials.AccessKeyId + "\n" + "Secret access key is " + data.Credentials.SecretAccessKey ); const newAccessKey = data.Credentials.AccessKeyId; const newSecretAccessKey = data.Credentials.SecretAccessKey; console.log( "\nWaiting 10 seconds for the user to assume the role with permission to list all buckets...\n" ); wait(10000); // Set the parameters for the temporary credentials. This grants permission to list S3 buckets. var new_role_creds = { accessKeyId: newAccessKey, secretAccessKey: newSecretAccessKey, sessionToken: data.Credentials.SessionToken, }; try { console.log( "Listing the S3 buckets using the credentials of the assumed role... \n" ); // Create an S3 client with the temporary credentials. const s3ClientWithNewCreds = new S3Client({ credentials: new_role_creds, region: REGION, }); const data = await s3ClientWithNewCreds.send( new ListBucketsCommand({}) ); console.log("Success. Your S3 buckets are:", data.Buckets); try { console.log( "Detaching s3 policy from user " + userName + " ... \n" ); const data = await iamClient.send( new DetachUserPolicyCommand({ PolicyArn: assume_policy_arn, UserName: userName, }) ); console.log("Success, S3 policy detached from user."); try { console.log( "Detaching role policy from " + role_name + " ... \n" ); const data = await iamClient.send( new DetachRolePolicyCommand({ PolicyArn: s3_policy_arn, RoleName: role_name, }) ); console.log( "Success, assume policy detached from role." ); try { console.log("Deleting s3 policy ... \n"); const data = await iamClient.send( new DeletePolicyCommand({ PolicyArn: s3_policy_arn, }) ); console.log("Success, S3 policy deleted."); try { console.log("Deleting assume role policy ... \n"); const data = await iamClient.send( new DeletePolicyCommand({ PolicyArn: assume_policy_arn, }) ); try { console.log("Deleting access keys ... \n"); const data = await iamClient.send( new DeleteAccessKeyCommand({ UserName: userName, AccessKeyId: myAccessKey, }) ); try { console.log( "Deleting user " + user_name + " ... \n" ); const data = await iamClient.send( new DeleteUserCommand({ UserName: userName }) ); console.log("Success, user deleted."); try { console.log( "Deleting role " + role_name + " ... \n" ); const data = await iamClient.send( new DeleteRoleCommand({ RoleName: role_name, }) ); console.log("Success, role deleted."); return "Run successfully"; // For unit tests. } catch (err) { console.log("Error deleting role .", err); } } catch (err) { console.log("Error deleting user.", err); } } catch (err) { console.log("Error deleting access keys.", err); } } catch (err) { console.log( "Error detaching assume role policy from user.", err ); } } catch (err) { console.log("Error deleting role.", err); } } catch (err) { console.log("Error deleting user.", err); } } catch (err) { console.log("Error detaching S3 policy from role.", err); process.exit(1); } } catch (err) { console.log("Error listing S3 buckets.", err); process.exit(1); } } catch (err) { console.log("Error assuming role.", err); process.exit(1); } } catch (err) { console.log( "Error adding permissions to user to assume role.", err ); process.exit(1); } } catch (err) { console.log("Error assuming role.", err); process.exit(1); } } catch (err) { console.log("Error creating policy. ", err); process.exit(1); } } catch (err) { console.log("Error attaching policy to role.", err); process.exit(1); } } } catch (err) { console.log("Error creating access keys. ", err); process.exit(1); } } catch (err) { console.log("Error creating user. ", err); } }; run(userName, s3_policy_name, role_name, assume_policy_name);