Ansible Ad-Hoc 常用命令
Ansible可以通過命令行形式使用它的模塊,Ansible自帶了很多模塊,可以直接使用這些模塊。目前Ansible已經自帶了259個模塊,可以通過ansible-doc -l 顯示所有自帶的模塊,也可以通過ansible-doc -s 模塊名 查看模塊的介紹及使用示例。
Ansible命令行的基本格式如下:
ansible <host-pattern> [-m modult_name] [-a agrs]
基本語法說明:
<host-pattern> :主機 [-m modult_name] :模塊名 [-a agrs]:模塊的參數
列出可使用的模塊名稱:
ansible-doc -l
列出某個模塊的描述信息和使用示例:
ansible-doc -s yum
command模塊(默認)
Ansible管理工具使用-m選項來指定使用模塊,默認使用command模塊,即-m選項省略時會運行此選項,用於在被管理節點上運行命令
1.對所有被管節點連通性進行測試
ansible all -m ping
2.查詢被管節點的系統時間
ansible webserver -m command -a ‘date‘
cron模塊 計劃性任務 (兩種狀態state: present:添加,absent:移除)
Ansible中的cron模塊用於定義計劃性任務。其中有兩種狀態(state):present表示添加(省略狀態時默認使用),absent表示移除
1.添加計劃性任務
ansible webserver -m cron -a ‘minute="*/10" job="/usr/bin/echo hello" name="test cron job"‘
2.查詢系統計劃性任務
ansible webserver -a ‘crontab -l‘
3.移除該計劃性任務
ansible webserver -m cron -a ‘minute="*/10" job="/usr/bin/echo hello" name="test cron job" state=absent‘
user模塊
Ansible中的user模塊用於創建新用戶和更改、刪除已存在的用戶。
1.創建用戶user1
ansible webserver -m user -a ‘name="user1"‘
2.刪除用戶mysql
ansible webserver -m user -a ‘name="user1" state=absent‘
group模塊
Ansible中的group模塊用於對用戶組進行管理
1.創建mysql組
ansible webserver -m group -a ‘name=mysql gid=306 system=yes‘
2.新建mysql組的user2用戶
ansible webserver -m user -a ‘name=user2 uid=306 system=yes group=mysql‘
copy模塊
Ansible中的copy模塊用於實現文件復制和批量下發文件,其中使用src定義本地源文件路徑,dest定義被管理主機文件路徑,使用content則是通過指定信息內容來生成目標文件
1.復制文件
ansible webserver -m copy -a ‘src=/etc/fstab dest=/tmp/fstab.txt owner=root mode=600‘
2.查看復制後的文件
ansible webserver -a ‘cat /tmp/fstab.txt‘
file模塊
在Ansible中使用file模塊來設置文件屬性,其中path指定文件路徑,src指定源文件路徑,使用name和dest來替換創建文件的符號鏈接
1.修改文件的屬性
ansible webserver -m file -a ‘owner=mysql group=mysql mode=644 path=/tmp/fstab.txt‘
2.創建連接文件
ansible webserver -m file -a ‘path=/tmp/fstab.link src=/tmp/fstab.txt state=link‘
3.創建空問文件/tmp/test1.txt
ansible webserver -m file -a ‘path=/tmp/test1.txt state=touch‘
ping模塊
Ansible中使用ping模塊來檢測指定主機的連通性
ansible all -m ping
shell模塊
Ansible中的shell模塊可以在被管理節點上運行命令,並支持像管道符等功能的復雜命令。
1.創建user3用戶
ansible webserver -m user -a ‘name=user3‘
2.設置user3用戶的密碼
ansible webserver -m shell -a ‘echo abc123|passwd --stdin user3‘
script模塊
Ansible中的script模塊可以將本地腳本文件復制到被管理節點上進行運行(需使用相對路徑來指定腳本)。
yum模塊
Ansible中的yum模塊負責在被管理節點上安裝與卸載軟件包,但是需要提前在每個節點配置自己的yum倉庫。其中name指定要安裝的軟件包名(可以指定版本號,不指定則安裝最新版),state指定安裝軟件包的狀態,present表示安裝,absent表示卸載。
1.安裝httpd軟件包
ansible webserver -m yum -a ‘name=httpd‘
2.被控節點查詢
rpm -q httpd
3.卸載httpd軟件包
ansible webserver -m yum -a ‘name=httpd state=absent‘
service模塊
在Ansible中使用service模塊來控制管理服務的運行狀態,其中enabled表示是否開啟自啟動(true或false),name定義服務名稱,state指定服務狀態(started、stoped、restarted)。
1.啟動httpd服務並添加系統管理
ansible webserver -m service -a ‘enable=true name=httpd state=started‘
2.查看httpd啟動狀態信息
ansible webserver -a ‘service httpd status‘
Ansible Ad-Hoc 常用命令