Security As Code— Secure AWS Access Using Terraform Managed IAM Groups/Users

What Is AWS IAM?

IAM Group

Security as Code: Use Terraform for IAM Groups/Users Management


You have an application called “testapp”, it runs on EC2 instance and has data stored in AWS s3 buckets. As the app owner, you only want to grant developer accesses to the EC2 instance and s3 bucket.


  • Create file
data "aws_iam_policy_document" "testapp_developer" {

# s3 full access
statement {
effect = "Allow"
actions = ["s3:*"]
resources = [

# EC2 restricted access
statement {
effect = "Allow"
actions = ["ec2:*"]
resources = ["arn:aws:ec2:${var.region}:${var.account}:instance/*"]
condition {
test = "StringLike"
values = ["testapp"]
variable = "ec2:ResourceTag/App"

resource "aws_iam_policy" "testapp_developer" {
name = "testapp_developer_policy"
description = "Policy for develop testapp"
policy = data.aws_iam_policy_document.testapp_developer.json
  • Create file, which defines all the variables
variable "account" {
default = "xxxxxxx" # Replace with your account ID

variable "region" {
default = "us-east-1"

variable "prefix" {
default = "testapp-prefix"

variable "s3_bucket_name" {
default = "testapp-bucket"
  • Create file, which defines the group and users
provider "aws" {
profile = "profile" # Replace with your profile
region = "us-east-1"

resource "aws_iam_group" "testapp_developer" {
name = "TestappDeveloper"

resource "aws_iam_group_policy_attachment" "custom_policy" {
group =
policy_arn = aws_iam_policy.testapp_developer.arn

resource "aws_iam_group_membership" "developer" {
group =
name = "testapp-developers"
users = [,

resource "aws_iam_user" "testapp_developer_user_one" {
name = "testapp-dev1"

resource "aws_iam_user" "testapp_developer_user_two" {
name = "testapp-dev2"

Test and Run

  • Initialize the terraform working directory
$ terraform init
  • Rewrite all configuration files to a canonical format and style
$ terraform fmt
  • Validate the syntax
$ terraform validate
Success! The configuration is valid.
  • Actual deploy
$ terraform apply....
Plan: 6 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes

You can see once deployed, you will have a “TestappDeveloper” group in your AWS IAM and two users created and assigned to this group.



Senior Cloud Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store