Terraform iam user

Terraform iam user DEFAULT

Rotating Secrets II - IAM users via Terraform

IAM Users infrastructure as a code with Terraform

In the 18F/cg-provision contains the Terraform files used to maintain our AWS infrastructure as code. User modules are in the path. Each module is utilized in and prints the contents after a successful Terrafrom apply.

Each of the user modules in individually leverage the and support having up to two of these resources. We name the resources with a version suffix. These resources are then referenced in our output with a suffix for previous and current keys e.g. and .

This is used to avoid invalidating all the previous credentials during a secrets rotation. This gives the operator enough of a window to update credentials across our various deployments.

Rotating IAM user access key ids and secret access keys

When rotating IAM user credentials, it’s important to generate new ones while making sure the old ones stay around until Concourse pipelines and Bosh manifests are updated with the latest version output. The following examples show file-diffs for a single user. You will repeat this process across all user modules and submit a single PR to begin the secret rotation window. You can also find examples of closed and merged pull requests in the repository around rotating IAM roles

Update the rotation iam_user module to have two access key resources

Create a new sequential version of the credentials in the modules found in and for each .

Note: These file-diffs are simply examples. They will not apply properly, so please don’t apply them. These changes will need to be made manually.

The example above shows keys being rotated from to . The example below shows that the named resources from above are set as values for the and outputs.

Repeat this process across all the and files. Once that’s done, submit a pull request against for . Once the pull request is merged, run the provisioning step in Concourse.

Capture the outputs for and replace all the values of in either Bosh manifests secrets stubs or Concourse credentials.

Revert the source for all modules

Once all the modules have been updated, revert the source back to the with a single updated version. This deletes the previous version credentials from the IAM users.

The example above references as the now current version by removing the version from the file. The example below removes the output value from the output since the previous version was removed in the file.

Once that’s done, submit a pull request against for again. Once the pull request is merged, run the provisioning step in Concourse. The Terraform will delete all the credentials from AWS.

Sours: https://cloud.gov/docs/ops/runbook/rotating-iam-users/


In my previous note, I mentioned the steps to authenticate Azure. Here in this note, I’ll list the steps to authenticate to AWS. The approach will be quite similar -we create an IAM user with appropriate policies, create/update terraform configuration files, and run the configuration files.

Step 1: Create an IAM user
To work with resources in AWS, we need appropriate access -read/modify. In this case, we need an IAM user with programmatic access permission (full access) to S3. Please attach appropriate policy (AmazonS3FullAccess) and store the Access key ID and Secret Access key securely. We need those in the next step.


Step 2: Update terraform configuration files
I followed the instructions here to create the AWS provider usage, authentication, and the instructions to create an S3 bucket were provided here. As stated in my previous note, the secured credentials (access_key and secret_key) are stored in a .tfvars file. This .tfvars file should not be added to the repository (update .gitignore accordingly).

terraform {
required_providers {
aws = {
source ="hashicorp/aws"
version ="3.13.0"
provider"aws" {
region =var.region
access_key =var.access_key
secret_key =var.secret_key
resource"random_integer""rand_int" {
min =10000
max =99999
resource"aws_s3_bucket""aws-b1" {
bucket ="${var.bucket_name}–${random_integer.rand_int.result}"
acl ="private"
tags = {
Name ="My bucket"
Environment ="Dev"

view raw
hosted with ❤ by GitHub

variable"region" {
description ="The region where to provision resources"
type =string
variable"access_key" {
description ="The access_key that belongs to the IAM user"
type =string
variable"secret_key" {
description ="The secret_key that belongs to the IAM user"
type =string
variable"bucket_name" {
description ="The name of S3 bucket"
default ="terraform-bucket"
type =string

view raw
hosted with ❤ by GitHub

Step 3: Execute terraform trial commands (init -> plan -> apply)


After I was able to verify that an S3 bucket was created under my AWS profile using Terraform configuration files.

The purpose of this note was to authenticate Terraform, and we saw that with the creation of the bucket in AWS S3.
image of newly created bucket

Other ideas to explore:
Is this the best method to authenticate Terraform?
How to provision an EC2 instance in AWS using Terraform?

Like this:



Sours: https://skundunotes.com/2020/11/04/authenticating-terraform-to-aws-using-iam-user/
  1. Klipsch computer speakers
  2. Warhammer 40k eldar books
  3. N64 roms mac


Terraform Tutorial - AWS IAM user, group, role, and policies - part 1

Bookmark and Share

bogotobogo.com site search:

terraform - IAM user and policies

In this post, we'll will create an IAM user and an S3 bucket. Then, we will map permissions for that bucket with an IAM policy and attach that policy to the new user.

This post mostly follows the guide from Create IAM Policies.


terraform { required_providers { aws = { source = "hashicorp/aws" version = "3.42.0" } } } provider "aws" { region = var.region } data "aws_iam_policy_document" "s3_policy" { statement { actions = ["s3:ListAllMyBuckets"] resources = ["arn:aws:s3:::*"] effect = "Allow" } statement { actions = ["s3:*"] resources = [aws_s3_bucket.bucket.arn] effect = "Allow" } } resource "aws_iam_user" "new_user" { name = "new_user" } resource "aws_iam_access_key" "my_access_key" { user = aws_iam_user.new_user.name pgp_key = var.pgp_key } resource "random_pet" "pet_name" { length = 3 separator = "-" } resource "aws_s3_bucket" "bucket" { bucket = "${random_pet.pet_name.id}-bucket" acl = "private" tags = { Name = "My bucket" Environment = "Dev" } } resource "aws_iam_policy" "policy" { name = "${random_pet.pet_name.id}-policy" description = "My test policy" policy = data.aws_iam_policy_document.s3_policy.json } output "rendered_policy" { value = data.aws_iam_policy_document.s3_policy.json } output "secret" { value = aws_iam_access_key.my_access_key.encrypted_secret sensitive = true }


variable "region" { default = "us-east-1" } variable "pgp_key" { description = "Either a base-64 encoded PGP public key, or a keybase username in the form keybase:username. Used to encrypt the password and the access key on output to the console." default = "" }

Before anything else, we need to do to Initializing the backend and provider plugins.

$ terraform init Initializing the backend... Initializing provider plugins... - Reusing previous version of hashicorp/aws from the dependency lock file - Using previously-installed hashicorp/aws v3.42.0 Terraform has been successfully initialized ...

Now, run and commands:

$ terraform plan $ terraform apply --auto-approve random_pet.pet_name: Creating... random_pet.pet_name: Creation complete after 0s [id=completely-wise-mongrel] aws_iam_user.new_user: Creating... aws_s3_bucket.bucket: Creating... aws_iam_user.new_user: Creation complete after 1s [id=new_user] aws_iam_access_key.my_access_key: Creating... aws_iam_access_key.my_access_key: Creation complete after 0s [id=AKIAQV57YS3YMIYTCU4I] aws_s3_bucket.bucket: Creation complete after 7s [id=completely-wise-mongrel-bucket] data.aws_iam_policy_document.s3_policy: Reading... data.aws_iam_policy_document.s3_policy: Read complete after 0s [id=3288376908] aws_iam_policy.policy: Creating... aws_iam_policy.policy: Creation complete after 2s [id=arn:aws:iam::047109936880:policy/completely-wise-mongrel-policy] Apply complete! Resources: 5 added, 0 changed, 0 destroyed. Outputs: rendered_policy = <<EOT { "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Action": "s3:ListAllMyBuckets", "Resource": "arn:aws:s3:::*" }, { "Sid": "", "Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::completely-wise-mongrel-bucket" } ] } EOT

We create a new_user with a permission to work on a S3 bucket. Note that the aws_secret_access_key is stored in terraform.tfstate not encrypted:

$ cat terraform.tfstate { "version": 4, "terraform_version": "0.15.3", "serial": 87, "lineage": "5b8287a5-118e-5c42-2432-fefdb9e74f06", "outputs": { "rendered_policy": { "value": "{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"\",\n \"Effect\": \"Allow\",\n \"Action\": \"s3:ListAllMyBuckets\",\n \"Resource\": \"arn:aws:s3:::*\"\n },\n {\n \"Sid\": \"\",\n \"Effect\": \"Allow\",\n \"Action\": \"s3:*\",\n \"Resource\": \"arn:aws:s3:::completely-wise-mongrel-bucket\"\n }\n ]\n}", "type": "string" } }, "resources": [ { "mode": "data", "type": "aws_iam_policy_document", "name": "s3_policy", "provider": "provider[\"registry.terraform.terraform.io/hashicorp/aws\"]", "instances": [ { "schema_version": 0, "attributes": { "encrypted_secret": null, "id": "AKIAQV57YS3YMIYTCU4I", "key_fingerprint": null, "pgp_key": "", "secret": "i8lp2...iRFP", "ses_smtp_password_v4": "BDUscxy7iogk6c1MQ2pGiqJIBr1QNufrgP684yFut1Iu", "status": "Active", "user": "new_user" }, "sensitive_attributes": [], "private": "bnVsbA==", "dependencies": [ "aws_iam_user.new_user" ] } ] }, { "mode": "managed", "type": "aws_iam_policy", "name": "policy", "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]", "instances": [ { "schema_version": 0, "attributes": { "arn": "arn:aws:iam::047109936880:policy/completely-wise-mongrel-policy", "description": "My test policy", "id": "arn:aws:iam::047109936880:policy/completely-wise-mongrel-policy", "name": "completely-wise-mongrel-policy", "name_prefix": null, "path": "/", "policy": "{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"\",\n \"Effect\": \"Allow\",\n \"Action\": \"s3:ListAllMyBuckets\",\n \"Resource\": \"arn:aws:s3:::*\"\n },\n {\n \"Sid\": \"\",\n \"Effect\": \"Allow\",\n \"Action\": \"s3:*\",\n \"Resource\": \"arn:aws:s3:::completely-wise-mongrel-bucket\"\n }\n ]\n}" }, "sensitive_attributes": [], "private": "bnVsbA==", "dependencies": [ "aws_s3_bucket.bucket", "data.aws_iam_policy_document.s3_policy", "random_pet.pet_name" ] } ] }, { "mode": "managed", "type": "aws_iam_user", "name": "new_user", "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]", "instances": [ { "schema_version": 0, "attributes": { "arn": "arn:aws:iam::047109936880:user/new_user", "force_destroy": false, "id": "new_user", "name": "new_user", "path": "/", "permissions_boundary": null, "tags": null, "unique_id": "AIDAQV57YS3YPHSUKSALS" }, "sensitive_attributes": [], "private": "bnVsbA==" } ] }, { "mode": "managed", "type": "aws_s3_bucket", "name": "bucket", "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]", "instances": [ { "schema_version": 0, "attributes": { "acceleration_status": "", "acl": "private", "arn": "arn:aws:s3:::completely-wise-mongrel-bucket", "bucket": "completely-wise-mongrel-bucket", "bucket_domain_name": "completely-wise-mongrel-bucket.s3.amazonaws.com", "bucket_prefix": null, "bucket_regional_domain_name": "completely-wise-mongrel-bucket.s3.amazonaws.com", "cors_rule": [], "force_destroy": false, "grant": [], "hosted_zone_id": "Z3AQBSTGFYJSTF", "id": "completely-wise-mongrel-bucket", "lifecycle_rule": [], "logging": [], "object_lock_configuration": [], "policy": null, "region": "us-east-1", "replication_configuration": [], "request_payer": "BucketOwner", "server_side_encryption_configuration": [], "tags": { "Environment": "Dev", "Name": "My bucket" }, "versioning": [ { "enabled": false, "mfa_delete": false } ], "website": [], "website_domain": null, "website_endpoint": null }, "sensitive_attributes": [], "private": "bnVsbA==", "dependencies": [ "random_pet.pet_name" ] } ] }, { "mode": "managed", "type": "random_pet", "name": "pet_name", "provider": "provider[\"registry.terraform.io/hashicorp/random\"]", "instances": [ { "schema_version": 0, "attributes": { "id": "completely-wise-mongrel", "keepers": null, "length": 3, "prefix": null, "separator": "-" }, "sensitive_attributes": [], "private": "bnVsbA==" } ] } ] }

Optional - keybase

To store the secret in encrypted, we need to provide a pgp_key "keybase:bogotobogo" via variables.tf:

... variable "pgp_key" { description = "Either a base-64 encoded PGP public key, or a keybase username in the form keybase:username. Used to encrypt the password and the access key on output to the console." default = "keybase:bogotobogo" }

Note that to provide the pgp_key, we need to install keybase in our local machine and create an account (in this case with a username, "bogotobogo". Then, do the following:

$ keybase pgp gen Enter your real name, which will be publicly visible in your new key: bogotobogo Enter a public email address for your key: [email protected] Enter another email address (or

Then, run terraform:

$ terraform apply --auto-approve ... Outputs: rendered_policy = <<EOT { "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Action": "s3:ListAllMyBuckets", "Resource": "arn:aws:s3:::*" }, { "Sid": "", "Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::completely-wise-mongrel-bucket" } ] } EOT secret = <sensitive>

Now the tf state has an encrypted secret:

$ cat terraform.tfstate ... { "mode": "managed", "type": "aws_iam_access_key", "name": "my_access_key", "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]", "instances": [ { "schema_version": 0, "attributes": { "encrypted_secretnew_user" ] } ] }, ...

To decrypt the secret:

$ terraform output -raw secret | base64 --decode | keybase pgp decrypt ceU17b8HenZRNg46WvWG4ha7dwTFwYm6IVFqU4k7

  • Introduction to Terraform with AWS elb & nginx
  • Terraform Tutorial - terraform format(tf) and interpolation(variables)
  • Terraform Tutorial - user_data
  • Terraform Tutorial - variables
  • Terraform Tutorial - creating multiple instances (count, list type and element() function)
  • Terraform 12 Tutorial - Loops with count, for_each, and for
  • Terraform Tutorial - State (terraform.tfstate) & terraform import
  • Terraform Tutorial - Output variables
  • Terraform Tutorial - Destroy
  • Terraform Tutorial - Modules
  • Terraform Tutorial - Creating AWS S3 bucket / SQS queue resources and notifying bucket event to queue
  • Terraform Tutorial - AWS ASG and Modules
  • Terraform Tutorial - VPC, Subnets, RouteTable, ELB, Security Group, and Apache server I
  • Terraform Tutorial - VPC, Subnets, RouteTable, ELB, Security Group, and Apache server II
  • Terraform Tutorial - Docker nginx container with ALB and dynamic autoscaling
  • Terraform Tutorial - AWS ECS using Fargate : Part I
  • Hashicorp Vault
  • HashiCorp Vault Agent
  • HashiCorp Vault and Consul on AWS with Terraform
  • Ansible with Terraform
  • AWS IAM user, group, role, and policies - part 1
  • AWS IAM user, group, role, and policies - part 2
  • Delegate Access Across AWS Accounts Using IAM Roles
  • Terraform import
  • Terraform commands cheat sheet
  • Terraform Cloud
  • Terraform 14
  • Creating Private TLS Certs

  • Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

    Sponsor Open Source development activities and free contents for everyone.

    Thank you.

    - K Hong

    Sours: https://www.bogotobogo.com/DevOps/Terraform/Terraform_IAM_User_group_role_Policies_1.php
    How to create an AWS IAM User policy for S3 bucket by Terraform

    Table of Contents

    See https://github.com/medined/create-iam-users-with-terraform-and-keybase for the copies of the files discussed here.

    GOAL: Provide a cryptographically secure way to distribute first-time passwords to a team. This means the system administrator (me!) should not know their passwords nor have any way to find them out.

    Recently I needed to create a few IAM users for a team. I choose to use Terraform to provision them. My first lesson was that while learning Terraform, create a separate directory for each project. For example, with my current knowledge I would not provision server resources and IAM resources in the same Terraform project.

    Since there are several files involved, first I will list them with a description.

    No secrets are stored in any of the files below. However, some teams might consider the permission list for each IAM role to be security-relevant. Check with your security people before storing the password files in a code repository though.

    accounts.txtThis file lists the iam user, keybase account, and group for each team member.
    iam-group-membership.tfThis file does not go into your code repository. It defines the relationship between IAM Groups and the IAM Users in those groups.
    iam-groups.tfThis file defines IAM groups, provides ARNs for existing IAM polices, and attaches groups and policies. This content might be considered sensitive.
    iam-user-*.tfThe are generated by the script. They should not be added to your code repository. Every user has their own file. To remove a user, just delete their file and re-apply. This file has the IAM user account, their access key, their login profile (i.e. the PGP key), and group membership. There is no secret information in this file except the user name itself. It will generate a local file holding the encrypted base64 password. The KeyBase website can be used to decrypt the password.
    encrypted_password.*.txtThis is the local file that the template produces.
    .gitignoreLists file that should not be in the code repository.
    main.tfThe heart of the process. It just sets up the AWS provider.
    terraform.tfvarsThis file sets some project configuration values like project name and aws region name. Do not add this file to your code repository.
    tfa.shThis is my script for running . It mainly sets up a log file so that all output is captured to help debug issues. It also runs user-add.sh to ensure the user accounts are up-to-date.
    tfd.shThis is my script for running . Like it mainly sets up a log file.
    user-add.shThis script creates and files that provision users and group membership.
    variables.tfThis file describes the variables used in the Terraform files. Only is used.


    This file should not be in your code repository. Below is an example. Change to fit your needs. Lines that start with a pound sign are ignored. Note that is prefectly find to use one KeyBase account for multiple IAM users. Whoever owns the KeyBase account can decrypt the passwords. This is a great feature for a tester than needs differently permissioned IAM users.


    The process will create any AWS resources needed and produce a local file containing the encrypted password. Below is a elided example of the files that will be created. If the user pastes the file content into the decryption form on the KeyBase site, they can decrypt the information to get their temporary AWS console password.


    The script produces this file using information from . This file should not be part of your code repository.


    This file has three sections. They are groups, policies, and group policy attachments. Each group and policy combination has its own attachment resource. This provides granular management. Delete an attachment to remove the policy from a group.

    Please use some prefix in your group names so that several projects can be managed at the same time. Otherwise, “administrators” in project “abcde” will conflict with project “zyxw”. Only group names need to be namespaced in this way.


    The script produces these files using information from . These files should not be part of your code repository. Here is an example:


    Define and in . Otherwise, this is pretty basic.


    Don’t add this file to your code repository. It’s simple for this project but sometimes it will contain sensitive information.




    Please install if you don’t have that tool. Or remove the usage of it from the file below.

    This script is used like this:

    The group must be in the VALID_IAM_GROUPS. Please adjust as needed.

    The script is straightforward. It uses a template to produce the user-XXXX.tf file.

    The code is:


    When you have the project files assembled, here are the steps.

    • Initialize Terraform.

    • Apply Terraform.

    • Example log file.

    • Fix mistakes.

    • Email the encrypted files to users with a procedure they should follow. For example,

    Sours: http://medined.github.io/terraform/using-keybase-for-secure-iam-user-credentials/

    User terraform iam

    Most companies these days use multiple cloud accounts to separate resources, customers, or even internal departments. With multiple AWS accounts, it’s practical to rely on a so-called bastion account for Identity and Access Management (IAM) users. It serves as one central place for users, S3 buckets, and other shared resources.

    PSawsrole copy

    If you are not using AWS Organizations, you can follow the best practices guide for multi-account setups here.

    While you could also just replicate your users across those other accounts, the simplest and cleanest way to access any resources there is to use AWS roles. Roles enable users and AWS services to access other AWS accounts without having to create a user in those accounts first. This post shows how to set up access to resources in another account via Terraform.

    Gaining Trust

    The way roles work is by using a web service called AWS Security Token Service (STS) to request temporary credentials for IAM, which are then used to identify you as that role. A user can request access to a role, which will grant that user that role’s temporary privileges.

    For that to be secure, there needs to be a trust established between the account or user and the role. It is possible to set up a role without restrictions that anyone can use, but that's very insecure and not recommended.

    Trust works by defining a policy to make that role assumable by only certain users, as well as a policy to allow only certain users to assume that role, taking care of permissions in both accounts. This might seem like doing the same thing twice, but you’re actually establishing the trust from both sides by setting those two policies.


    Setting Up the Role

    In this example, we’re setting up a user in an AWS account we’ll call ‘utils’:


    We’re giving it the right to assume a specific role in another account.

    Since we’re using the same Terraform for two AWS accounts, we’re defining a second provider, which is then used to make sure the next resources get created in the second account instead of the first.

    In the second account (let’s call it ‘prod’), we’re creating a role with a policy to allow that role to be assumed from the utils account.

    We are also adding a policy to grant the newly created role some permissions in the prod account. In this case, we’re only letting it list a few S3 buckets.

    We create a JSON file for the S3 permissions, called “role_permissions_policy.json”. Those could be done inline like the other policies, but having them separate makes the Terraform files easier to read —especially with longer statements.

    Back in the Terraform files we attach that policy (by referring to the JSON file) to the role we created before.


    The complete files can also be found in this repository.

    Now apply those Terraform files by running and then . 

    Assuming the Role



    If you want to use the newly created user, add a password to it and login as that user into the utils account.

    Try out the role to access the S3 buckets in prod by following the steps in the documentation.

    Alternatively use the AWS CLI

    1. Get the role ARN.

    2. Request STS from AWS using the role ARN and a session name of your choosing.

    3. User gets temporary credentials, export these as environment variables.

    4. Access S3 using the temp credentials.

    Ta-da! We can now login into our utils account, assume the role, and look at the prod S3 buckets.

    Of course this is a fairly simple example, but roles are also immensely useful for granting temporary access or allowing users to switch between different accounts and permission levels quickly. Admins can check user permissions without logging in and out, developers can access different accounts without changing users, and pipelines can function across AWS accounts without multiple sets of access keys.



    New call-to-action

    Sours: https://blog.container-solutions.com/how-to-create-cross-account-user-roles-for-aws-with-terraform
    Terraform 05 - Configure Identity and Access Management (IAM) on AWS via Terraform

    Create IAM Policies

    IAM identities (users, groups, or roles) must be assigned explicit permissions to access AWS resources. The associated IAM policy determines the privileges available to an IAM identity. Policies are JSON documents that define explicit allow/deny privileges to specific resources or resource groups.

    There are advantages to managing IAM policies in Terraform rather than manually in AWS. With Terraform, you can reuse your policy templates and ensure the principle of least privilege with resource interpolation.

    In this tutorial, you will create an IAM user and an S3 bucket. Then, you will map permissions for that bucket with an IAM policy. Finally, you will attach that policy to the new user and learn how to iterate on more complex policies.


    To follow along with this tutorial, you will need:

    »Clone the example repository

    Clone the Create IAM policies with Terraform repository.

    $git clone https://github.com/hashicorp/learn-terraform-iam-policy.git

    Change into the repository directory.

    $cd learn-terraform-iam-policy

    »Review the IAM policy resource

    The IAM policy resource is the starting point for creating an IAM policy in Terraform.

    The file contains an IAM policy resource, an S3 bucket, and a new IAM user. Open the file in your code editor and review the IAM policy resource. The in your policy is a string to avoid duplicate policy names.

    resource "aws_iam_policy""policy"{name="${random_pet.pet_name.id}-policy"description="My test policy"policy=<<EOT{ "Version": "2012-10-17", "Statement": [ { "Action": [ "s3:ListAllMyBuckets" ], "Effect": "Allow", "Resource": "*" }, { "Action": [ "s3:*" ], "Effect": "Allow", "Resource": "${aws_s3_bucket.bucket.arn}" } ]}EOT}

    The resource's attribute uses a multi-line heredoc string. For simple policies or one-off configurations, this approach is acceptable. However, as your policies grow more complex and you begin to reuse them throughout your environment, it can be difficult to parse policies using heredoc strings.

    »Refactor your policy

    The data source uses HCL to generate a JSON representation of an IAM policy document. Writing the policy as a Terraform configuration has several advantages over defining your policy inline in the resource.

    • Writing your policy with this data source makes applying policies to your AWS resources more flexible. You can overwrite, append, or update policies with this resource by using the and arguments.
    • Terraform error checking automatically formats your policy document into correct JSON when you run your apply.
    • Data sources make it easier to reuse policies throughout your environment.

    Copy the configuration below into your file. This data source uses HCL syntax to define the same IAM privileges as the policy in the heredoc string.

    data "aws_iam_policy_document""example"{statement{actions=["s3:ListAllMyBuckets"]resources=["arn:aws:s3:::*"]effect="Allow"}statement{actions=["s3:*"]resources=[aws_s3_bucket.bucket.arn]effect="Allow"}}

    Both statements in this policy apply to any user, group, or role with this policy attached. The first policy statement allows the user to list every S3 bucket in the AWS account. The second policy statement allows the user to perform any action on the bucket you create in this configuration, but not on other buckets in the account.

    Update your resource attribute to use the IAM policy document and save your changes.

    resource "aws_iam_policy" "policy" { name = "${random_pet.pet_name.id}-policy" description = "My test policy"+ policy = data.aws_iam_policy_document.example.json- policy = <<EOT- {- "Version": "2012-10-17",- "Statement": [- {- "Action": [- "s3:ListAllMyBuckets"- ],- "Effect": "Allow",- "Resource": "*"- },- {- "Action": [- "s3:*"- ],- "Effect": "Allow",- "Resource": "${aws_s3_bucket.bucket.arn}"- }- ]- }- EOT- }

    »Create a policy attachment

    The resource and data source used together will create a policy, but this configuration does not apply this policy to any users or roles. You must create a policy attachment for your policy to apply to your users.

    In your file, add a new policy attachment resource to apply your policy to the user created in this configuration.

    resource "aws_iam_user_policy_attachment""attachment"{user= aws_iam_user.new_user.name policy_arn= aws_iam_policy.policy.arn }

    The policy attachment resource has two required attributes: the and the . Terraform interpolates your policy Amazon Resource Name (ARN) from your previously defined resource when you apply this configuration. Each AWS resource has an ARN, and Terraform passes that unique identifier to the AWS API.

    This resource assigns your policy to a specific user. If you are creating a group or a role, you can use the group or role attachment resources instead.

    Add an output for your JSON-rendered policy to the end of your configuration file.

    output "rendered_policy" {value= data.aws_iam_policy_document.example.json }

    »Create your user, bucket, and policy

    Now that you have created and attached a policy in your configuration, apply your changes.

    In your terminal, initialize your Terraform configuration.

    $terraform init

    Apply your configuration. Enter when prompted to accept your changes.

    $terraform apply## ...Apply complete! Resources: 5 added, 0 changed, 0 destroyed.Outputs:rendered_policy = <<EOT{ "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Action": "s3:ListAllMyBuckets", "Resource": "arn:aws:s3:::*" }, { "Sid": "", "Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::primarily-liberal-spider-bucket" } ]}EOT

    The output should contain a rendered policy with the complete ARN of your newly created bucket.

    »Test the policy

    Test this policy in the AWS Policy Simulator. This tool lets you test an IAM policy by simulating whether a user would be allowed to run AWS operations.

    Use the Policy Simulator to test if your user can delete any objects or buckets in the S3 service.

    1. First, select , then your policy name from the left sidebar. Your policy name should start with your random animal and .
    2. In the "Select service" drop-down, select "S3".
    3. In the "Select actions" drop-down, choose "DeleteObject" and "DeleteBucket".
    4. Click "Run Simulation" and verify the simulator denies both actions as intended.

    AWS Policy Simulator

    Next, test if your user can delete objects in the test bucket you created or delete the bucket itself.

    1. Copy the ARN of your test bucket. Your ARN should start with .
    2. Expand the simulation result drop-down for each action and add the bucket ARN.
    3. Select "Run Simulation" and verify the simulator allows both actions as intended.

    AWS Policy Simulator

    »Clean up your infrastructure

    Before moving on, destroy the infrastructure you created in this tutorial.

    $terraform destroy

    Be sure to respond to the confirmation prompt with yes.

    »Next Steps

    In this tutorial, you created and refactored an AWS IAM policy with Terraform. To learn more about creating policies with Terraform, consider the resources below.

    • S3 bucket policies differ from IAM policies. To learn more about S3 bucket policy resources, review the S3 bucket policy resource.
    • The function allows you to create templatized policies for use in your configuration.
    • For an alternate to heredoc formatting, use the function.
    Sours: https://learn.hashicorp.com/tutorials/terraform/aws-iam-policy?in=terraform/aws

    Now discussing:

    Terraform Aws Iam User

    README Header

    Cloud Posse

    Terraform Module to provision a basic IAM user suitable for humans. It will establish a login profile and associate the user with IAM groups.

    We do not recommend creating IAM users for any other purpose. For external systems (e.g. CI/CD) check out our module.

    This project is part of our comprehensive "SweetOps" approach towards DevOps.

    Terraform Open Source Modules

    It's 100% Open Source and licensed under the APACHE2.

    We literally have hundreds of terraform modules that are Open Source and well-maintained. Check them out!


    IMPORTANT: The branch is used in just as an example. In your code, do not pin to because there may be breaking changes between releases. Instead pin to the release tag (e.g. ) of one of our latest releases.

    First, make sure all users register with keybase.io to faciliate public key encryption (PKE). Then use their keybase username to automatically encrypt their AWS secret. It's that easy!

    NOTE: We recommend using email addresses for IAM user accounts.


    Makefile Targets


    terraform>= 0.12.0
    aws>= 2.0
    null>= 2.0
    template>= 2.0


    aws>= 2.0
    template>= 2.0


    additional_tag_mapAdditional tags for appending to tags_as_list_of_maps. Not added to .no
    attributesAdditional attributes (e.g. )no
    contextSingle object for setting entire context at once.
    See description of individual variables for details.
    Leave string and numeric variables as to use default value.
    Individual variable settings (non-null) override settings in context object,
    except for attributes, tags, and additional_tag_map, which are merged.
    enabled = bool
    namespace = string
    environment = string
    stage = string
    name = string
    delimiter = string
    attributes = list(string)
    tags = map(string)
    additional_tag_map = map(string)
    regex_replace_chars = string
    label_order = list(string)
    id_length_limit = number
    "additional_tag_map": {},
    "attributes": [],
    "delimiter": null,
    "enabled": true,
    "environment": null,
    "id_length_limit": null,
    "label_order": [],
    "name": null,
    "namespace": null,
    "regex_replace_chars": null,
    "stage": null,
    "tags": {}
    delimiterDelimiter to be used between , , , and .
    Defaults to (hyphen). Set to to use no delimiter at all.
    enabledSet to false to prevent the module from creating any resourcesno
    environmentEnvironment, e.g. 'uw2', 'us-west-2', OR 'prod', 'staging', 'dev', 'UAT'no
    force_destroyWhen destroying this user, destroy even if it has non-Terraform-managed IAM access keys, login profile or MFA devices. Without force_destroy a user with non-Terraform-managed access keys and login profile will fail to be destroyed.no
    groupsList of IAM user groups this user should belong to in the accountno
    id_length_limitLimit to this many characters.
    Set to for unlimited length.
    Set to for default, which is .
    Does not affect .
    label_orderThe naming order of the id output and Name tag.
    Defaults to ["namespace", "environment", "stage", "name", "attributes"].
    You can omit any of the 5 elements, but at least one must be present.
    login_profile_enabledWhether to create IAM user login profileno
    nameSolution name, e.g. 'app' or 'jenkins'no
    namespaceNamespace, which could be your organization name or abbreviation, e.g. 'eg' or 'cp'no
    password_lengthThe length of the generated passwordno
    password_reset_requiredWhether the user should be forced to reset the generated password on first login.no
    pathDesired path for the IAM userno
    permissions_boundaryThe ARN of the policy that is used to set the permissions boundary for the userno
    pgp_keyProvide a base-64 encoded PGP public key, or a keybase username in the form . Required to encrypt password.n/ayes
    regex_replace_charsRegex to replace chars with empty string in , , and .
    If not set, is used to remove all characters other than hyphens, letters and digits.
    stageStage, e.g. 'prod', 'staging', 'dev', OR 'source', 'build', 'test', 'deploy', 'release'no
    tagsAdditional tags (e.g. no
    user_nameDesired name for the IAM user. We recommend using email addresses.n/ayes


    keybase_password_decrypt_commandCommand to decrypt the Keybase encrypted password
    keybase_password_pgp_messagePGP encrypted message (e.g. suitable for email exchanges)
    pgp_keyPGP key used to encrypt sensitive data for this user
    user_arnThe ARN assigned by AWS for this user
    user_login_profile_encrypted_passwordThe encrypted password, base64 encoded
    user_login_profile_key_fingerprintThe fingerprint of the PGP key used to encrypt the password
    user_nameIAM user name
    user_unique_idThe unique ID assigned by AWS

    Share the Love

    Like this project? Please give it a ★ on our GitHub! (it helps us a lot)

    Are you using this project or any of our other projects? Consider leaving a testimonial. =)

    Related Projects

    Check out these related projects.

    • terraform-aws-iam-assumed-roles - Terraform Module for Assumed Roles on AWS with IAM Groups Requiring MFA
    • terraform-aws-iam-s3-user - Terraform module to provision a basic IAM user with permissions to access S3 resources, e.g. to give the user read/write/delete access to the objects in an S3 bucket
    • terraform-aws-organization-access-group - Terraform module to create an IAM Group and Policy to grant permissions to delegated IAM users in the Organization's master account to access a member account
    • terraform-aws-ssm-iam-role - Terraform module to provision an IAM role with configurable permissions to access SSM Parameter Store
    • terraform-aws-iam-chamber-user - Terraform module to provision a basic IAM chamber user with access to SSM parameters and KMS key to decrypt secrets, suitable for CI/CD systems (e.g. TravisCI, CircleCI, CodeFresh) or systems which are external to AWS that cannot leverage AWS IAM Instance Profiles
    • terraform-aws-lb-s3-bucket - Terraform module to provision an S3 bucket with built in IAM policy to allow AWS Load Balancers to ship access logs


    Got a question? We got answers.

    File a GitHub issue, send us an email or join our Slack Community.

    README Commercial Support

    DevOps Accelerator for Startups

    We are a DevOps Accelerator. We'll help you build your cloud infrastructure from the ground up so you can own it. Then we'll show you how to operate it and stick around for as long as you need us.

    Learn More

    Work directly with our team of DevOps experts via email, slack, and video conferencing.

    We deliver 10x the value for a fraction of the cost of a full-time engineer. Our track record is not even funny. If you want things done right and you need it done FAST, then we're your best bet.

    • Reference Architecture. You'll get everything you need from the ground up built using 100% infrastructure as code.
    • Release Engineering. You'll have end-to-end CI/CD with unlimited staging environments.
    • Site Reliability Engineering. You'll have total visibility into your apps and microservices.
    • Security Baseline. You'll have built-in governance with accountability and audit logs for all changes.
    • GitOps. You'll be able to operate your infrastructure via Pull Requests.
    • Training. You'll receive hands-on training so your team can operate what we build.
    • Questions. You'll have a direct line of communication between our teams via a Shared Slack channel.
    • Troubleshooting. You'll get help to triage when things aren't working.
    • Code Reviews. You'll receive constructive feedback on Pull Requests.
    • Bug Fixes. We'll rapidly work with you to fix any bugs in our projects.

    Join our Open Source Community on Slack. It's FREE for everyone! Our "SweetOps" community is where you get to talk with others who share a similar vision for how to rollout and manage infrastructure. This is the best place to talk shop, ask questions, solicit feedback, and work together as a community to build totally sweet infrastructure.

    Discourse Forums

    Participate in our Discourse Forums. Here you'll find answers to commonly asked questions. Most questions will be related to the enormous number of projects we support on our GitHub. Come here to collaborate on answers, find solutions, and get ideas about the products and services we value. It only takes a minute to get started! Just sign in with SSO using your GitHub account.


    Sign up for our newsletter that covers everything on our technology radar. Receive updates on what we're up to on GitHub as well as awesome new projects we discover.

    Office Hours

    Join us every Wednesday via Zoom for our weekly "Lunch & Learn" sessions. It's FREE for everyone!



    Bug Reports & Feature Requests

    Please use the issue tracker to report any bugs or file feature requests.


    If you are interested in being a contributor and want to get involved in developing this project or help out with our other projects, we would love to hear from you! Shoot us an email.

    In general, PRs are welcome. We follow the typical "fork-and-pull" Git workflow.

    1. Fork the repo on GitHub
    2. Clone the project to your own machine
    3. Commit changes to your own branch
    4. Push your work back up to your fork
    5. Submit a Pull Request so that we can review your changes

    NOTE: Be sure to merge the latest changes from "upstream" before making a pull request!


    Copyright © 2017-2020 Cloud Posse, LLC



    See LICENSE for full details.


    All other trademarks referenced herein are the property of their respective owners.


    This project is maintained and funded by Cloud Posse, LLC. Like it? Please let us know by leaving a testimonial!

    Cloud Posse

    We're a DevOps Professional Services company based in Los Angeles, CA. We ❤️ Open Source Software.

    We offer paid support on all of our projects.

    Check out our other projects, follow us on twitter, apply for a job, or hire us to help with your cloud strategy and implementation.


    README FooterBeacon

    Sours: https://opensourcelibs.com/lib/terraform-aws-iam-user

    85 86 87 88 89