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

【Ansible】変数結合時に()を入れないとどうなるのか検証してみた

Last updated at Posted at 2021-04-23

はじめに

<バージョン>
ansible 2.9.7
 Ansibleでは以下のようにリストを結合することが出来ますが、これをfilterにかけるときは
注意が必要みたいです。今回はuniqueフィルターで検証します。

sample.yml
---
- name: list test
  hosts: localhost
  gather_facts: no
  vars:
    list1: ['a', 'b', 'c']
    list2: ['b', 'd', 'b']
  tasks:
    - name:
      debug:
        var: list1 + list2

1-1. 参考playbook1

 特に何も気にせず、uniqueフィルターにかけてみましょう。

list_test_1.yml
---
- name: list test
  hosts: localhost
  gather_facts: no
  vars:
    list1: ['a', 'b', 'c']
    list2: ['b', 'd', 'b']
  tasks:
    - name:
      debug:
        var: list1 + list2 | unique

1-2. 実行結果1

 後半のlist2にしかフィルターがかかりませんでした。

出力
  - a
  - b
  - c
  - b
  - d

2-1. 参考playbook2

 list1とlist2を( )で囲いましょう。

list_test_2.yml
---
- name: list test
  hosts: localhost
  gather_facts: no
  vars:
    list1: ['a', 'b', 'c']
    list2: ['b', 'd', 'b']
  tasks:
    - name:
      debug:
        var: (list1 + list2) | unique

2-2. 実行結果2

 全体にフィルターがかかりました。

出力
  - a
  - b
  - c
  - d

3-1. 参考playbook3

 ここまで来ると法則性がわかったと思いますが、念のためリストを3個にしてみます。

list_test_3.yml
---
- name: list test
  hosts: localhost
  gather_facts: no
  vars:
    list1: ['a', 'b', 'c']
    list2: ['b', 'd', 'b']
    list3: ['a', 'd', 'd']
  tasks:
    - name:
      debug:
        var: list1 + list2 + list3 | unique

3-2. 実行結果3

 list3にだけfilterがかかりました。

出力
  - a
  - b
  - c
  - b
  - d
  - b
  - a
  - d

まとめ

 ( )をつけずに変数の結合結果をフィルターに渡すと、最後の変数にだけfilterがかかるので注意しましょう。

参考記事

変数文字列を連結する適切な方法

2
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
2
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?