1. Answers
  2. Set instance role in AWS Auto Scaling group

How do I set an instance role in an AWS Auto Scaling group?

In this example, we will create an AWS Auto Scaling group and assign an IAM role to the instances within the group. This will involve creating an IAM role, an instance profile, a launch configuration, and the Auto Scaling group itself.

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

// Create an IAM role
const role = new aws.iam.Role("exampleRole", {
    assumeRolePolicy: aws.iam.assumeRolePolicyForPrincipal({ Service: "ec2.amazonaws.com" }),
});

// Attach a policy to the role
const policy = new aws.iam.RolePolicy("examplePolicy", {
    role: role.id,
    policy: JSON.stringify({
        Version: "2012-10-17",
        Statement: [{
            Action: "sts:AssumeRole",
            Effect: "Allow",
            Resource: "*",
        }],
    }),
});

// Create an instance profile
const instanceProfile = new aws.iam.InstanceProfile("exampleInstanceProfile", {
    role: role.name,
});

// Create a launch configuration
const launchConfig = new aws.ec2.LaunchConfiguration("exampleLaunchConfig", {
    imageId: "ami-0c55b159cbfafe1f0", // Example AMI ID
    instanceType: "t2.micro",
    iamInstanceProfile: instanceProfile.name,
});

// Create an Auto Scaling group
const autoScalingGroup = new aws.autoscaling.Group("exampleAutoScalingGroup", {
    launchConfiguration: launchConfig.id,
    minSize: 1,
    maxSize: 2,
    desiredCapacity: 1,
    vpcZoneIdentifiers: ["subnet-0bb1c79de3EXAMPLE"], // Example subnet ID
    tags: [{
        key: "Name",
        value: "example-asg",
        propagateAtLaunch: true,
    }],
});

// Export the name of the Auto Scaling group
export const autoScalingGroupName = autoScalingGroup.name;

Key Points

  • IAM Role: Created to define permissions and policies for the instances.
  • Instance Profile: Associates the IAM role with EC2 instances.
  • Launch Configuration: Specifies the instance settings, including the IAM instance profile.
  • Auto Scaling Group: Manages the group of instances and their scaling policies.

Summary

We created an AWS Auto Scaling group and assigned an IAM role to the instances within the group using Pulumi. This involved creating an IAM role, attaching a policy to it, creating an instance profile, setting up a launch configuration, and finally creating the Auto Scaling group.

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