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?

More than 5 years have passed since last update.

Ansibleでバックスラッシュをto_jsonフィルタで出力したい

Last updated at Posted at 2020-02-25

Problem

Ansibleのtemplateモジュールでvarsに定義したバックスラッシュ\を含む文字列を出力する場合、varsで'\'のようにシングルクォートで囲めばバックスラッシュのまま出力されますが、to_jsonフィルタでJSONとして出力させようとすると、\\のように勝手にエスケープされてしまいます。

環境

  • Ansible 2.8.5
  • jinja2 2.10.1

単純な出力

vars.yml
---
vars:
  include_backslash_text: '\n'
template.j2
{{ vars.include_backslash_text }}
出力結果
\n

to_jsonフィルタによる出力

vars.yml
---
vars:
  include_backslash_text: '\n'
template.j2
{{ vars.include_backslash_text | to_json }}
出力結果
"\\n"

おそらく、to_jsonフィルタによって値がダブルクォートで囲まれるため、フィルタが気を利かせてエスケープするものと思われます。
では、\nのようなバックスラッシュを含む文字列をそのままJSON形式で出力するにはどうすればいいのでしょうか。

Solution

試行錯誤の結果、以下でうまくいきました。

vars.yml
---
vars:
  include_backslash_text: "\n" # ダブルクォートにする
template.j2
{{ vars.include_backslash_text | to_json | regex_replace("\\\\", "\\\\") }}
出力結果
"\n"

なぜこれでうまくいくのかよく分かりませんが、もっといい書き方があれば教えてください。

1
1
0

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?