재귀(Recursion)
템플릿은 서로를 재귀적으로 호출할 수 있어요! 동전 던지기 예제를 변형해 앞면이 나올 때까지 계속 던지는 워크플로우를 만들어 볼게요.
본문
템플릿끼리 재귀적으로 호출할 수 있어요! 위 동전 던지기 템플릿의 이 변형에서는 앞면이 나올 때까지 계속 동전을 던져요.
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
generateName: coinflip-recursive-
spec:
entrypoint: coinflip
templates:
- name: coinflip
steps:
# flip a coin
- - name: flip-coin
template: flip-coin
# evaluate the result in parallel
- - name: heads
template: heads # call heads template if "heads"
when: "{{steps.flip-coin.outputs.result}} == heads"
- name: tails # keep flipping coins if "tails"
template: coinflip
when: "{{steps.flip-coin.outputs.result}} == tails"
- name: flip-coin
script:
image: python:alpine3.23
command: [python]
source: |
import random
result = "heads" if random.randint(0,1) == 0 else "tails"
print(result)
- name: heads
container:
image: alpine:3.23
command: [sh, -c]
args: ["echo \"it was heads\""]
비교를 위해 동전 던지기를 몇 번 실행한 결과예요.
argo get coinflip-recursive-tzcb5
STEP PODNAME MESSAGE
✔ coinflip-recursive-vhph5
├───✔ flip-coin coinflip-recursive-vhph5-2123890397
└─┬─✔ heads coinflip-recursive-vhph5-128690560
└─○ tails
STEP PODNAME MESSAGE
✔ coinflip-recursive-tzcb5
├───✔ flip-coin coinflip-recursive-tzcb5-322836820
└─┬─○ heads
└─✔ tails
├───✔ flip-coin coinflip-recursive-tzcb5-1863890320
└─┬─○ heads
└─✔ tails
├───✔ flip-coin coinflip-recursive-tzcb5-1768147140
└─┬─○ heads
└─✔ tails
├───✔ flip-coin coinflip-recursive-tzcb5-4080411136
└─┬─✔ heads coinflip-recursive-tzcb5-4080323273
└─○ tails
첫 번째 실행에서는 동전이 바로 앞면이 나와 멈췄어요. 두 번째 실행에서는 뒷면이 세 번 나온 뒤에야 앞면이 나와 멈췄어요.
더 알아보기 (Learn more)
- 재귀 템플릿은
when조건으로 자기 자신을 다시 호출해 반복을 구현하는 패턴이에요. - 종료 조건이 없으면 무한히 반복되니
when조건 설계에 유의하세요. - conditionals 워크스루의 동전 던지기 예제가 이 페이지의 기반이에요.