1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Ansible Tips: YAMLやJSONにおけるnullは、{{ }}内のJinja2フォーマットではnone

Last updated at Posted at 2024-06-03

備忘

nullやnoneは混乱することが多いので確認

YAMLやJSONにおけるnullは、{{ }}内やwhen:式やdebug出力などではNone

サマリー

JSON YAML(フロースタイル) Jinja2 debug出力
null null, Null, NULL, ~ none, None None もしくは出力なし

    - vars:
        l1: "{{ [none,None] }}"
        l2: "{{ '[null]' | from_json }}"
        l3: "{{ '[null,Null,NULL,~]' | from_yaml }}"
        l4: [null,Null,NULL,~,!!null ""]
        l5:
          - null
          - Null
          - NULL
          - ~
          -
      ansible.builtin.debug:
        msg: |-
          {{ l1 }}
          {{ l2 }}
          {{ l3 }}
          {{ l4 }}
          {{ l5 }}
TASK [ansible.builtin.debug] ***********************************************************************************************************
ok: [localhost] => {}

MSG:

[None, None]
[None]
[None, None, None, None]
[None, None, None, None, None]
[None, None, None, None, None]

when: などではjinja2フォーマットという理解なのでNone

    - loop:
        -
        - foo
      when: item != None
      ansible.builtin.debug:
        var: item
TASK [ansible.builtin.debug] ***********************************************************************************************************
skipping: [localhost] => (item=None)  => {
    "ansible_loop_var": "item",
    "false_condition": "item != None",
    "item": null
}
ok: [localhost] => (item=foo) => {
    "ansible_loop_var": "item",
    "item": "foo"
}

ちなみにansible-lint --fixをかけると

---
- hosts: all
  gather_facts: false
  tasks:
    - vars:
        l1: "{{ [none, None] }}"
        l2: "{{ '[null]' | from_json }}"
        l3: "{{ '[null,Null,NULL,~]' | from_yaml }}"
        l4: [!!null "", !!null "", !!null "", !!null "", !!null ""]
        l5:
          -
          -
          -
          -
          -
      ansible.builtin.debug:
        msg: |-
          {{ l1 }}
          {{ l2 }}
          {{ l3 }}
          {{ l4 }}
          {{ l5 }}

フロースタイルにおける!!null ""は冗長に感じるので、個人的にはnullで良いかと。
ブロックスタイルは何も書かないことでnullを表現。こちらは明瞭。

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?