小技巧 - 在 --extra-vars 帶入 boolean 變數

前兩天在執行 playbook 時,想試著以 –extra-vars / -e 帶入 boolean 型態的變數,卻發現怎麼傳都不行。

我試了

  • True / False
  • true / false
  • yes / no

都不行。

後來試著去把變數印出來,發現都是字串,而非 boolean。

# test-bool.yml
---
- name: Test "--extra-vars" / "-e" with boolean
  hosts: localhost

  vars:
    foo: no

  tasks:
    - debug:
        var: foo

ansible-playbook -i localhost, -c local -e foo=yes test-bool.yml 來執行

輸出結果:

PLAY [Test "--extra-vars" / "-e" with boolean] ***************************************************

TASK [Gathering Facts] ***************************************************************************
ok: [localhost]

TASK [debug] *************************************************************************************
ok: [localhost] => {
    "foo": "yes"
}

PLAY RECAP ***************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

會看到 foo 是個字串。

當然我們可以做額外的判斷,然後使用 | bool 來處理,但這樣實在是不太方便。

後來上網找了一下,發現有人提到一樣的情況:

解決方法也很簡單,就是改傳 json 進去。

ansible-playbook -i localhost, -c local -e '{"foo":true}' test-bool.yml

這樣就可以解決了。