Menu
AWS SDK for JavaScript
Developer Guide for SDK v2.154.0

Working with IAM Policies

JavaScript code example that applies to Node.js execution

This Node.js code example shows:

  • How to create and delete IAM policies.

  • How to 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:

Configuring the SDK

Configure the SDK for JavaScript by creating a global configuration object then setting the region for your code. In this example, the region is set to us-west-2.

Copy
// Load the SDK for JavaScript var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'us-west-2'});

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'); // 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) { 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'); // 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) { 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'); // 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] }; 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'); // Set 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] }; 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