How do I attach EC2 DescribeInstances permission to an IAM role?
To attach the EC2 DescribeInstances
permission to an IAM role using Pulumi, you need to create an IAM role, define a policy that includes the DescribeInstances
action, and attach the policy to the role. Here is how you can do it:
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Create an IAM Role
const ec2Role = new aws.iam.Role("ec2Role", {
assumeRolePolicy: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Action: "sts:AssumeRole",
Principal: {
Service: "ec2.amazonaws.com",
},
Effect: "Allow",
Sid: "",
},
],
}),
});
// Define the policy that allows DescribeInstances
const describeInstancesPolicy = new aws.iam.Policy("describeInstancesPolicy", {
description: "A policy that allows EC2 DescribeInstances",
policy: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Action: "ec2:DescribeInstances",
Effect: "Allow",
Resource: "*",
},
],
}),
});
// Attach the policy to the role
const rolePolicyAttachment = new aws.iam.RolePolicyAttachment("rolePolicyAttachment", {
role: ec2Role.name,
policyArn: describeInstancesPolicy.arn,
});
// Export the role ARN
export const roleArn = ec2Role.arn;
In this program:
- We create an IAM role (
ec2Role
) with a trust policy that allows EC2 to assume the role. - We define a policy (
describeInstancesPolicy
) that grants theec2:DescribeInstances
permission. - We attach this policy to the IAM role using a
RolePolicyAttachment
. - Finally, we export the ARN of the role for reference.
This setup ensures that the IAM role has the necessary permissions to describe EC2 instances.
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.