0
0

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 3 years have passed since last update.

Ansibleと変数と時々jinja2

Last updated at Posted at 2020-06-01

はじめに

Ansibleのtemplatesで使用される、jinja2はAnsibleのYAMLファイル内でも使用できます。

jinja2の表記を使用したい箇所を{{ }}で囲むだけです。
また、別の変数も{{ }}内で参照することができます。

playbook.yml
- hosts: localhost
  connection: local
  vars:
    file_path: /path/to/file
    file_name: "{{ file_path.split('/')[-1] }}"
    dir_name: "{{ file_path.split('/')[-2] }}"
  tasks:
    - name: "print file_path"
      debug:
        msg: var={{ file_path }} # var=/path/to/file

    - name: "print file_name"
      debug:
        msg: var={{ file_name }} # var=file

    - name: "print dir_name"
      debug:
        msg: var={{ dir_name }} # var=to

利用できる場所に指定はありません。
例えば、変数定義であればvars/main.yml, group_vars/, host_vars/などで利用可能です。

終わりに

上記の使い方はちょっとアレですが。。。
変数定義で上手に利用すると変更があった際に、修正箇所が少なくできます。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?