1. ホーム
  2. スクリプト・コラム
  3. リナックスシェル

ansibleでシェルスクリプトを実行する方法

2022-01-05 02:22:26

1. スクリプトを書く: pb_shell.sh

wfq@ubuntu:~/playbook$ cat pb_shell.sh 
#!binecho "today(`date`) is a nice day, since I do some nice demo about ansible and excute very well." > /home/wfq/playbook/pb.log
wfq@ubuntu:~/playbook$

2. ansibleコマンドを実行し、スクリプトを他の複数のサーバーにコピーします。

wfq@ubuntu:~/playbook$ ansible asb -m copy -a "src=/home/wfq/playbook/pb_shell.sh dest=/home/wfq/playbook/"
192.168.174.134 | success >> {
    "changed": true, 
    "dest": "/home/wfq/playbook/pb_shell.sh", 
    "gid": 1000, 
    "group": "wfq", 
    "md5sum": "79744ccf5b60c7d020bb261d11516252", 
    "mode": "0664", 
    "owner": "wfq", 
    "size": 135, 
    "src": "/home/wfq/.ansible/tmp/ansible-tmp-1523198762.69-211691352620479/source", 
    "state": "file", 
    "uid": 1000
}

192.168.174.131 | success >> {
    "changed": true, 
    "dest": "/home/wfq/playbook/pb_shell.sh", 
    "gid": 1000, 
    "group": "wfq", 
    "md5sum": "79744ccf5b60c7d020bb261d11516252", 
    "mode": "0664", 
    "owner": "wfq", 
    "size": 135, 
    "src": "/home/wfq/.ansible/tmp/ansible-tmp-1523198762.69-274155692570175/source", 
    "state": "file", 
    "uid": 1000
}

192.168.174.133 | success >> {
    "changed": true, 
    "dest": "/home/wfq/playbook/pb_shell.sh", 
    "gid": 1000, 
    "group": "wfq", 
    "md5sum": "79744ccf5b60c7d020bb261d11516252", 
    "mode": "0664", 
    "owner": "wfq", 
    "size": 135, 
    "src": "/home/wfq/.ansible/tmp/ansible-tmp-1523198764.85-163098225256987/source", 
    "state": "file", 
    "uid": 1000
}

192.168.174.132 | success >> {
    "changed": true, 
    "dest": "/home/wfq/playbook/pb_shell.sh", 
    "gid": 1000, 
    "group": "wfq", 
    "md5sum": "79744ccf5b60c7d020bb261d11516252", 
    "mode": "0664", 
    "owner": "wfq", 
    "size": 135, 
    "src": "/home/wfq/.ansible/tmp/ansible-tmp-1523198764.89-251052794120091/source", 
    "state": "file", 
    "uid": 1000
}

wfq@ubuntu:~/playbook$ 

3. 3. ansibleコマンドを実行し、デイリーサーバーでpb_shell.shスクリプトを実行します。

wfq@ubuntu:~/playbook$ ansible asb -m shell -a "sh /home/wfq/playbook/pb_shell.sh chdir=/home/wfq/playbook"
192.168.174.134 | success | rc=0 >>
192.168.174.131 | success | rc=0 >>
192.168.174.132 | success | rc=0 >>
192.168.174.133 | success | rc=0 >>

4. 例えば、サーバー131で、実行によって生成されたログを表示します。

wfq@ubuntu:~/playbook$ cat pb.log 
today(Sun Apr 08, 2018 22:46:19 CST) is a nice day, since I do some nice demo about ansible and excute very well.
wfq@ubuntu:~/playbook$ 
wfq@ubuntu:~/playbook$ ls
pb.log pb_shell.sh
wfq@ubuntu:~/playbook$ 

ansibleでシェルスクリプトを実行する方法は、この記事ですべてです。ansibleでシェルスクリプトを実行する方法については、BinaryDevelopの過去の記事を検索するか、以下の記事を引き続き閲覧してください。