12
7

More than 5 years have passed since last update.

Ansible の script module の挙動

Posted at

言いたいこと:

script module のスクリプトを相対パスで指定するときは roles/:name/files の中にあると判断される

Ansible 書くのが辛いから shell script 書いて ansible 内で実行してもいい?

って言われたもんでそういうモジュールあるかと思って調べたら script module ってのがあった

使い方は

- name: Run script
  script: /path/to/script.sh --with-args 1234

という感じで script のキーのあとに実行するスクリプトを指定するだけのシンプルなモジュールなのだけど、ドキュメントがすべて絶対パス前提になっている。

相対パスで指定した場合、どこにあるファイルが呼ばれるの?

ってことで確認。
次の Playbook を用意して ping という名前の role を用意。

pingbook.yml
hosts: all
roles:
  - ping

rolesの内容は次のような感じ。

roles/ping/tasks/main.yml
- name: Run script
  script: script.sh
  register: result
- debug:
    var: result

そしてどこで呼ばれるのかを試すためのディレクトリ構成は下のとおり。
あとスクリプトの中身も下にあるような感じで scripts, files, templates で末尾を変えてます。

takayuki@takayukioda:~/vagrant/sandbox$ tree roles/
roles/
└── ping
    ├── files
    │   └── script.sh
    ├── scripts
    │   └── script.sh
    ├── tasks
    │   └── main.yml
    └── templates
        └── script.sh

5 directories, 4 files

takayuki@takayukioda:~/vagrant/sandbox$ cat roles/ping/files/script.sh 
#!/bin/sh

pwd
echo "roles/ping/files"

ほいでもって実行結果はこちら。

takayuki@takayukioda:~/vagrant/sandbox$ ansible-playbook -i localhost pingbook.yml 

PLAY [Ping] ******************************************************************* 

GATHERING FACTS *************************************************************** 
ok: [localhost]

TASK: [ping | Run script] ***************************************************** 
changed: [localhost]

TASK: [ping | debug ] ********************************************************* 
ok: [localhost] => {
    "var": {
        "result": {
            "changed": true, 
            "invocation": {
                "module_args": "script.sh", 
                "module_complex_args": {}, 
                "module_name": "script"
            }, 
            "rc": 0, 
            "stderr": "", 
            "stdout": "/home/takayuki/vagrant/sandbox\nroles/ping/files\n", 
            "stdout_lines": [
                "/home/takayuki/vagrant/sandbox", 
                "roles/ping/files"
            ]
        }
    }
}

TASK: [ansible user] ********************************************************** 
ok: [localhost] => {
    "var": {
        "ansible_user_id": "takayuki"
    }
}

PLAY RECAP ******************************************************************** 
localhost                  : ok=4    changed=1    unreachable=0    failed=0   

ということで相対パスの際は roles/:name/files 直下のファイルが使われることが分かった。

ansible のドキュメントは基本丁寧なんだけど、たまに求めてるのがなくて辛い。

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