Google Code Prettify

2020年4月15日 星期三

K8s: 設定環境變數

  1. spring.profiles.active=${spring_profiles_active}
  2. server.servlet.context-path=/
  3. server.port=8080
  4.  
  5. # encrypt
  6. jasypt.encryptor.bean=encryptorBean
  7. jasypt.encryptor.password=${jasypt_encryptor_password}
  8. jasypt.encryptor.algorithm=PBEWithMD5AndDES
spring boot 的程式,設定多半寫在 application.properties,裡面的值基於資安,或是其它各種理由,可能不會直接寫在檔案裡,而會取自環境變數,如上的 application.properties 有兩個參數來自環境變數,在 K8s 的環境要怎麼傳入環境變數呢?

這裡簡單的寫一支 REST API,會傳回 application.properties 裡的值,看看那兩個取自環境變數的值是否正確,程式如下:
  1. @RestController
  2. @RequestMapping("/info")
  3. @Slf4j
  4. public class InfoController {
  5. @Autowired
  6. private Environment env;
  7. @Autowired
  8. ResourceLoader resourceLoader;
  9. @GetMapping("/app")
  10. public Map app() {
  11. Map all = new HashMap();
  12. Set keys = new HashSet<>();
  13. try {
  14. Resource resource = resourceLoader.getResource("classpath:application.properties");
  15. InputStream is = resource.getInputStream();
  16. Properties prop = new Properties();
  17. prop.load(is);
  18. keys = prop.keySet();
  19. for(Object key:keys) {
  20. all.put((String) key, env.getProperty((String) key));
  21. }
  22. }
  23. catch (IOException e) {
  24. log.error(e.getMessage(), e);
  25. }
  26. return all;
  27. }
  28. }
下面是建立 pod 的 yaml,第 9~13 行就是傳入環境變數的方式。
  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4. name: practice-pod
  5. spec:
  6. containers:
  7. - name: practice-pod
  8. image: steven/practice-pod
  9. env:
  10. - name: spring_profiles_active
  11. value: "test"
  12. - name: jasypt_encryptor_password
  13. value: "mykey"
  14. imagePullSecrets:
  15. - name: steven-harbor
如果我們用 ReplicaSet 啟動兩個 pod,如下:
practice-pod 這個 pod 是用上面的 yaml 產生的,確實可以取得環境變數,但是 practice-rs-grtx7 和 practice-rs-lncdr 這兩個 pod 並無法取得環境變數,因為 rs 每次產生 pod,是從 image 產生,並沒有傳入環境變數,為了解決這個問題,建立 ReplicaSet 的 yaml 要如下 18~22 行:
  1. apiVersion: apps/v1
  2. kind: ReplicaSet
  3. metadata:
  4. name: practice-rs
  5. spec:
  6. replicas: 2
  7. selector:
  8. matchLabels:
  9. app: practice-rs
  10. template:
  11. metadata:
  12. labels:
  13. app: practice-rs
  14. spec:
  15. containers:
  16. - name: practice-pod
  17. image: harbor.steven.idv.tw/steven/practice-pod
  18. env:
  19. - name: spring_profiles_active
  20. value: "test"
  21. - name: jasypt_encryptor_password
  22. value: "mykey"
  23. imagePullSecrets:
  24. - name: steven-harbor
輸入如下指令測試看看: (使用 kubectl get svc 指令,可以看到 external-ip)
  1. curl http://172.16.3.39:9090/info/app
輸出如下結果:
  1. {"jasypt.encryptor.algorithm":"PBEWithMD5AndDES","jasypt.encryptor.bean":"encryptorBean","server.servlet.context-path":"/","server.port":"8080","jasypt.encryptor.password":"mykey","spring.profiles.active":"test"}
可以看到,兩個環境變數都有抓到。

沒有留言:

張貼留言