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.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Always start AWS users with the least privilege and only grant specific permissions as needed.
Prerequisites
Before you begin, ensure you have an IAM user created. In our example, Lucy has already been created.Creating an IAM Policy Document
AWS uses JSON-formatted policy documents to define permissions. Below is an example of an administrator access policy document:Defining Resources in Terraform
To add permissions via Terraform, you will use theaws_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 1: Declare the IAM User and IAM Policy
Below is a Terraform configuration snippet that first defines the IAM user resource, followed by the IAM policy resource: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:Step 3: Attaching the Policy to the IAM User
Even though the IAM policy is defined, it is not automatically granted to Lucy. To attach the policy, we use theaws_iam_user_policy_attachment resource. This resource takes the username and the ARN of the IAM policy as inputs:
Complete Terraform Configuration
Combining all the resources, the complete Terraform configuration looks as follows:Deploying the Configuration
After finalizing your Terraform configuration, follow these steps to preview and apply your changes:Double-check your IAM policies and user attachments to ensure you are not inadvertently granting excessive permissions.
Alternative Approach: Using an External JSON File
An alternative method to define the IAM policy document is to store it in an external file. This can enhance readability and maintainability.Steps to Use an External File:
- Create a file named
admin-policy.jsonin the same directory as yourmain.tf. - Move the JSON policy document into
admin-policy.json.
file function: