When sketching out a demo stack for a new app or AWS service, it may make more sense to use an AWS provided IAM policy rather than carefully targeting the actions and resources for a custom policy.
Another use case of AWS provided policies might be, for example, when creating
an EKS (managed Kubernetes) cluster: it’s probably wiser to use the provided
AmazonEKSWorkerNodePolicy
rather than finding out all the permissions required
by your worker nodes during a long and painful day of trial and error.
So, how can we reference an AWS provided policy in Terraform? Instead of creating
a new custom policy with resource "aws_iam_policy"
, use the aws_iam_policy
data
source like this:
data "aws_iam_policy" "eks_worker_node" {
arn = "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy"
}
Attaching the policy to a role
As usual when working with policies, you can attach them in a number of ways. For example:
resource "aws_iam_role_policy_attachment" "worker_node" {
role = aws_iam_role.worker_node.name
policy_arn = data.aws_iam_policy.eks_worker_node.arn
}
Remember: resource
blocks are used to make new stuff, while data
blocks
are used to query and using existing things into your Terraform state.