-1

I am trying to set environment variables and use them in application.yml of my spring-boot application.

System/OS: windows Terminal: Git Bash

application.yml

datasource:
    url: ${DATABASE_URL:jdbc:mysql://localhost:3306/test?useSSL=false}
    username: ${DATABASE_USERNAME:root}
    password: ${DATABASE_PASSWORD:admin}

Now, to set these environment variables, i did following steps

  1. create .env file with these environment varaibles
PORT=8000
DATABASE_URL="jdbc:mysql://localhost:3306/test?useSSL=false"
DATABASE_USERNAME=kp-usr-1
DATABASE_PASSWORD=Kpi987223oibnW
  1. Use source .env command to set environment variables for the session

After source .env I can check and verify all env vars using echo $DATABASE_URL command, but it is not picked up by application.yml ( when running ./gradlew build or ./gradlew bootJar)

If i set these environment variables in Windows Environment variables from Window settings, then everything works as expected.

Is there anything am i missing ? I want to load the environment variables from .env file for the current session of Java process.

  • I tried multiple scripts, like reading lines from .env and calling export=$line, but that also didn`t worked.
  • Running export DATABASE_URL=abd; export DATABASE_USER=admin; TERM=cygwin ./gradlew test works, but this is cumbersome, when we have too many varaibles.
  • Note: I am using windows with git bash terminal
Jassi
  • 619
  • 7
  • 12
  • 1
    git's bash is just a cross-platform terminal emulator, it's not actually the OS itself, so when you invoke gradle on windows you're not running "a shell script in git bash", you're running gradle in Windows, in a new process, independent of git bash itself, and it only has access to the user's environment variables set for Windows. What you _can_ do is explicitly include any args that you need forward from your invocation by using the `--args` flag, because that way you explicitly pass values into gradle as part of its run. E.g https://stackoverflow.com/questions/36923288/#57890208 – Mike 'Pomax' Kamermans Sep 02 '23 at 16:57

1 Answers1

0

According the information that i have,when you set environment variable in Terminal,the variables are temporary belong to the Terminal you execute these command and not persistent.
These variables persistent location is the Windows registry.
At windows 10.
User environment variable location is HKEY_CURRENT_USER\Environment.
System environment variables location is HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment\

You can execute the follow code in windows script like .bat or .cmd to do the persistence.

//set a temporary simple name for system environment location
set MACHINEregpath=HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
    
//set GOROOT = C:\go in the System environment and persistence it in Registry
reg add "%MACHINEregpath%" /v "GOROOT" /t REG_SZ /d "C:\go" /f
ash
  • 26
  • 3