Mastering Cloud IAM Roles with Terraform: A Practical Guide
Managing Identity and Access Management (IAM) roles across multiple cloud providers can be repetitive and error-prone. Terraform allows you to define, provision, and version these roles as code, ensuring consistency and auditability. This tutorial walks through the core steps to create and manage IAM roles using Terraform.
Before you start, ensure you have Terraform installed an the appropriate provider (e.g., hashicorp/aws, hashicorp/google, hashicorp/azurerm). Your credentials should be configured via environment variables or a shared config file.
1. Define the IAM Role Resource
In Terraform, an IAM role is a resource block. For AWS, it’s aws_iam_role; for Google Cloud, google_project_iam_member or google_service_account; for Azure, azurerm_role_definition. Example for AWS:
resource "aws_iam_role" "ec2_role" {
name = "ec2-s3-read-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Principal = {
Service = "ec2.amazonaws.com"
}
Action = "sts:AssumeRole"
}
]
})
}
2. Attach Policies to Grant Permissions
Policies define what the role can do. You can attach a managed policy or an inline policy. Using reusable aws_iam_policy_attachment or aws_iam_role_policy:
resource "aws_iam_role_policy_attachment" "s3_read" {
role = aws_iam_role.ec2_role.name
policy_arn = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess"
}
3. Manage Trust Relationships and Assumable Roles
Trust policies control who can assume the role. The assume_role_policy in the role block defines this. Use data sources to fetch existing roles or policies for cross-account trust.
4. Apply and Version Control
Run terraform plan to preview changes, then terraform apply. Store your Terraform state remotely (e.g., S3, Terraform Cloud) to collaborate and track role versions. Use variables for environment-specific role names.
Conclusion: Terraform transforms IAM role management into a repeatable, code-driven process. By defining roles, policies, and trust relationships in configuration files, you eliminate manual mistakes and enable full lifecycle automation across cloud platforms.