Thursday, January 16, 2020

Terraform AWS Assume Role


Using AWS Assume Role in Terraform

You built a Terraform build server or TFE server on AWS EC2.  You want to be able to deploy resources to multiple accounts in your organization. How do you do this?

References:
https://www.terraform.io/docs/providers/aws/index.html
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#w329aac23c19c25c21b9b3
https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html
https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_permissions-to-switch.html
https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html


Be sure you have added an Instance Profile loaded onto your instance, you can extract the temporary credential for testing.

This is the aws cli command to look up your own identity:

aws sts get-caller-identity


This is how you extract the temp cred :
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/SOURCE_ROLE_NAME

Let's say from this instance you want to execute Terraform commands against a different role than the Instance Profile.

Be sure the Source Role is given necessary permission to assume the Target Role

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Resource": "arn:aws:iam::888888888888:role/TARGET_ROLE_NAME"
            
        }
    ]
}

And the Target Role must have the necessary Trust relationship to the Source Role. In the below example, I also limit this action to happen from some known IP range.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::999999999999:role/SOURCE_ROLE_NAME"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "IpAddress": {
          "aws:SourceIp": "10.10.10.0/24"
        }
      }
    }
  ]
}

You can test your policy via this command
aws sts assume-role --role-arn arn:aws:iam::888888888888:role/TARGET_ROLE_NAME --role-session-name MySession

Once your test works, then you can use the assume_role block inside "aws" provider.

Assume Role Usage:

provider "aws" {
  assume_role {
    role_arn     = "arn:aws:iam::88888888888/TARGET_ROLE_NAME"
    session_name = "MY_SESSION_NAME"
    external_id  = "SOME_OPTIONAL_EXTERNAL_ID"
  }
}

No comments:

Post a Comment

AWS WAF log4j query

How to query AWS WAF log for log4j attacks 1. Setup your Athena table using this instruction https://docs.aws.amazon.com/athena/latest/ug/wa...