てくなべ (tekunabe)

ansible / network automation / 学習メモ

[Ansible] 変数名を参照する際に "{{ varname }}" のようにクォーテーションで囲う理由

はじめに

2020/06/09 開催の【リモート開催】Ansibleもくもく会 (サーバ編 & NW編)2020.06 にメンターとして参加させていただきました。

いただいた質問の中に、変数名の参照の際にダブルクォーテーションで囲う場合と囲わない場合があるが必須?というものがありました。

確かにテキストの中では、囲ったり囲ってなかったりしました。

普段、癖で囲っているので、そういえばなんでだろうと思い、その場で調べた結果をこちらにも共有します。

[2020/06/10 追記] なお、公式ドキュメントを quote variable で検索しました。

{ で始まる文字列をディクショナリと認識させないため

答えはこちらのページにありました。

docs.ansible.com

{ から始まると、YAMLシンタックス的にディクショナリだと解釈しようとするため、というのが理由でした。

YAML Syntax — Ansible Documentation にも

If a value after a colon starts with a “{“, YAML will think it is a dictionary, so you must quote it

とあります。

例えば、以下のような場合は囲う必要があります。

        msg: "{{ greeting }}"    # OK

以下のように、囲わない場合は、エラーになります。

        msg: {{ greeting }}     # エラー
  • エラー
ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 1 (char 0)

Syntax Error while loading YAML.
  found unacceptable key (unhashable type: 'AnsibleMapping')

The error appears to be in '/home/studentXX/ansible-files/test.yml': line 11, column 15, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

      debug:
        msg: {{ greeting }}
              ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:

    with_items:
      - {{ foo }}

Should be written as:

    with_items:
      - "{{ foo }}"

一方で、これはエラーになりません。

        msg: msg is {{ greeting }}   # セーフだが・・

まとめ

混乱を避けるため、クォーテーションで囲うように統一するのが良いと思いました。