1

I am looking to pass varibales value dynamically as shown below to terraform image as mentioned in the link

image:
  name: hashicorp/terraform:light
  entrypoint:
    - /usr/bin/env
    - 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
    - 'ACCESS_KEY_ID=${ENV}_AWS_ACCESS_KEY_ID'
    - 'SECRET_ACCESS_KEY=${ENV}_AWS_SECRET_ACCESS_KEY'
    - 'DEFAULT_REGION=${ENV}_AWS_DEFAULT_REGION'        
    - 'export AWS_ACCESS_KEY_ID=${!ACCESS_KEY_ID}'
    - 'export AWS_SECRET_ACCESS_KEY=${!SECRET_ACCESS_KEY}'
    - 'export AWS_DEFAULT_REGION=${!DEFAULT_REGION}'

However, I am getting empty values. How can I pass dynamic values to the variables.

mair
  • 325
  • 1
  • 5
  • 14

1 Answers1

0

The confusion arises from the subtle fact, that the gitlab runner executes the commands passed into the script section using sh rather than bash

And the core issue is encountered that the following syntax

'export AWS_ACCESS_KEY_ID=${!ACCESS_KEY_ID}'

is understood correctly only by bash and not by sh

Therefore, we need to workaround it by using syntax that is understood by sh

For your case, something like the following should do it

image:
  name: hashicorp/terraform:light
  entrypoint:
    - /usr/bin/env
    - 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'


job:
  before_script:
   - ACCESS_KEY_ID=${ENV}_AWS_ACCESS_KEY_ID
   - export AWS_ACCESS_KEY_ID=$(eval echo \$$ACCESS_KEY_ID )
   - SECRET_ACCESS_KEY=${ENV}_AWS_SECRET_ACCESS_KEY
   - export AWS_SECRET_ACCESS_KEY=$( eval echo \$$SECRET_ACCESS_KEY )       
   - DEFAULT_REGION=${ENV}_AWS_DEFAULT_REGION
   - export AWS_DEFAULT_REGION=$( eval echo \$$DEFAULT_REGION )
  script:
   - echo $AWS_ACCESS_KEY_ID
   - echo $AWS_SECRET_ACCESS_KEY
   - echo $AWS_DEFAULT_REGION
   
Tolis Gerodimos
  • 3,782
  • 2
  • 7
  • 14
  • I have tried but it didnt work. Also getting bad substitution if I tried in before_script as before_script: - DEFAULT_REGION=${ENV}_AWS_DEFAULT_REGION - export AWS_DEFAULT_REGION=${!DEFAULT_REGION} – mair Feb 16 '22 at 11:20
  • @gmairi please check again – Tolis Gerodimos Feb 17 '22 at 17:42