4
4

More than 3 years have passed since last update.

【Ansible】ワイルドカードでディレクトリを検索して中身をコピーする

Last updated at Posted at 2019-10-06

やりたいこと

タイトルのまんまです。
commandモジュールshellモジュール使わずやってみよう!と始めました。

やりかた

たったこれだけですが、意外と手こずりました。。

- name: ディレクトリを探す
  find:
    paths: /hogehoge/
    patterns: "copy*"
    file_type: directory
  register: find_result

- name: 中身をコピー
  synchronize:
    src: "{{ item.path }}/"
    dest: /fugafuga/copyto/
  with_items: "{{ find_result.files }}"
  delegate_to: "{{ inventory_hostname }}"

簡単に説明

ディレクトリを探す

まず、findモジュールでディレクトリを探します。
https://docs.ansible.com/ansible/latest/modules/find_module.html

例では/hogehoge/copy*ディレクトリを探しています。
結果をfind_resultに格納します。

中身をコピー

synchronizeモジュールでコピーします。
https://docs.ansible.com/ansible/latest/modules/synchronize_module.html

例では事前に探したディレクトリの中身を/fugafuga/copyto/以下にコピーしています。

synchronizeモジュールはローカルからリモートに同期するモジュールですが、
delegate_toキーワードを使うとリモート内で(リモートからリモートに)同期できます。
inventory_hostnameは処理中のリモートのことです。
https://docs.ansible.com/ansible/latest/user_guide/playbooks_delegation.html#delegation

コピー元のパスはfind_result.files.pathに入ってますが、filesが配列になってるので with_items で一つずつ取り出して処理します。
https://docs.ansible.com/ansible/2.4/playbooks_loops.html#using-register-with-a-loop

まとめ

commandモジュールやshellモジュールは強力ですが、最終手段にしたいですよね。
実は最初commandモジュールで実装していたのですが、リファクタリングしてたら詰まった!という事例でした。
Ansibleのメリット生かす為にもAnsibleライクな実装を心がけたいですね。

4
4
2

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