How do I provision IAM Instance Profiles with EC2 Launch Templates on AWS?
In this example, we will provision an IAM Instance Profile and use it with an EC2 Launch Template on AWS. An IAM Instance Profile allows EC2 instances to securely access AWS services. The EC2 Launch Template helps in creating EC2 instances with predefined configurations.
Key Points:
- Create an IAM Role with a policy allowing access to specific AWS services.
- Create an IAM Instance Profile and associate it with the IAM Role.
- Create an EC2 Launch Template using the IAM Instance Profile.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Create an IAM Role
const role = new aws.iam.Role("myRole", {
assumeRolePolicy: JSON.stringify({
Version: "2012-10-17",
Statement: [{
Action: "sts:AssumeRole",
Principal: {
Service: "ec2.amazonaws.com",
},
Effect: "Allow",
Sid: "",
}],
}),
});
// Attach a policy to the IAM Role
const rolePolicy = new aws.iam.RolePolicy("myRolePolicy", {
role: role.id,
policy: JSON.stringify({
Version: "2012-10-17",
Statement: [{
Action: [
"s3:ListBucket",
"s3:GetObject",
],
Effect: "Allow",
Resource: "*",
}],
}),
});
// Create an IAM Instance Profile
const instanceProfile = new aws.iam.InstanceProfile("myInstanceProfile", {
role: role.name,
});
// Create an EC2 Launch Template
const launchTemplate = new aws.ec2.LaunchTemplate("myLaunchTemplate", {
iamInstanceProfile: {
name: instanceProfile.name,
},
imageId: "ami-0c55b159cbfafe1f0", // Example AMI ID, replace with a valid one
instanceType: "t2.micro",
keyName: "my-key-pair", // Replace with your key pair name
tags: {
Name: "MyLaunchTemplate",
},
});
export const launchTemplateId = launchTemplate.id;
export const instanceProfileArn = instanceProfile.arn;
Summary:
In this example, we created an IAM Role with a policy that allows access to certain AWS services. We then created an IAM Instance Profile and associated it with the IAM Role. Finally, we created an EC2 Launch Template that uses the IAM Instance Profile. This setup allows EC2 instances launched from this template to assume the IAM Role and access the specified AWS services securely.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.