広告 Ansible

Ansibleのshellモジュールとcommandモジュールの使い分け

Ansibleのshellモジュールとcommandモジュールの使い分けがいまいちわかんなくて、調べてみました。

Ansibleの公式ドキュメントでは下記のようにありました。

shellモジュール

The shell module takes the command name followed by a list of space-delimited arguments.
It is almost exactly like the command module but runs the command through a shell (/bin/sh) on the remote node.


If you want to execute a command securely and predictably, it may be better to use the command
module instead. Best practices when writing playbooks will follow the trend of using command
unless shell is explicitly required. When running ad-hoc commands, use your best judgement.

安全で、想定通りの実行結果を得たいときは commandモジュールを使用する方がいいんですね。

commandモジュール

The command module takes the command name followed by a list of space-delimited arguments.
The given command will be executed on all selected nodes. It will not be processed through the shell,
so variables like $HOME and operations like "<", ">", "|", and "&" will not work (use the shell module if you need these features).


If you want to execute a command securely and predictably, it may be better to use the command
module instead. Best practices when writing playbooks will follow the trend of using command unless
shell is explicitly required. When running ad-hoc commands, use your best judgement.

他方、commandモジュールはリモートノードのシェル経由ではないのでパイプやリダイレクト、環境変数が使用できない。

パイプなりリダイレクト使いたければshellモジュールを使うしかない、と。

まとめ

shellモジュールとcommandモジュールの特性と使い分けについて、ざっくりとまとめました。

shellモジュール

shellはリモートノードのシェル(/bin/sh)を通して実行される。

次の文字を使用できる。

$HOME, "<", ">", "|", "&"

変数を埋め込む場合などにエスケープ漏れしやすいので気をつけないといけない。

commandモジュール

commandはシェル経由ではないので次の文字を使用できない。

$HOME, "<", ">", "|", "&"

shellが必要無い場合は command を使う方が安全

原則commandモジュールを使用すべき

Sponsor Link

-Ansible