?
目錄
特點
參數總結
?使用?ansible?命令
1. 基本示例
2. 傳遞參數
3. 使用?creates?參數
4. 使用?removes?參數
?示例 Playbook 文件
?基本語法
1. 基本使用
2. 傳遞參數
3. 使用?creates?參數
4. 使用?removes?參數
5. 使用?register?捕獲輸出
6. 使用?args?指定參數
Ansible 的?script
?模塊是用來在遠程主機上運行本地腳本文件的一個模塊。它將本地腳本文件復制到目標主機上并執行。這個模塊對于一些復雜操作性任務或者需要快速運行自定義腳本的場景非常有用。
特點
- 腳本語言不限:可以是任何可執行的腳本,比如 Bash、Python、Perl 等。
- 參數傳遞:允許傳遞參數給腳本。
- 直接執行:無需考慮遠程主機的具體環境,直接在遠程主機上執行腳本。
?
參數總結
-
chdir
:- 描述:在執行腳本前更改到此目錄。
- 類型:字符串
- 默認值:無
-
creates
:- 描述:僅在指定文件不存在時執行腳本。
- 類型:字符串
- 默認值:無
-
executable
:- 描述:用于執行腳本的可執行程序(例如
bash
,python
,ruby
等)。 - 類型:字符串
- 默認值:無
- 描述:用于執行腳本的可執行程序(例如
-
removes
:- 描述:僅在指定文件存在時執行腳本。
- 類型:字符串
- 默認值:無
-
stdin
:- 描述:為腳本提供標準輸入。
- 類型:字符串
- 默認值:無
-
stdin_add_newline
:- 描述:如果為
yes
,則在標準輸入數據末尾添加一個新行。 - 類型:布爾值
- 默認值:
yes
- 描述:如果為
-
strip_empty_ends
:- 描述:如果為
yes
,則從標準輸入數據的兩端移除空行。 - 類型:布爾值
- 默認值:
no
- 描述:如果為
-
cmd
:- 描述:要執行的本地腳本的路徑和可選參數。
- 類型:字符串或列表
- 必需:是
?
?使用?ansible
?命令
?
1. 基本示例
在遠程主機上運行本地腳本?my_script.sh
:
ansible all -m script -a "/path/to/my_script.sh"
2. 傳遞參數
在遠程主機上運行本地腳本?my_script.sh
?并傳遞參數:
ansible all -m script -a "/path/to/my_script.sh --option value"
3. 使用?creates
?參數
只有在遠程主機上不存在?/tmp/myfile
?時才運行腳本:
ansible all -m script -a "creates=/tmp/myfile /path/to/my_script.sh"
4. 使用?removes
?參數
只有在遠程主機上存在?/tmp/myfile
?時才運行腳本:
ansible all -m script -a "removes=/tmp/myfile /path/to/my_script.sh"
?
?示例 Playbook 文件
?
?基本語法
一個典型的?script
?模塊結構如下:
- name: Description of the taskscript: /path/to/local/script.sh
還可以添加多個可選參數,如?creates
?和?removes
,來條件化執行腳本。
1. 基本使用
在遠程主機上執行腳本?my_script.sh
:
---
- name: Run basic scripthosts: alltasks:- name: Execute the scriptscript: /path/to/my_script.sh
2. 傳遞參數
在遠程主機上執行腳本?my_script.sh
?并傳遞參數:
---
- name: Run script with argumentshosts: alltasks:- name: Execute the script with argumentsscript: /path/to/my_script.sh --option value
3. 使用?creates
?參數
只有在遠程主機上不存在?/tmp/myfile
?文件時才執行腳本:
---
- name: Conditionally run script if file does not existhosts: alltasks:- name: Execute the script if file does not existscript:path: /path/to/my_script.shcreates: /tmp/myfile
4. 使用?removes
?參數
只有在遠程主機上存在?/tmp/myfile
?文件時才執行腳本:
---
- name: Conditionally run script if file existshosts: alltasks:- name: Execute the script if file existsscript:path: /path/to/my_script.shremoves: /tmp/myfile
5. 使用?register
?捕獲輸出
捕獲腳本執行的輸出并在后續任務中使用:
---
- name: Capture script outputhosts: alltasks:- name: Run script and capture outputscript: /path/to/my_script.shregister: script_output- name: Print script outputdebug:var: script_output.stdout
6. 使用?args
?指定參數
在腳本中指定額外參數:
---
- name: Run script with specific argumentshosts: alltasks:- name: Execute the script with multiple argumentsscript:path: /path/to/my_script.shargs:creates: /tmp/myfileremoves: /tmp/removefile
?