11.2. ConfigMap 속성 소스에 대한 튜토리얼 실행

다음 튜토리얼을 사용하면 Kubernetes 시크릿 및 ConfigMap 설정을 실험할 수 있습니다. Kubernetes 통합 활성화에 설명된 대로 Spring Cloud Kubernetes 플러그인을 활성화하여 Kubernetes 구성 오브젝트를 Spring Boot Externalized Configuration과 통합합니다.

11.2.1. Spring Boot Camel Config 빠른 시작 실행

다음 튜토리얼은 Kubernetes Secrets 및 ConfigMap을 설정할 수 있는 Spring -boot-camel-config-archetype Maven archetype을 기반으로 합니다.

절차

  1. 새 쉘 프롬프트를 열고 다음 Maven 명령을 입력하여 간단한 Camel Spring Boot 프로젝트를 생성합니다.

    mvn org.apache.maven.plugins:maven-archetype-plugin:2.4:generate \
      -DarchetypeCatalog=https://maven.repository.redhat.com/ga/io/fabric8/archetypes/archetypes-catalog/2.2.0.fuse-sb2-790047-redhat-00004/archetypes-catalog-2.2.0.fuse-sb2-790047-redhat-00004-archetype-catalog.xml \
      -DarchetypeGroupId=org.jboss.fuse.fis.archetypes \
      -DarchetypeArtifactId=spring-boot-camel-config-archetype \
      -DarchetypeVersion=2.2.0.fuse-sb2-790047-redhat-00004

    archetype 플러그인은 대화형 모드로 전환되어 나머지 필드를 입력하라는 메시지를 표시합니다.

    Define value for property 'groupId': : org.example.fis
    Define value for property 'artifactId': : fuse79-configmap
    Define value for property 'version':  1.0-SNAPSHOT: :
    Define value for property 'package':  org.example.fis: :
    Confirm properties configuration:
    groupId: org.example.fis
    artifactId: fuse79-configmap
    version: 1.0-SNAPSHOT
    package: org.example.fis
    Y: : Y

    메시지가 표시되면 groupId 값으로 org.example.fis 를 입력하고 artifactId 값으로 fuse79-configmap 을 입력합니다. 나머지 필드의 기본값을 수락합니다.

  2. OpenShift에 로그인하고 애플리케이션을 배포할 OpenShift 프로젝트로 전환합니다. 예를 들어 developer 사용자로 로그인하고 openshift 프로젝트에 배포하려면 다음 명령을 입력합니다.

    oc login -u developer -p developer
    oc project openshift
  3. 명령줄에서 새 fuse79-configmap 프로젝트의 디렉터리로 변경하고 이 애플리케이션에 대한 Secret 오브젝트를 생성합니다.

    cd fuse79-configmap
    oc create -f sample-secret.yml
    참고

    애플리케이션을 배포하기 전에 Secret 오브젝트를 생성해야 합니다. 그러지 않으면 배포된 컨테이너가 Secret을 사용할 수 있을 때까지 대기 상태가 됩니다. 나중에 Secret을 생성하면 컨테이너가 대기 상태가 됩니다. Secret Object 설정 방법에 대한 자세한 내용은 시크릿 설정을 참조하십시오.

  4. 빠른 시작 애플리케이션을 빌드하고 배포합니다. fuse79-configmap 프로젝트의 최상위 수준에서 다음을 입력합니다.

    mvn oc:deploy -Popenshift
  5. 다음과 같이 애플리케이션 로그를 확인합니다.

    1. 브라우저에서 OpenShift 웹 콘솔로 이동하고(https://OPENSHIFT_IP_ADDR, OPENSHIFT_IP_ADDR 을 클러스터의 IP 주소로 교체) 인증 정보로 로그인합니다(예: 사용자 이름 developer 및 암호, 개발자).
    2. 왼쪽 패널에서 홈을 확장합니다. Status (상태)를 클릭하여 프로젝트 상태 페이지를 확인합니다. 선택한 네임스페이스(예: openshift)의 기존 애플리케이션이 모두 표시됩니다.
    3. fuse79-configmap 을 클릭하여 퀵 스타트에 대한 개요 정보 페이지를 확인합니다.
    4. 왼쪽 패널에서 워크로드를 확장합니다.
    5. 포드 를 클릭한 다음 fuse79-configmap-xxxx 를 클릭합니다. 애플리케이션의 Pod 세부 정보가 표시됩니다.
    6. 로그 탭을 클릭하여 애플리케이션 로그를 확인합니다.
  6. src/main/resources/application.properties 에 구성된 기본 수신자 목록은 생성된 메시지를 direct:async-queuedirect:file 이라는 두 개의 더미 엔드포인트로 보냅니다. 이로 인해 다음과 같은 메시지가 애플리케이션 로그에 기록됩니다.

    5:44:57.377 [Camel (camel) thread #0 - timer://order] INFO  generate-order-route - Generating message message-44, sending to the recipient list
    15:44:57.378 [Camel (camel) thread #0 - timer://order] INFO  target-route-queue - ----> message-44 pushed to an async queue (simulation)
    15:44:57.379 [Camel (camel) thread #0 - timer://order] INFO  target-route-queue - ----> Using username 'myuser' for the async queue
    15:44:57.380 [Camel (camel) thread #0 - timer://order] INFO  target-route--file - ----> message-44 written to a file
  7. ConfigMap 오브젝트를 사용하여 fuse79-configmap 애플리케이션의 구성을 업데이트하려면 fuse79-configmap 애플리케이션 권한을 부여하여 OpenShift ApiServer에서 데이터를 볼 수 있는 권한을 부여해야 합니다. 다음 명령을 입력하여 fuse79-configmap 애플리케이션의 서비스 계정에 대한 보기 권한을 부여합니다.

    oc policy add-role-to-user view system:serviceaccount:openshift:qs-camel-config
    참고

    서비스 계정은 system:serviceaccount:PROJECT_NAME:SERVICE_ACCOUNT_NAME 구문을 사용하여 지정됩니다. fis-config 배포 설명자는 qs-camel-configSERVICE_ACCOUNT_NAME 을 정의합니다.

  8. 작동 중인 실시간 다시 로드 기능을 보려면 다음과 같이 ConfigMap 오브젝트를 생성합니다.

    oc create -f sample-configmap.yml

    새 ConfigMap은 실행 중인 애플리케이션에서 Camel 경로의 수신자 목록을 재정의하여 생성된 메시지를 direct:async-queue,direct:file, direct:mail. ConfigMap 오브젝트에 대한 자세한 내용은 ConfigMap 설정을 참조하십시오. 이로 인해 다음과 같은 메시지가 애플리케이션 로그에 기록됩니다.

    16:25:24.121 [Camel (camel) thread #0 - timer://order] INFO  generate-order-route - Generating message message-9, sending to the recipient list
    16:25:24.124 [Camel (camel) thread #0 - timer://order] INFO  target-route-queue - ----> message-9 pushed to an async queue (simulation)
    16:25:24.125 [Camel (camel) thread #0 - timer://order] INFO  target-route-queue - ----> Using username 'myuser' for the async queue
    16:25:24.125 [Camel (camel) thread #0 - timer://order] INFO  target-route--file - ----> message-9 written to a file (simulation)
    16:25:24.126 [Camel (camel) thread #0 - timer://order] INFO  target-route--mail - ----> message-9 sent via mail

11.2.2. 구성 속성 metrics

구성 속성^n은 삽입을 통해 구성 설정을 수신할 수 있는 일반 Java 8080입니다. Java 코드와 외부 구성 메커니즘 간의 기본 인터페이스를 제공합니다.

외부 구성 및 Cryostat 레지스트리

다음 이미지는 Spring Boot Externalized Configuration이 spring-boot-camel-config quickstart에서 작동하는 방법을 보여줍니다.

kube spring boot 01

구성 메커니즘에는 다음과 같은 주요 부분이 있습니다.

속성 소스
구성에 삽입하기 위한 속성 설정을 제공합니다. 기본 속성 소스는 애플리케이션의 application.properties 파일이며, 선택적으로 ConfigMap 오브젝트 또는 Secret 오브젝트로 덮어쓸 수 있습니다.
구성 속성 metrics
속성 소스에서 configuraton 업데이트를 수신합니다. 구성 속성 8080은 @Configuration@ConfigurationProperties 주석으로 데코레이팅된 Java 8080입니다.
Spring 8080 레지스트리
필수 주석을 사용하면 구성 속성 metrics이 Spring 8080 레지스트리에 등록됩니다.
Camel 8080 레지스트리와 통합
Camel 8080 레지스트리는 Spring 8080 레지스트리와 자동으로 통합되어 Camel 경로에서 registered Spring 빈을 참조할 수 있습니다.

빠른 시작Configuration 클래스

fuse79-configmap 프로젝트의 구성 속성 sum은 다음과 같이 QuickstartConfiguration Java 클래스( src/main/java/org/example/fis/ 디렉터리에 있음)로 정의됩니다.

package org.example.fis;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration  1
@ConfigurationProperties(prefix = "quickstart")  2
public class QuickstartConfiguration {

    /**
     * A comma-separated list of routes to use as recipients for messages.
     */
    private String recipients;  3

    /**
     * The username to use when connecting to the async queue (simulation)
     */
    private String queueUsername;  4

    /**
     * The password to use when connecting to the async queue (simulation)
     */
    private String queuePassword;  5

    // Setters and Getters for Bean properties
    // NOT SHOWN
    ...
}
1
@Configuration 주석을 사용하면 빠른 시작 클래스가 ID가 있는 빈으로 Spring에 인스턴스화되고 등록되며, quickstartConfiguration 클래스가 생성됩니다. 이렇게 하면 Camel에서 빈에 자동으로 액세스할 수 있습니다. 예를 들어 target-route-queue 경로는 Camel 구문 ${bean:quickstartConfiguration?method=getQueueUsername} 을 사용하여 queueUserName 속성에 액세스할 수 있습니다.
2
@ConfigurationProperties 주석은 속성 소스에서 속성 값을 정의할 때 사용해야 하는 접두사인 quickstart 를 정의합니다. 예를 들어 속성 파일은 recipient 속성을 quickstart.recipients 로 참조합니다.For example, a properties file would reference the recipient property as quickstart.recipients.
3
recipient 속성은 속성 소스에서 삽입할 수 있습니다.
4
queueUsername 속성은 속성 소스에서 삽입할 수 있습니다.
5
queuePassword 속성은 속성 소스에서 삽입할 수 있습니다.

11.2.3. 보안 설정

이 빠른 시작의 Kubernetes 시크릿은 추가 필수 단계 중 하나와 별도로 표준 방식으로 설정됩니다. Spring Cloud Kubernetes 플러그인은 시크릿의 마운트 경로로 구성되어야 런타임에 보안을 읽을 수 있습니다. 보안을 설정하려면 다음을 수행합니다.

  1. 샘플 시크릿 오브젝트 생성
  2. 시크릿의 볼륨 마운트 구성
  3. Secret 속성을 읽을 수 있도록 spring-cloud-kubernetes 구성

샘플 Secret 오브젝트

빠른 시작 프로젝트는 다음과 같이 샘플 Secret, sample-secret.yml 을 제공합니다. Secret 오브젝트의 속성 값은 항상 base64로 인코딩됩니다( base64 명령줄 유틸리티 사용). Pod의 파일 시스템에 보안이 마운트되면 값이 자동으로 일반 텍스트로 다시 디코딩됩니다.

sample-secret.yml 파일

apiVersion: v1
kind: Secret
metadata: 1
  name: camel-config
type: Opaque
data:
  # The username is 'myuser'
  quickstart.queue-username: bXl1c2VyCg== 2
  quickstart.queue-password: MWYyZDFlMmU2N2Rm 3

1
metadata.name: 시크릿을 식별합니다. OpenShift 시스템의 다른 부분에서는 이 ID를 사용하여 보안을 참조합니다.
2
Quickstart.queue-username: quickstartConfiguration VLAN의 queueUsername 속성에 삽입해야 합니다. 값은 base64로 인코딩 되어야 합니다.
3
Quickstart.queue-password: quickstartConfiguration 8080의 queuePassword 속성에 삽입해야 합니다. 값은 base64로 인코딩 되어야 합니다.
참고

Kubernetes에서는 CamelCase에서 속성 이름을 정의할 수 없습니다(속성 이름이 모두 소문자여야 함). 이 제한을 해결하려면 Spring Boot가 queueUsername 과 일치하는 하이픈이 지정된 형식의 queue-username 을 사용합니다. 이는 외부화된 구성에 대한 Spring Boot의 완화된 바인딩 규칙을 활용합니다.

시크릿의 볼륨 마운트 구성

보안을 볼륨 마운트로 구성하여 런타임에 보안을 로드하도록 애플리케이션을 구성해야 합니다. 애플리케이션이 시작되면 Secret 속성이 파일 시스템의 지정된 위치에서 사용할 수 있게 됩니다. 애플리케이션의 deployment.yml 파일은 Secret의 볼륨 마운트를 정의하는 src/main/jkube/ 디렉터리에 있습니다.

deployment.yml 파일

spec:
  template:
    spec:
      serviceAccountName: "qs-camel-config"
      volumes: 1
        - name: "camel-config"
          secret:
            # The secret must be created before deploying this application
            secretName: "camel-config"
      containers:
        -
          volumeMounts: 2
            - name: "camel-config"
              readOnly: true
              # Mount the secret where spring-cloud-kubernetes is configured to read it
              # see src/main/resources/bootstrap.yml
              mountPath: "/etc/secrets/camel-config"
          resources:
#            requests:
#              cpu: "0.2"
#              memory: 256Mi
#            limits:
#              cpu: "1.0"
#              memory: 256Mi
             env:
              - name: SPRING_APPLICATION_JSON
               value: '{"server":{"undertow":{"io-threads":1, "worker-threads":2 }}}'

1
volumes 섹션에서 배포는 camel-config 라는 시크릿을 참조하는 camel-config 라는 새 볼륨을 선언합니다.
2
volumeMounts 섹션에서 배포는 camel-config 볼륨을 참조하는 새 볼륨 마운트를 선언하고 Secret 볼륨을 Pod 파일 시스템의 경로 /etc/secrets/camel-config 에 마운트하도록 지정합니다.

Secret 속성을 읽을 수 있도록 spring-cloud-kubernetes 구성

시크릿을 Spring Boot 외부화된 구성과 통합하려면 Spring Cloud Kubernetes 플러그인을 시크릿의 마운트 경로로 구성해야 합니다. Spring Cloud Kubernetes는 지정된 위치에서 시크릿을 읽고 속성 소스로 Spring Boot에서 사용할 수 있도록 합니다. Spring Cloud Kubernetes 플러그인은 quickstart 프로젝트의 src/main/resources 아래에 있는 bootstrap.yml 파일의 설정으로 구성됩니다.

bootstrap.yml 파일

# Startup configuration of Spring-cloud-kubernetes
spring:
  application:
    name: camel-config
  cloud:
    kubernetes:
      reload:
        # Enable live reload on ConfigMap change (disabled for Secrets by default)
        enabled: true
      secrets:
        paths: /etc/secrets/camel-config

spring.cloud.kubernetes.secrets.paths 속성은 Pod의 보안 볼륨 마운트 경로 목록을 지정합니다.

참고

bootstrap.properties 파일(또는 bootstrap.yml 파일)은 application.properties 파일과 유사하게 작동하지만 애플리케이션 시작의 이전 단계에서 로드됩니다. bootstrap.properties 파일에서 Spring Cloud Kubernetes 플러그인과 관련된 속성을 설정하는 것이 더 안정적입니다.

11.2.4. ConfigMap 설정

ConfigMap 오브젝트를 생성하고 뷰 권한을 적절하게 설정하는 것 외에도 Spring Cloud Kubernetes와의 통합을 위해서는 ConfigMap의 metadata.name 값과 프로젝트의 bootstrap.yml 파일에 구성된 spring.application.name 속성 값과 일치해야 합니다. ConfigMap을 설정하려면 다음을 수행합니다.

  • 샘플 ConfigMap 오브젝트 생성
  • 보기 권한 설정
  • Spring Cloud Kubernetes 플러그인 구성

샘플 ConfigMap 오브젝트

빠른 시작 프로젝트는 샘플 ConfigMap인 sample-configmap.yml 을 제공합니다.

kind: ConfigMap
apiVersion: v1
metadata: 1
  # Must match the 'spring.application.name' property of the application
  name: camel-config
data:
  application.properties: | 2
    # Override the configuration properties here
    quickstart.recipients=direct:async-queue,direct:file,direct:mail 3
1
metadata.name: ConfigMap을 식별합니다. OpenShift 시스템의 다른 부분에서는 이 ID를 사용하여 ConfigMap을 참조합니다.
2
data.application.properties: 이 섹션에는 애플리케이션과 함께 배포된 원래 application.properties 파일의 설정을 재정의할 수 있는 속성 설정이 나열됩니다.
3
Quickstart.recipients: quickstartConfiguration VLAN의 받는 사람 속성에 삽입해야 합니다.

보기 권한 설정

Secret의 deployment.yml 파일에 표시된 대로 프로젝트의 deployment.yml 파일에서 serviceAccountNameqs-camel-config 로 설정됩니다. 따라서 빠른 시작 애플리케이션에 대한 보기 권한을 활성화하려면 다음 명령을 입력해야 합니다( 테스트 프로젝트 네임스페이스에 배포된다고 가정).

oc policy add-role-to-user view system:serviceaccount:test:qs-camel-config

Spring Cloud Kubernetes 플러그인 구성

Spring Cloud Kubernetes 플러그인은 bootstrap.yml 파일의 다음 설정으로 구성됩니다.

spring.application.name
이 값은 ConfigMap 오브젝트의 metadata.name 과 일치해야 합니다(예: quickstart 프로젝트의 sample-configmap.yml 에 정의된 대로). 기본값은 application 입니다.
spring.cloud.kubernetes.reload.enabled
이를 true 로 설정하면 ConfigMap 오브젝트의 동적 재로드가 활성화됩니다.

지원되는 속성에 대한 자세한 내용은 PropertySource Reload Configuration Properties 을 참조하십시오.