如何将 YAML 作为 bash 脚本中的文本嵌入到 YAML 中?

How do I embed YAML inside a YAML as text in bash script?

我正在使用 bash 组装 YAML 构建管道,如下所示。

      cat <<EOT >> ${BUILD_SOURCESDIRECTORY}/azure-pipelines.yml
  - template: templates/deploy-to-env-ssh.yml@infrastructure
    parameters:
      dockerHostEndpoint: ${DOCKER_HOST}
      jobName: ${BASENAME}
      stackName: ${STACK_NAME}
      composeFile: ${STACK_NAME}.yml
      schedule: ???
        $(cat schedule.yml)
      tz: ${TZ}
EOT

我想要的是将以下 YAML 作为字符串存储到 schedule 中,我可以在管道的另一部分中重复使用。

version: 1.4
jobs:
  DockerJob:
    cmd: docker ps
    time: "*"
    notifyOnSuccess:
      - type: stdout
        data:
          - stdout

不过好像需要缩进

您可以使用 pr 实用程序:

cat <<EOF >> ${BUILD_SOURCESDIRECTORY}/azure-pipelines.yml
  - template: templates/deploy-to-env-ssh.yml@infrastructure
    parameters:
      dockerHostEndpoint: ${DOCKER_HOST}
      jobName: ${BASENAME}
      stackName: ${STACK_NAME}
      composeFile: ${STACK_NAME}.yml
      schedule: $(printf "\n" && pr -to 8 schedule.yml)
      tz: ${TZ}
EOT

我使用 printf "\n" 因为如果你想在新行上写 $(…) 就需要将 $(…) 放在第一列,因为每一行包括第一行一个将被给定的空格数偏移。