ansible語法
注意:需要提示分發公鑰
ansible test -a "free -h"
ansible test -m command -a "free -h"
-m:指定模塊
-a:指定參數
test 對應 /etc/ansible/hosts中的[test]
all 對應 /etc/ansible/hosts所有ip
注意:默認模塊不支持管道通信
常用參數
參數 | 解釋 |
---|---|
-m | 模塊,默認command |
-a | 參數 |
-C,--checks | 檢查,預期執行 |
-syntax-checks | 檢查劇本,預期執行 |
顏色說明
綠:正常
紅:異常
黃:有變動
模塊詳情
查看模塊信息
ansible-doc -v command
chdir參數的使用:
ansible test -m command -a "chdir=/etc pwd"
shell模塊
注意:執行時,各主機本地需要存在shell腳本
與command模塊的不同在於,shell模塊可以使用變量,管道,定向符號等
script
當前節點的本地腳本,遠程執行
#本地節點腳本文件
cat >/home/centos/sh.sh <<EOF
#!/bin/bash
echo $HOSTMANE
w
ping qq.com -c 2
EOF
#遠程執行本地文件
ansible test -m script -a "/home/centos/sh.sh"
腳本文件不具有執行權限,也可以遠程執行命令
copy
參數 | 說明 |
---|---|
backup | 是否備份遠程已存在的文件 |
content | 可以設定文件的值 |
dest | 遠端路徑 |
directory_mode | 遞歸設置目錄的權限,默認為系統權限 |
forces | 文件內容存在差異,forces為yes則覆蓋,為no,則不覆蓋。默認覆蓋。別名:thirsty |
src | 路徑以/結尾,只復制目錄中的文件,否則遞歸復制所有文件,類似rsync |
mode | 權限位設置 |
owner | 屬主 |
group | 屬組 |
src 不能和 content一起使用
copy使用示例
遠程復制
ansible test -m copy -a "src=/etc/hosts dest=~/ mode=0644 owner=centos group=centos"
ansilbe test -m shell -a "ls -la ~/host*"
遠程執行 主機復制本地文件
#本地創建一個文件
touch sh.sh
ansible test -m copy -a "src=~/sh.sh dest=~/sh.sh.sh remote_src=true"
#此時僅能在本地機器上顯示復制的文件,表明remote_src為true時只能復制遠端已存在的文件
ansible test -m shell -a "ls -l ~/sh*"
內容傳遞
注意:換行符使用\n代替
ansible test -m copy -a "content='hello\nworld' dest=~/h.c mod=0600"
ansilbe test -m shel -a "cat ~/.h.c"
file
主要用於創建文件,刪除文件,設置文件屬性
普通參數
參數 | 說明 |
---|---|
owner | 屬主 |
group | 屬組 |
mode | 權限 |
dest | 遠端路徑 |
src | 本地路徑 |
state
有存在多種狀態,如下
參數 | 說明 |
---|---|
directory | 目錄 |
file | 文件 |
link | 軟鏈接 |
hard | 硬鏈接 |
absent | 遞歸刪除目錄,取消軟鏈接 |
touch | 創建文件 |
注意:不能同時遞歸創建目錄和重命名
創建目錄
ansible test -m file -a "path=~/a/b/c/d/e/f state=directory"
ansible test -m shell -a "tree ~/"
遞歸刪除目錄
#根據之前創建的目錄
ansible test -m file -a "dest=~/a state=absent"
ansible test -m shell -a "ls -l ~/"
創建文件
ansible test -m file -a "dest=~/a.txt state=touch"
ansible test -m shell -a "ls ~/"
創建軟鏈接
#根據之前創建的文件,創建軟鏈接
ansible test -m file -a "dest=~/softa.txt src=~/a.txt state=link"
ansible test -m shell -a "ls -l ~/"
創建硬鏈接
#先給a.txt文件追加"hello\nworld"
ansible test -m shell -a "rm -f ~/a.txt"
ansible test -m copy -a "content='hello\nworld' dest=~/a.txt"
ansible test -m shell -a "cat ~/a.txt"
ansible test -m file -a "dest=~/ahard.txt src=~/a.txt state=hard"
ansible test -m shell -a "cat ~/ahard.txt"
ansible test -m shell -a "ls -il | grep a"