Deploy AWS IAM User, Group & Policy Using Terraform

Deploy AWS IAM User, Group & Policy Using Terraform

Welcome back to the series of Deploying On AWS Cloud Using Terraform 👨🏻‍💻. In this entire series, we will focus on our core concepts of Terraform by launching important basic services from scratch which will take your infra-as-code journey from beginner to advanced. This series would start from beginner to advance with real life Usecases and Youtube Tutorials.

If you are a beginner for Terraform and want to start your journey towards infra-as-code developer as part of your devops role buckle up 🚴‍♂️ and lets get started and understand core Terraform concepts by implementing it...🎬

Let's understand it in 2 scenarios

  1. Create 5 IAM users and a Developer group, and align all users as part of this Developer Group.

  2. Create IAM Policies and assign this to the Developer group.

❗️❗️Pre-Requisite❗️❗️

1️⃣ Deploying On AWS Cloud Using Terraform Series Pre-Requisites

2️⃣ Terraform Naming Conventions & Best Practices

👁‍🗨👁‍🗨 YouTube Tutorial 📽

🔎Basic Terraform Configurations🔍

As part of the basic configuration we are going to setup 3 terraform files

  1. Providers File:- Terraform relies on plugins called "providers" to interact with cloud providers, SaaS providers, and other APIs.
    Providers are distributed separately from Terraform itself, and each provider has its own release cadence and version numbers.
    The Terraform Registry is the main directory of publicly available Terraform providers, and hosts providers for most major infrastructure platforms. Each provider has its own documentation, describing its resource types and their arguments.
    We would be using AWS Provider for our terraform series. Make sure to refer Terraform AWS documentation for up-to-date information.
    Provider documentation in the Registry is versioned; you can use the version menu in the header to change which version you're viewing.

     provider "aws" { 
     region = "var.AWS_REGION" 
     shared_credentials_file = "<Your AWS Credentials File path>" 
     }
    
  2. Variables File:- Terraform variables lets us customize aspects of Terraform modules without altering the module's own source code. This allows us to share modules across different Terraform configurations, reusing same data at multiple places.
    When you declare variables in the root terraform module of your configuration, you can set their values using CLI options and environment variables. When you declare them in child modules, the calling module should pass values in the module block.

     variable "AWS_REGION" { 
     default = "us-east-1" 
     }
    
  3. Versions File:- It's always a best practice to maintain a version file where you specific version based on which your stack is testing and live on production.

     terraform { 
     required_version = ">= 0.12" 
     }
    

Scenario 1:-Create 5 IAM users and a Developer group, and align all users as part of this Developer Group

Let's create a variable to type a list to pass our user names for whom the IAM user profile needs to be created in AWS.

variable "usernames" {
  type = list(string)
  default = ["Dheeraj","Sandip","Avinash","Vishal","Toshal"]
}

🔳 Resource

aws_iam_user:- This resource is used to create an AWS IAM user.

🔳 Arguments

name:- This is a mandatory argument to define user name as part of resource creation.
count:- Variable to take the length of the user list and save it.
element:- It's an intrinsic function of terraform to retrieve a single element from a list.

resource "aws_iam_user" "userlist" {
  count = "${length(var.username)}"
  name = "${element(var.username,count.index )}"
}

🔳 Resource

aws_iam_group:- This resource is used to create an AWS IAM group.

🔳 Arguments

name:- This is a mandatory argument to define group name as part of resource creation.

resource "aws_iam_group" "dev_group" {
  name = "Developer"
}

🔳 Resource

aws_iam_user_group_membership:- This resource is used to associate AWS IAM users to single or multiple groups.

🔳 Arguments

name:- This is a mandatory argument to define this group membership association.
user:- This is a mandatory argument to provide a list of users to be associated with the group.
groups:- This is a mandatory argument to provide a list of groups to be associated.
count:- Variable to take the length of the user list and save it.
element:- It's an intrinsic function of terraform to retrieve a single element from a list.

resource "aws_iam_user_group_membership" "user_group_membership" {
  count  = length(var.username)
  user   = element(var.username, count.index)
  groups = [aws_iam_group.dev_group.name, ]
}

Scenario 2:-Create IAM Policies and assign this to the Developer group.

🔳 Resource

aws_iam_policy:- This resource is used to create IAM policy and define JSON policy within it.

🔳 Arguments

name:- This is an optional argument to define the IAM policy name.
description:- This is an optional argument to provide more details about the IAM policy.
policy:- This is a mandatory argument to JSON policy document.

resource "aws_iam_policy" "dev_group_policy" {
  name        = "dev-policy"
  description = "My test policy"
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = [
          "ec2:Describe*",
          "ec2:Get*",
        ]
        Effect   = "Allow"
        Resource = "*"
      },
    ]
  })
}

🔳 Resource

aws_iam_group_policy_attachment:- This resource is used to attach the AWS IAM policy to the group.

🔳 Arguments

group:- This is a mandatory argument to provide the name of the group to which the policy needs to be attached.
policy_arn:- This is a mandatory argument to provide AWS IAM policy arn which needs to be associated with the group.

resource "aws_iam_group_policy_attachment" "custom_policy" {
  group      = aws_iam_group.dev_group.name
  policy_arn = aws_iam_policy.dev_group_policy.arn
}

🔳 Output File

Output values make information about your infrastructure available on the command line, and can expose information for other Terraform configurations to use. Output values are similar to return values in programming languages.

output "user_arn" {
  description = "Provide the IAM user names which are created as part of this resource"
  value = aws_iam_user.userlist.*.arn
}
output "dev-group-id" {
  value       = aws_iam_group.dev_group.id
  description = "A reference to the created IAM group"
}

🔊To view the entire GitHub code click here

1️⃣ The terraform fmt command is used to rewrite Terraform configuration files to a canonical format and style👨‍💻.

 terraform fmt

2️⃣ Initialize the working directory by running the command below. The initialization includes installing the plugins and providers necessary to work with resources. 👨‍💻

terraform init

3️⃣ Create an execution plan based on your Terraform configurations. 👨‍💻

terraform plan

4️⃣ Execute the execution plan that the terraform plan command proposed. 👨‍💻

terraform apply -auto-approve

ELB (2).png

destroy.png

❗️❗️Important Documentation❗️❗️

⛔️ Hashicorp Terraform
⛔️ AWS CLI
⛔️ Hashicorp Terraform Extension Guide
⛔️ Terraform Autocomplete Extension Guide
⛔️ AWS IAM Policy
⛔️ IAM Policy Group Attachment
⛔️ AWS IAM Group Membership
⛔️ AWS IAM Group
⛔️ AWS IAM User

🥁🥁 Conclusion 🥁🥁

In this blog, we have configured the below resources
✦ AWS IAM User.
✦ AWS IAM Group.
✦ AWS IAM Policy.
I have also referenced what arguments and documentation we are going to use so that while you are writing the code it would be easy for you to understand terraform official documentation. Stay with me for the next blog where we will be doing deep dive into Target Group, Elastic Load Balancer & ELB Listener Using Terraform.

📢 Stay tuned for my next blog.....

🎊**So, did you find my content helpful? If you did or like my other content, feel free to buy me a coffee. Thanks. **🎊

![](https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=Dheeraj3&button_colour=5F7FFF&font_colour=ffffff&font_family=Cookie&outline_colour=000000&coffee_colour=FFDD00 align="left")

👨🏻‍💻Terraform Github Repository👨🏻‍💻

Did you find this article valuable?

Support Dheeraj Choudhary by becoming a sponsor. Any amount is appreciated!