Home > database >  How can I set a dynamic environment variable when building my Spring Boot app as a docker image usin
How can I set a dynamic environment variable when building my Spring Boot app as a docker image usin

Time:08-19

If you check the commit for the sample aws-apprunner-terraform code (which uses petclinic) you will find that they include in their dockerfile the following:

ENTRYPOINT env spring.datasource.password=$(aws ssm get-parameter --name /database/password --with-decrypt --region $AWS_REGION | grep Value | cut -d '"' -f4) java -Djava.security.egd=file:/dev/./urandom -jar /app.jar

Essentially it is setting the spring.datasource.password environment variable dynamically at runtime to retrieve a value from the AWS SSM. This is all fine when using a Dockerfile.

But when I build my application using Spring Boot's in-built bootBuildImage task (I use gradle) I'm not sure how to achieve the same effect.

How can I set a environment variable value to be dynamic like is done in the example above when using the build pack provided by Spring Boot?

CodePudding user response:

You could create a .profile in the root of your repo with contents like:

export MY_VAR=$(some-dynamic-value)

More info: https://github.com/buildpacks/spec/blob/main/buildpack.md#app-interface

CodePudding user response:

When using the Spring Boot Gradle plugin's bootBuildImage or the Maven plugin's spring-boot:build-image with the default Paketo buildpacks, you can use service bindings to provide external credentials.

To test this locally, you'd do something like this:

$ mkdir -p bindings/db
$ echo "mysql" > bindings/db/type
$ aws ssm get-parameter --name /database/password --with-decrypt --region $AWS_REGION | grep Value | cut -d '"' -f4 > bindings/db/password

to end up with this directory structure:

bindings
└── db
    ├── password
    └── type

When running the application in the container, mount the bindings directory to the container and provide an environment variable named SERVICE_BINDING_ROOT that points to the bindings directory. The Spring Cloud Bindings library that the Paketo buildpacks contribute to the app image will do the rest.

I don't know enough about Terraform to advise how best to implement this in the tf scripts.

  • Related