본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

루프 (Loops)

원문 보기 위키 갱신

워크플로를 작성할 때는 입력 집합을 반복(iterate)할 수 있는 능력이 매우 유용해요. argo-workflows가 루프를 수행하는 방식이 바로 그것입니다. 이 문서에서는 withSequence, withItems, withParam 세 가지 방법과 루프 결과 집계 방법을 다룹니다.

출처: Argo Workflows 문서

본문

워크플로를 작성할 때는 입력 집합을 반복할 수 있는 능력이 종종 매우 유용합니다. 이것이 바로 argo-workflows가 루프를 수행하는 방식이에요.

템플릿을 여러 번 실행하는 기본적인 방법은 세 가지입니다.

  • withSequence는 숫자 시퀀스를 반복합니다.
  • withItems는 작업할 항목들의 리스트를 받아요. 둘 중 하나입니다:
    • 단순한 단일 값. 템플릿 안에서 '{{item}}'으로 사용할 수 있어요.
    • JSON 객체. 객체의 각 요소는 키로 '{{item.key}}'처럼 접근할 수 있습니다.
  • withParam은 JSON 배열을 받아 반복합니다. 마찬가지로 항목들은 withItems처럼 객체일 수 있어요. 이 방식은 매우 강력합니다. 워크플로의 다른 스텝에서 JSON을 생성할 수 있으므로 동적(dynamic) 워크플로를 만들 수 있거든요.

withSequence 예제

withSequence를 사용해 템플릿을 여러 번 실행합니다.

apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: loop-sequence-
spec:
  entrypoint: loop-sequence-example

  templates:
  - name: loop-sequence-example
    steps:
    - - name: hello-world-x5
        template: hello-world
        withSequence:
          count: "5"

  - name: hello-world
    container:
      image: busybox
      command: [echo]
      args: ["hello world!"]

withItems 기본 예제

withItems로 항목 리스트를 반복하면서, 인스턴스화되는 각 템플릿에 문자열을 대입합니다.

apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: loops-
spec:
  entrypoint: loop-example
  templates:
  - name: loop-example
    steps:
    - - name: print-message-loop
        template: print-message
        arguments:
          parameters:
          - name: message
            value: "{{item}}"
        withItems:              # invoke print-message once for each item in parallel
        - hello world           # item 1
        - goodbye world         # item 2

  - name: print-message
    inputs:
      parameters:
      - name: message
    container:
      image: busybox
      command: [echo]
      args: ["{{inputs.parameters.message}}"]

withItems 좀 더 복잡한 예제

각 워크플로에 두 개 이상의 정보를 전달하고 싶다면, withItems의 각 항목에 JSON 객체를 사용하고 키로 요소에 접근하면 됩니다. 아래 예제와 같아요.

apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: loops-maps-
spec:
  entrypoint: loop-map-example
  templates:
  - name: loop-map-example # parameter specifies the list to iterate over
    steps:
    - - name: test-linux
        template: cat-os-release
        arguments:
          parameters:
          - name: image
            value: "{{item.image}}"
          - name: tag
            value: "{{item.tag}}"
        withItems:
        - { image: 'debian', tag: '9.1' }       #item set 1
        - { image: 'debian', tag: '8.9' }       #item set 2
        - { image: 'alpine', tag: '3.6' }       #item set 3
        - { image: 'ubuntu', tag: '17.10' }     #item set 4

  - name: cat-os-release
    inputs:
      parameters:
      - name: image
      - name: tag
    container:
      image: "{{inputs.parameters.image}}:{{inputs.parameters.tag}}"
      command: [cat]
      args: [/etc/os-release]

withParam 예제

이 예제는 바로 앞의 예제와 똑같은 일을 하지만, 정보를 템플릿에 하드코딩하는 대신 withParam으로 JSON 배열 인자를 전달해요.

apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: loops-param-arg-
spec:
  entrypoint: loop-param-arg-example
  arguments:
    parameters:
    - name: os-list                                     # a list of items
      value: |
        [
          { "image": "debian", "tag": "9.1" },
          { "image": "debian", "tag": "8.9" },
          { "image": "alpine", "tag": "3.6" },
          { "image": "ubuntu", "tag": "17.10" }
        ]

  templates:
  - name: loop-param-arg-example
    inputs:
      parameters:
      - name: os-list
    steps:
    - - name: test-linux
        template: cat-os-release
        arguments:
          parameters:
          - name: image
            value: "{{item.image}}"
          - name: tag
            value: "{{item.tag}}"
        withParam: "{{inputs.parameters.os-list}}"      # parameter specifies the list to iterate over

  # This template is the same as in the previous example
  - name: cat-os-release
    annotations: 
      workflows.argoproj.io/display-name: "os-{{inputs.parameters.image}}-{{inputs.parameters.tag}}" # this sets a custom name for the node in the UI, based on the template's parameters
    inputs:
      parameters:
      - name: image
      - name: tag
    container:
      image: "{{inputs.parameters.image}}:{{inputs.parameters.tag}}"
      command: [cat]
      args: [/etc/os-release]

워크플로의 다른 스텝에서 온 withParam 예제

마지막으로, 가장 강력한 형태는 한 스텝에서 객체의 JSON 배열을 동적으로 생성한 뒤 다음 스텝으로 전달하는 것입니다. 그러면 두 번째 스텝에서 사용되는 개수와 값들이 런타임에만 계산돼요.

apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  generateName: loops-param-result-
spec:
  entrypoint: loop-param-result-example
  templates:
  - name: loop-param-result-example
    steps:
    - - name: generate
        template: gen-number-list
    # Iterate over the list of numbers generated by the generate step above
    - - name: sleep
        template: sleep-n-sec
        arguments:
          parameters:
          - name: seconds
            value: "{{item}}"
        withParam: "{{steps.generate.outputs.result}}"

  # Generate a list of numbers in JSON format
  - name: gen-number-list
    script:
      image: python:alpine3.23
      command: [python]
      source: |
        import json
        import sys
        json.dump([i for i in range(20, 31)], sys.stdout)

  - name: sleep-n-sec
    inputs:
      parameters:
      - name: seconds
    container:
      image: alpine:3.23
      command: [sh, -c]
      args: ["echo sleeping for {{inputs.parameters.seconds}} seconds; sleep {{inputs.parameters.seconds}}; echo done"]

루프의 집계 결과에 접근하기

루프가 끝나면 모든 반복(iteration)의 출력을 JSON 배열로 접근할 수 있어요. 아래 예제는 그것을 읽는 방법을 보여 줍니다.

주의할 점: 각 반복의 출력은 반드시(must) 유효한 JSON이어야 합니다.

apiVersion: argoproj.io/v1alpha1
kind: WorkflowTemplate
metadata:
  name: loop-test
spec:
  entrypoint: main
  templates:
  - name: main
    steps:
    - - name: execute-parallel-steps
        template: print-json-entry
        arguments:
          parameters:
          - name: index
            value: '{{item}}'
        withParam: '[1, 2, 3]'
    - - name: call-access-aggregate-output
        template: access-aggregate-output
        arguments:
          parameters:
          - name: aggregate-results
            # If the value of each loop iteration isn't a valid JSON,
            # you get a JSON parse error:
            value: '{{steps.execute-parallel-steps.outputs.result}}'
  - name: print-json-entry
    inputs:
      parameters:
      - name: index
    # The output must be a valid JSON
    script:
      image: alpine:3.23
      command: [sh]
      source: |
        cat <<EOF
        {
        "input": "{{inputs.parameters.index}}",
        "transformed-input": "{{inputs.parameters.index}}.jpeg"
        }
        EOF
  - name: access-aggregate-output
    inputs:
      parameters:
      - name: aggregate-results
        value: 'no-value'
    script:
      image: alpine:3.23
      command: [sh]
      source: |
        echo 'inputs.parameters.aggregate-results: "{{inputs.parameters.aggregate-results}}"'

image

위 워크플로의 마지막 스텝은 다음과 같은 출력을 갖습니다: inputs.parameters.aggregate-results: "[{"input":"1","transformed-input":"1.jpeg"},{"input":"2","transformed-input":"2.jpeg"},{"input":"3","transformed-input":"3.jpeg"}]"

더 알아보기 (Learn more)

  • withSequence는 횟수 기반, withItems는 고정 리스트 기반이고, withParam은 런타임에 생성된 JSON 배열을 받는 가장 동적인 방식이에요.
  • 루프의 집계 결과를 재사용하려면 각 반복의 출력이 반드시 유효한 JSON이어야 합니다.
  • 동적 워크플로가 필요하다면 한 스텝에서 JSON 배열을 생성해 withParam으로 다음 스텝에 전달하는 패턴을 익혀 두세요.