1

I want to assume role then save its output in a variable and then use that variable to extract some credentials from it. But terraform is throwing an error.

#!/bin/sh

ASSUME_ROLE=$(aws sts assume-role --output json --role-arn arn:aws:iam::123123123123:role/SomeRole --role-session-name test --profile myprofile)

export AWS_ACCESS_KEY_ID=$(echo ${ASSUME_ROLE} | awk -F'"' '/AccessKeyId/{print $4}')
export AWS_SECRET_ACCESS_KEY=$(echo ${ASSUME_ROLE} | awk -F'"' '/SecretAccessKey/{print $4}')
export AWS_SESSION_TOKEN=$(echo ${ASSUME_ROLE} | awk -F'"' '/SessionToken/{print $4}')

aws --profile myprofile route53 create-vpc-association-authorization --hosted-zone-id abcd3245 --vpc VPCRegion=us-east-1,VPCId=vpc-123e123

aws route53 associate-vpc-with-hosted-zone --hosted-zone-id abcd3245 --vpc VPCRegion=us-east-1,VPCId=vpc-123e123

Here is the output

There is no variable named "ASSUME_ROLE"., and 2 other diagnostic(s)
Adiii
  • 54,482
  • 7
  • 145
  • 148
  • Having `#!/bin/sh` makes this not a Bash script. Either make sure you don't use any Bash-only constructs, or change the shebang to point to `bash` instead of `sh`. See also [Difference between sh and bash](https://stackoverflow.com/questions/5725296/difference-between-sh-and-bash) – tripleee Jul 15 '19 at 15:26
  • I have ran and tested this script in a separate sh file and it was working. But when I added it into my terraform code it always shows the same error. @tripleee – yaggesh likhar Jul 15 '19 at 15:31
  • terraform fail assigning value to bash variable, here is the way u might intrested `resource "null_resource" "ec2-des" { provisioner "local-exec" { on_failure = "fail" interpreter = ["/bin/bash", "-c"] command = <> info.txt cat info.txt | awk '{print $1}' #what ever EOT } triggers = { always_run = "${timestamp()}" } }` – Adiii Jul 15 '19 at 15:55

2 Answers2

2

This error indicates that Terraform's template_file implementation understood ${ASSUME_ROLE} as being a template interpolation and so it tried to find an element named ASSUME_ROLE in the template vars map.

It doesn't seem like there are any actual Terraform template sequences in this string, in which case there's no reason to render this as a template. Instead, just read it verbatim using the file function.

If you do need this to be a template, you can escape the literal ${ sequences by writing $${ instead. Terraform's template language replaces $${ with ${ during rendering.

Martin Atkins
  • 62,420
  • 8
  • 120
  • 138
0

You probably just need to export your ASSUME_ROLE variable. export makes variables available in subshells (and $(echo ${ASSUME_ROLE}...) is a subshell). Otherwise they are only available in the current context.

Leon S.
  • 3,337
  • 1
  • 19
  • 16