0

I am trying to get an env variable in Kotlin using another environment variable. For example, if I have a unique variable per AWS Region, I'd like something like this: System.getenv("Key"-$aws_region"). However, I can't seem to get it working right now (it is always null). Is the following syntax correct or am I missing something?

val awsRegionProvider: String =
    when {
        System.getenv("aws_region") != null -> System.getenv("aws_region")
        else -> ""
    }
}

val uniqueKey: String =
        System.getenv("UniqueKey-$awsRegionProvider")

I've already added aws_region & UniqueKey-us-west-2 to my env variables but uniqueKey complains about being null. Let me know if there are further details I can add.

2
  • What is Provider?  (Also, you can replace the whole when block with System.getenv("aws_region") ?: "".) Commented Dec 14, 2020 at 20:53
  • Sorry I've removed the Provider part, wasn't necessary. Got it, I'll use that syntax instead then. Any ideas on the using a var for getting an env var? Commented Dec 14, 2020 at 20:59

1 Answer 1

1

You can try with overriding the getters as following:

val awsRegionProvider: String get() = System.getenv("aws_region")?: ""
 

val uniqueKey: String get() = System.getenv("UniqueKey-$awsRegionProvider")
Sign up to request clarification or add additional context in comments.

2 Comments

Tried this out but still getting System.getenv("UniqueK…y-$awsRegionProvider") must not be null. I know aws_region and UniqueKey-us-west-2 both exist and that aws_region points to us-west-2...not sure what's the issue.
Looks like something is wrong with my env variables in Teamcity actually, since you were the only comment I've gone ahead and accepted your solution. Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.