Skip to content

Instantly share code, notes, and snippets.

@dynnamitt
Created February 21, 2023 09:50
Show Gist options
  • Save dynnamitt/2c93bb093bc8f96ab51f5c7f47012717 to your computer and use it in GitHub Desktop.
Save dynnamitt/2c93bb093bc8f96ab51f5c7f47012717 to your computer and use it in GitHub Desktop.
terraform shell-provider, script-wrapper when using aws-cli role-arns
#!/bin/sh
# ========================================================================
#
# This is requires since we always assume a ROLE inside Terraform(go-sdk),
# BUT when we RETURN to shell we have a different IDENTITY.
# This shell IDENTITY must again assume the same "inside-TF ROLE" to
# be successful in using aws-cli
#
# =========================================================================
# this is same role-arn as TF-provider uses.
ROLE_ARN=$1
shift
echo A $(aws sts get-caller-identity)
SESS_SET=$(aws sts assume-role --role-session-name assumer-script \
--role-arn $ROLE_ARN \
--output text \
--query "Credentials.[
join('AWS_ACCESS_KEY_ID=', ['', @.AccessKeyId]),
join('AWS_SECRET_ACCESS_KEY=', ['', @.SecretAccessKey]),
join('AWS_SESSION_TOKEN=', ['', @.SessionToken])
]" )
for e in $SESS_SET
do
export "$e"
done
exec "$@"
@dynnamitt
Copy link
Author

# magic.tf
data "aws_caller_identity" "current" {}

data "aws_arn" "id_sts" {
  arn = data.aws_caller_identity.current.arn
}

locals {
  rolename = split("/", data.aws_arn.id_sts.resource)[1]
  assumerole_arn = "arn:aws:iam::${data.aws_arn.id_sts.account}:role/${local.rolename}"
}

data "shell_script" "iam-pols" {

  lifecycle_commands {  
          read   =  <<-EOT
            ${path.module}/wrap_awscli_calls.sh ${local.assumerole_arn} \
            aws iam list-policies \
            --region ${data.aws_arn.id_sts.region} \
            --output json --query "Policies[] | {All_Pols:[]} "
          EOT
 }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment