iT邦幫忙

2024 iThome 鐵人賽

DAY 3
1
DevOps

菜逼八用Github Actions系列 第 3

Day 03 - YAML基本語法

  • 分享至 

  • xImage
  •  

目錄

摘要

在上一篇我們得知了Github Actions的workflow會用YAML格式撰寫

在這篇我們會了解一下YAML的基本語法,以及一些注意事項

型別

字串

如果是空格開始、結束,或包含空格的字串,應使用單引號把它包住。包含特殊符號的字串也要

# 單行字串
name: Tempura
fullName: 'Tempura Ninja'

如果文字有多行,就要使用保留換行(|),或者摺疊換行(>)

前者會保留所有換行,並把所有換行轉為\n,後者則只在結尾有\n

# 保留換行
content:|
    Lorem ipsum dolor sit amet consectetur adipisicing elit.
    Perferendis beatae nostrum necessitatibus officiis labore.

#相當於
# Lorem ipsum dolor sit amet consectetur adipisicing elit.\n Perferendis beatae nostrum necessitatibus officiis labore.\n

#摺疊換行
content:>
    Lorem ipsum dolor sit amet consectetur adipisicing elit.
    Perferendis beatae nostrum necessitatibus officiis labore. 

#相當於
# Lorem ipsum dolor sit amet consectetur adipisicing elit.Perferendis beatae nostrum necessitatibus officiis labore.\n 

其他

其他基本型別的表達相當簡單

totalCount: 30

# 使用!!int強制轉為integer
totalValue: !!int "42"

使用ISO-8601標準,時間和時區可以不給

today: 2024-09-14
meetingTime: 2024-09-31T10:00:00-08:00
# true、1、on為true
truth=true

# false、0、off為false
lie=false

# null、~為null
noValue=null

物件型別

profile:
    name: Tempura

# 相當於
# {
#   profile:{
#     name: "Tempura",
#   }
# }
hobbies:
    - planting
    - watching anime

# 相當於
# {
#   hobbies: ['planting', 'watching anime']
# }
hobbies:
    - planting
    - watching anime:
        - Kimetsu No Yaiba

錨點

錨點用於複用,可以提高文件的複用性和維護性

使用&可以設置錨點,*則是引用錨點

default: &default
  name: Default Name
  age: 30
​
person1:
  <<: *default
  name: Alice
​
person2:
  <<: *default
  name: Bob
  age: 25

# 相當於
# {
#   "default": {
#     "name": "Default Name",
#     "age": 30
#   },
#   "person1": {
#     "name": "Alice",
#     "age": 30
#   },
#   "person2": {
#     "name": "Bob",
#     "age": 25
#   }
# }

這個功能相當方便,只可惜儘管許多開發者許願希望開放在Github Actions能用,但目前Github Actions並不支援

其他注意事項

  • 大小寫敏感

    • name和Name會被視為兩個不同
      name: Iris
      Name: Penny
      
  • 嚴謹的縮排

    • 不一定要縮幾格,但是同樣階層的屬性一定要對齊
    • 在VS Code 中上可以使用tab做縮排,它會自動幫你轉成空格。但如果是直接在Github上選new workflow做編輯,就只能用空格
  • 冒號後面一定要有一個空格,或者換行

    • 如果沒有的話,key會被誤判成字串而報錯

      https://ithelp.ithome.com.tw/upload/images/20240729/20135568EqUq5LJAYX.png

  • YAML原生並不支援placeholder

    • 有些文章會把{{}}歸在YAML語法,但事實上placeholder並不是YAML原生的標準規格。我們能在Github Actions、Kubernetes之類的平台上用placeholder是因為它們有實作動態替換值的功能
  • 註解

    • 使用#可以表示註解
      # 這是註解
      

上一篇
Day 02 - Github Actions簡介 & YAML簡介 & VS Code套件
下一篇
Day 04 - block-style & flow-style的YAML
系列文
菜逼八用Github Actions29
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言