Setup GCP application credentials in spring boot


In spring boot, you need to setup GCP credentials in order to use the Google Cloud Services for example  access bucket object. You can do it following  ways


For production

1. You can add file directly to Dockerfile(bad idea)

FROM openjdk:8-jdk-alpine
COPY target/myapp*.jar /opt/app/myapp.jar
COPY /path/to/permission.json /opt/secret/gcp-permission.json
ENV GOOGLE_APPLICATION_CREDENTIALS="/opt/secret/gcp-permission.json"
ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom","-jar","/opt/app/mnyapp.jar"]


2. You can also add as docker compose file or config map on kubernetes

services:
  myapp:
    image: eu.gcr.io/marufh/myaap
    restart: always
    container_name: myapp
    environment:
      - "GOOGLE_APPLICATION_CREDENTIALS=/opt/secret/gcp-permission.json"


3. open ~/.bash-profile or  ~/.zshrc file and add the following

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/permission.json


For development 


1. You can add directly on the pom.xml

<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
<profiles>
<profile>dev</profile>
</profiles>
<environmentVariables>
<GOOGLE_APPLICATION_CREDENTIALS>/path/to/permission.json</GOOGLE_APPLICATION_CREDENTIALS>
</environmentVariables>
</configuration>
</plugin>


2. You can also directly add file on the code

@PostConstruct
public void init() {
try {
storage = StorageOptions.getDefaultInstance()
.toBuilder()
.setCredentials(GoogleCredentials.
fromStream(
new FileInputStream("/path/to/permission.json")))
.build()
.getService();
} catch (IOException e) {
throw new RuntimeException(e);
}
}