Menu
AWS SDK for JavaScript
Developer Guide for SDK version 2.122.0

Working with IAM Policies


                                        Relationship between JavaScript environments, the SDK, and Lambda

This Node.js example shows you how to:

  • Create and delete IAM policies

  • Attach and detach IAM policies from roles

The Scenario

You grant permissions to a user by creating a policy, which is a document that lists the actions that a user can perform and the resources those actions can affect. Any actions or resources that are not explicitly allowed are denied by default. Policies can be created and attached to users, groups of users, roles assumed by users, and resources.

In this example, a series of Node.js modules are used to manage policies in IAM. The Node.js modules use the SDK for JavaScript to create and delete policies as well as attaching and detaching role policies using these methods of the AWS.IAM client class:

For more information about IAM users, see Overview of Access Management: Permissions and Policies in the IAM User Guide.

Prerequisite Tasks

To set up and run this example, you must first complete these tasks:

  • Install Node.js. For more information about installing Node.js, see the Node.js website.

  • Create a JSON file named config.json with your credentials and the region setting. For more information about providing your credentials using a JSON file, see Loading Credentials in Node.js from a JSON File.

  • Create an IAM role to which you can attach policies. For more information about creating roles, see Creating IAM Roles in the IAM User Guide.

Configuring the SDK

Configure the SDK for JavaScript by creating a global configuration object, setting the region, and providing credentials for your code. In this example, the credentials are provided using the JSON file you created.

Copy
// Load the SDK for JavaScript var AWS = require('aws-sdk'); // Load credentials and set the region from the JSON file AWS.config.loadFromPath('./config.json');

Creating an IAM Policy

Create a Node.js module with the file name iam_createpolicy.js. Be sure to configure the SDK as previously shown. To access IAM, create an AWS.IAM service object. Create two JSON objects, one containing the policy document you want to create and the other containing the parameters needed to create the policy, which includes the policy JSON and the name you want to give the policy. Be sure to stringify the policy JSON object in the parameters. Call the createPolicy method of the AWS.IAM service object.

Copy
// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Load credentials and set region from JSON file AWS.config.loadFromPath('./config.json'); // 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) { throw err; } else { console.log("New Policy: ", data); } });

To run the example, type the following at the command line.

Copy
node iam_createpolicy.js

This sample code can be found here on GitHub.

Getting an IAM Policy

Create a Node.js module with the file name iam_getpolicy.js. Be sure to configure the SDK as previously shown. To access IAM, create an AWS.IAM service object. Create a JSON object containing the parameters needed retrieve a policy, which is the ARN of the policy you want to get. Call the getPolicy method of the AWS.IAM service object. Write the policy description to the console.

Copy
// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Load credentials and set region from JSON file AWS.config.loadFromPath('./config.json'); // 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) { throw err; } else { console.log(params.PolicyArn + ' - ' + data.Policy.Description); } });

To run the example, type the following at the command line.

Copy
node iam_getpolicy.js

This sample code can be found here on GitHub.

Attaching a Managed Role Policy

Create a Node.js module with the file name iam_attachrolepolicy.js. Be sure to configure the SDK as previously shown. To access IAM, create an AWS.IAM service object. Create a JSON object containing the parameters needed to get a list of managed IAM policies attached to a role, which consists of the name of the role. Provide the role name as a command-line parameter. Call the listAttachedRolePolicies method of the AWS.IAM service object, which returns an array of managed policies to the callback function.

Check the array members to see if the policy you want to attach to the role is already attached. If the policy is not attached, call the attachRolePolicy method to attach it.

Copy
// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Load credentials and set region from JSON file AWS.config.loadFromPath('./config.json'); // Create the IAM service object var iam = new AWS.IAM({apiVersion: '2010-05-08'}); var paramsRoleList = { RoleName: process.argv[2] }; var policyName = 'AmazonDynamoDBFullAccess'; var policyArn = 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess'; iam.listAttachedRolePolicies(paramsRoleList).eachPage(function(err, data) { if (err) { throw err; } if (data && data.AttachedPolicies) { data.AttachedPolicies.forEach(function(rolePolicy) { if (rolePolicy.PolicyName === policyName) { console.log(policyName + ' is already attached to this role.'); process.exit(); } }); } else { // there are no more results when data is null var params = { PolicyArn: policyArn, RoleName: process.argv[2] }; iam.attachRolePolicy(params, function(err, data) { if (err) { console.error('Unable to attach policy to role.'); throw err; } else { console.log('Role attached successfully.'); } }); } });

To run the example, type the following at the command line.

Copy
node iam_attachrolepolicy.js IAM_ROLE_NAME

Detaching a Managed Role Policy

Create a Node.js module with the file name iam_detachrolepolicy.js. Be sure to configure the SDK as previously shown. To access IAM, create an AWS.IAM service object. Create a JSON object containing the parameters needed to get a list of managed IAM policies attached to a role, which consists of the name of the role. Provide the role name as a command-line parameter. Call the listAttachedRolePolicies method of the AWS.IAM service object, which returns an array of managed policies in the callback function.

Check the array members to see if the policy you want to detach from the role is attached. If the policy is attached, call the detachRolePolicy method to detach it.

Copy
// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Load credentials and set region from JSON file AWS.config.loadFromPath('./config.json'); // Create the IAM service object var iam = new AWS.IAM({apiVersion: '2010-05-08'}); var paramsRoleList = { RoleName: process.argv[2] }; var policyName = 'AmazonDynamoDBFullAccess'; var policyArn = 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess'; iam.listAttachedRolePolicies(paramsRoleList).eachPage(function(err, data, done) { if (err) { throw err; } var foundPolicy = false; if (data && data.AttachedPolicies) { data.AttachedPolicies.forEach(function(rolePolicy) { if (rolePolicy.PolicyName !== policyName) { return; } foundPolicy = true; var params = { PolicyArn: policyArn, RoleName: process.argv[2] }; iam.detachRolePolicy(params, function(err, data) { if (err) { console.error('Unable to detach policy from role.'); throw err; } else { console.log('Policy detached from role successfully.'); process.exit(); } }); }); if (!foundPolicy) { done(); } } else { console.log('Policy was not attached to the role.'); } });

To run the example, type the following at the command line.

Copy
node iam_detachrolepolicy.js IAM_ROLE_NAME