## 執行命令模塊 [shell][1] 和 command
這兩個模塊都用來執行命令,shell的范圍更大,支持腳本和管道,因此推薦使用shell。
>[info] -m 指定模塊 module
> -a 指定參數 args
當參數為沒有空格隔開的內容時,可以不使用引號(單引號/雙引號都可以);否則要使用引號。
### 選項
```
chdir
change dir
creates
a filename, when it already exists, this step will not be run.
removes
a filename, when it does not exist, this step will not be run.
warn
no
yes
```
### 返回結果

### 命令行使用格式
```
ansible anserver -m command -a 'hostname'
ansible anserver -m shell -a 'hostname'
```
### 腳本的遠程執行
先使用copy模塊復制腳本到遠程客戶端,再使用shell模塊執行
```
# ansible anserver -m shell -a '/tmp/test.sh'
若文件無執行權限,則可使用以下
# ansible anserver -m shell -a '/bin/bash /tmp/test.sh'
```
### 在playbook中使用格式
```
---
- name: shell and command test
hosts: s.hi.com
tasks:
- name: shell test
shell: hostname
- name: command test
command: hostname
```
### 補充
當不指定模塊時,默認使用`command`模塊
`ansible hostname -a 'hostname'`
## 示例
~~~
# 使用args來執行一些選項
- name: This command will change the working directory to somedir/ and will only run when somedir/somelog.txt doesn't exist.
shell: somescript.sh >> somelog.txt
args:
chdir: somedir/
creates: somelog.txt
executable: /bin/bash
# /bin/sh不能同時處理重定向和通配符操作,使用/bin/bash可以
- name: Run a command that uses non-posix shell-isms (in this example /bin/sh doesn't handle redirection and wildcards together but bash does)
shell: cat < /tmp/*txt
args:
executable: /bin/bash
# 在另一個解釋器下執行
- name: Run expect to wait for a successful PXE boot via out-of-band CIMC
shell: |
set timeout 300
spawn ssh admin@{{ cimc_host }}
expect "password:"
send "{{ cimc_password }}\n"
expect "\n{{ cimc_name }}"
send "connect host\n"
expect "pxeboot.n12"
send "\n"
exit 0
args:
executable: /usr/bin/expect
delegate_to: localhost
~~~
[1]:http://docs.ansible.com/ansible/shell_module.html
- 目錄
- ansible基礎
- ansible簡介
- ansible安裝和測試
- ansible配置文件
- 常用命令
- yaml在ansible中的用法
- inventory
- 變量與facts
- when語句
- handler模塊
- 大雜燴
- ansible模塊
- assert 模塊
- copy模塊
- cron模塊
- debug模塊
- django_manage模塊
- file模塊
- filesystem模塊
- git模塊
- hostname模塊
- lineinfile模塊
- mount模塊
- mysql_user模塊
- mysql_db模塊
- pip模塊
- selinux
- setup模塊
- shell 和 command 模塊
- stat模塊
- supervisorctl
- systemd
- timezone
- unarchive模塊
- user模塊
- wait_for
- yum和service模塊
- 其他模塊或者方法
- setup模塊
- url模塊
- slack 模塊
- pause 模塊
- 其他
- 報錯處理
- playbooks
- 復雜的playbook
- 循環
- roles
- YAML
- jinja2