1. Answers
  2. Building AWS IAM Instance Profiles

How do I build an AWS IAM instanceprofile?

To manage AWS IAM roles and instance profiles, you need to define these resources: aws_iam_role, aws_iam_role_policy, and aws_iam_instance_profile. Here’s a breakdown of what each resource does:

  • aws_iam_role: This is the IAM role that the instance profile will assume.
  • aws_iam_role_policy: This policy will be attached to the IAM role, defining what AWS services or resources the role can access.
  • aws_iam_instance_profile: This resource is a wrapper for the IAM role, allowing EC2 instances to use it.

Here is an example of how these resources come together:

import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

// Define the IAM role
const example = new aws.iam.Role("example", {
    name: "example-role",
    assumeRolePolicy: JSON.stringify({
        Version: "2012-10-17",
        Statement: [{
            Action: "sts:AssumeRole",
            Effect: "Allow",
            Principal: {
                Service: "ec2.amazonaws.com",
            },
        }],
    }),
});
// Define a policy to attach to the role
const exampleRolePolicy = new aws.iam.RolePolicy("example", {
    name: "example-policy",
    role: example.id,
    policy: JSON.stringify({
        Version: "2012-10-17",
        Statement: [{
            Action: [
                "s3:ListBucket",
                "s3:GetObject",
            ],
            Effect: "Allow",
            Resource: "*",
        }],
    }),
});
// Create the instance profile
const exampleInstanceProfile = new aws.iam.InstanceProfile("example", {
    name: "example-instance-profile",
    role: example.name,
});
export const roleName = example.name;
export const instanceProfileName = exampleInstanceProfile.name;

In this program:

  • The aws_iam_role resource creates an IAM role with a trust policy that allows EC2 instances to assume this role.
  • The aws_iam_role_policy resource attaches a policy to the IAM role, granting specific permissions.
  • The aws_iam_instance_profile resource creates an instance profile wrapping the IAM role.
  • Outputs are defined for the role and instance profile names for use elsewhere.

In summary, you’ve created an IAM role with a policy, attached that policy to the role, and then created an instance profile for EC2 instances.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up