Using this Terraform code, we can provision AWS IAM users and attach policies to them.
This Terraform configuration allows for the creation of IAM users in AWS and the attachment of a predefined policy to those users. IAM (Identity and Access Management) in AWS enables you to securely control access to AWS services and resources.
Before using this Terraform configuration, ensure you have the following:
-
Passing IAM credentials through environment variables ensures that Terraform can securely access them without explicitly storing them in its configuration.
-
Terraform automatically fetches these credentials from the environment variables during its execution.
- Update the variables.tf file to specify the usernames for the IAM users you want to create.
- Initialize the Terraform configuration by running
terraform init
. - Review the execution plan by running
terraform plan
. - If the plan looks good, apply the changes by running
terraform apply
. - After applying the changes, Terraform will output the details of the created IAM users.
The aws_iam_user
resource block is responsible for creating IAM users in AWS. It iterates over the usernames specified in the var.username variable and creates a user for each.
The aws_iam_policy
resource block defines a policy named ec2_policy
, which allows describing EC2 instances. It grants the necessary permissions using a JSON-encoded policy document.
The aws_iam_policy_attachment resource block attaches the ec2_policy
to the IAM users created earlier. It iterates over each IAM user and attaches the policy to them. The lifecycle block ensures that the attachment is created before any existing attachments are destroyed, to prevent downtime.