How to extend default ALB controller policy using AWS CDK?
When working with TypeScript and AWS CDK, you may come across a situation where you need to extend the default Application Load Balancer (ALB) controller policy. In this blog post, we will explore two solutions to achieve this using AWS CDK.
Solution 1: Using the addManagedPolicy method
The first solution involves using the addManagedPolicy
method provided by the aws-eks
module in AWS CDK. This method allows us to add managed policies to the IAM role associated with the ALB controller.
Here’s an example code snippet that demonstrates how to extend the default ALB controller policy:
import * as eks from 'aws-eks';
import * as iam from 'aws-iam';
import * as cdk from 'aws-cdk-lib';
const stack = new cdk.Stack();
const cluster = new eks.Cluster(stack, 'MyCluster', {
version: eks.KubernetesVersion.V1_21,
});
const albControllerRole = cluster.awsAuth?.role;
if (albControllerRole) {
albControllerRole.addManagedPolicy(
iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonRDSFullAccess')
);
}
By using the addManagedPolicy
method, we can add any managed policy available in AWS IAM to the ALB controller role. In the example above, we added the AmazonRDSFullAccess
policy to the role.
Solution 2: Using the addToPolicy method
The second solution involves using the addToPolicy
method provided by the aws-iam
module in AWS CDK. This method allows us to directly add permissions to the IAM role associated with the ALB controller.
Here’s an example code snippet that demonstrates how to extend the default ALB controller policy using the addToPolicy
method:
import * as eks from 'aws-eks';
import * as iam from 'aws-iam';
import * as cdk from 'aws-cdk-lib';
const stack = new cdk.Stack();
const cluster = new eks.Cluster(stack, 'MyCluster', {
version: eks.KubernetesVersion.V1_21,
});
const albControllerRole = cluster.awsAuth?.role;
if (albControllerRole) {
albControllerRole.addToPolicy(
new iam.PolicyStatement({
actions: ['rds:*'],
resources: ['*'],
})
);
}
Using the addToPolicy
method, we can directly specify the actions and resources for the ALB controller role. In the example above, we granted the role full access to Amazon RDS by specifying the rds:*
action and *
resource.
Both solutions mentioned above provide a way to extend the default ALB controller policy using AWS CDK. Choose the solution that best suits your requirements and integrate it into your TypeScript code.
That’s it! You’ve learned how to extend the default ALB controller policy using AWS CDK in TypeScript. Happy coding!
Leave a Reply