1
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】regex_searchの検索内容に変数を使いたい

Last updated at Posted at 2021-05-21

はじめに

<バージョン>
ansible 2.9.7

 文字列の検索には__regex_search__が便利なので使っていましょう。
 今回は以下のような複数行のデータに対し、与えられた条件のような確認をしてみましょう。
条件

  1. appleが含まれること
  2. orangeが含まれないこと
sample_data
fruit
  apple
  peach
  banana

1. 参考playbook

 今回は、loopで変数を渡すことによって検索を行います。このようにすると汎用性も高まりますね。
ポイント
(1)__multiline=true__を入れると、複数行にわたって検索出来る
(2)regex_search内に変数を入れることも可能

sample_search.yml
---
- hosts: localhost
  connection: local
  gather_facts: false
  vars:
    sample_data: |
      fruit
        apple
        peach
        banana
  tasks:
    - name: "search"
      debug:
        msg: "match"
      loop:
        - "apple"
        - "orange"
      when:    # ポイント
        - >-
          sample_data | regex_search('^\s+' + item + '$', multiline=true)

2. 実行結果

 想定通りの結果を得ることが出来ました。ちなみに、whenの内容を__not sample_data ~__にすると
regex_searchにマッチしない場合に処理が実行されます。

出力
(venv) [centos@ip-<ip addr> ansible]$ ansible-playbook sample_search.yml 

PLAY [localhost] *********************************************************************************************************

TASK [search] **************************************************************************************************************
ok: [localhost] => (item=apple) => 
  msg: match
skipping: [localhost] => (item=orange) 

PLAY RECAP ***************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

参考記事

フィルター — Ansible Documentation

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