How do I grant an IAM role to an ECS task for RDS database connection in AWS?
In this example, we will grant an IAM Role to an ECS Task to allow it to connect to an RDS database. This involves creating an IAM Role, attaching the necessary policy to the role that permits RDS access, and linking the role to an ECS Task Definition.
Here’s a detailed explanation:
- IAM Role: We’ll create an IAM role that the ECS Task will assume.
- Policy Attachment: We’ll attach the Amazon RDS IAM policy to the role which includes permissions needed to connect to the RDS instance.
- ECS Task Definition: We’ll amend the ECS Task Definition to use the created IAM role.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const ecsTaskExecutionRole = new aws.iam.Role("ecs_task_execution_role", {
name: "ecs_task_execution_role",
assumeRolePolicy: JSON.stringify({
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Principal: {
Service: "ecs-tasks.amazonaws.com",
},
Action: "sts:AssumeRole",
}],
}),
});
const ecsTaskExecutionPolicy = new aws.iam.PolicyAttachment("ecs_task_execution_policy", {
name: "ecs_task_execution_policy",
roles: [ecsTaskExecutionRole.name],
policyArn: "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",
});
const rdsAccessPolicy = new aws.iam.Policy("rds_access_policy", {
name: "rds_access_policy",
policy: JSON.stringify({
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Action: [
"rds:DescribeDBInstances",
"rds:Connect",
],
Resource: "*",
}],
}),
});
const ecsTaskRdsPolicyAttachment = new aws.iam.RolePolicyAttachment("ecs_task_rds_policy_attachment", {
role: ecsTaskExecutionRole.name,
policyArn: rdsAccessPolicy.arn,
});
const example = new aws.ecs.TaskDefinition("example", {
family: "example",
containerDefinitions: JSON.stringify([{
name: "example",
image: "your-docker-image",
essential: true,
environment: [{
name: "RDS_HOST",
value: "your-rds-database.endpoint",
}],
}]),
executionRoleArn: ecsTaskExecutionRole.arn,
taskRoleArn: ecsTaskExecutionRole.arn,
networkMode: "awsvpc",
requiresCompatibilities: ["FARGATE"],
cpu: "256",
memory: "512",
});
export const ecsTaskExecutionRoleArn = ecsTaskExecutionRole.arn;
export const ecsTaskDefinitionFamily = example.family;
In summary, we created an IAM role with policies that allow it to connect to RDS and assigned this role to an ECS Task Definition, ensuring the ECS task can assume this role and access the RDS database.
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.