YAML 裡的字串很長該怎麼做?

Playbook 是使用 YAML 格式,在使用上難免會遇到要放很長的字串的情況,想保留可讀性又不想有多餘的換行符號,該怎麼辦呢?

在 YAML 裡已經有規範此部份,在這種情況有四種方法可以幫助我們:

  • |: 其下內容的換行,就是換行,最後一行會有換行。
  • >: 其下內容的換行,不會是換行,會變為一個很長的字串,最後會有換行。
  • |-: 其下內容的換行,就是換行,但最後一行不會有換行。
  • >-: 其下內容的換常,不會是換行,最後一行也不會有換行。

直接來看看範例

---
- name: Test long string
  hosts: all

  vars:
    s1: "hello"
    s2: |
      s2
      this is my very very very
      long string
      line1
      line2
      line3
    s3: >
      s3
      this is my very very very
      long string
      line1
      line2
      line3
    s4: |-
      s4
      this is my very very very
      long string
      line1
      line2
      line3
    s5: >-
      s5
      this is my very very very
      long string
      line1
      line2
      line3

  tasks:
    - name: s1
      copy:
        content: "{{ s1 }}"
        dest: "/tmp/s1.txt"
    - name: s2
      copy:
        content: "{{ s2 }}"
        dest: "/tmp/s2.txt"
    - name: s3
      copy:
        content: "{{ s3 }}"
        dest: "/tmp/s3.txt"
    - name: s4
      copy:
        content: "{{ s4 }}"
        dest: "/tmp/s4.txt"
    - name: s5
      copy:
        content: "{{ s5 }}"
        dest: "/tmp/s5.txt"

s2~s5 這四個變數裡的內容分別以 |, >, |-, >- 來定義。

接著來看看執行結果

$ cat /tmp/s1.txt 
hello%
$ cat /tmp/s2.txt 
s2
this is my very very very
long string
line1
line2
line3
$ cat /tmp/s3.txt 
s3 this is my very very very long string line1 line2 line3
$ cat /tmp/s4.txt 
s4
this is my very very very
long string
line1
line2
line3%
$ cat /tmp/s5.txt 
s5 this is my very very very long string line1 line2 line3%        

從執行結果,就可以看到如同之前所描述的情況。

簡單的說,>>- 可以增加 YAML 的可讀性,又不會有多餘的換行符號。而 ||- 則可以讓字串跟定義的一致,在 YAML 裡看到換行,那字串裡就會有換行符號。

參考資料