Learn to create and attach IAM policies using Terraform, following the principle of least privilege for AWS users.
In this lesson, you will learn how to create IAM policies using Terraform and attach them to an AWS user. We will use the example of an IAM user named Lucy, who initially has no permissions. By following the principle of least privilege, we will incrementally grant her the required permissions.
Always start AWS users with the least privilege and only grant specific permissions as needed.
To add permissions via Terraform, you will use the aws_iam_policy resource. According to the AWS Terraform Provider Documentation, the only mandatory argument for this resource is the policy document in JSON format.
Step 2: Incorporate the Policy Document with Heredoc Syntax
One efficient method to include the policy document within your Terraform configuration is to use a heredoc. This allows you to embed multi-line strings without external file references. Here’s how to integrate the JSON document using this syntax:
Even though the IAM policy is defined, it is not automatically granted to Lucy. To attach the policy, we use the aws_iam_user_policy_attachment resource. This resource takes the username and the ARN of the IAM policy as inputs:
Copy
Ask AI
resource "aws_iam_user_policy_attachment" "lucy-admin-access" { user = aws_iam_user.admin-user.name policy_arn = aws_iam_policy.adminUser.arn}
In this lesson, you learned how to create an IAM policy with Terraform and attach it to an IAM user. These techniques are essential for managing AWS permissions securely and efficiently. Continue practicing these methods with practical exercises to master AWS infrastructure provisioning with Terraform.For more information on IAM policies and Terraform, refer to: