Ansible -常用模塊介紹

目錄

  1. Ansible - 安裝介紹
  2. Ansible -常用模塊介紹
  3. Ansbile - Playbook 使用
  4. Ansible - Roles 使用示例

參考

  1. bilibili馬哥視頻
  2. 運維派教程

基礎配置

[root@localhost ~]# cat /etc/ansible/hosts 
[server]
10.91.156.209

[node]
10.91.156.205


Command模塊

功能

在遠程主機執行命令,此爲默認模塊,可忽略-m選項

注意:此命令不支持 $VARNAME < > | ; & 等,用shell模塊實現

文檔

[root@localhost ~]# ansible-doc -s command
- name: Execute commands on targets
  command:
      argv:                  # Passes the command as a list rather than a string. Use `argv' to avoid quoting values that would otherwise be interpreted incorrectly (for example "user name"). Only the
                               string or the list form can be provided, not both.  One or the other must be provided.
      chdir:                 # Change into this directory before running the command.
      cmd:                   # The command to run.
      creates:               # A filename or (since 2.0) glob pattern. If it already exists, this step *won't* be run.
      free_form:             # The command module takes a free form command to run. There is no actual parameter named 'free form'.
      removes:               # A filename or (since 2.0) glob pattern. If it already exists, this step *will* be run.
      stdin:                 # Set the stdin of the command directly to the specified value.
      stdin_add_newline:     # If set to `yes', append a newline to stdin data.
      strip_empty_ends:      # Strip empty lines from the end of stdout/stderr in result.
      warn:                  # Enable or disable task warnings.

示例

# 切換到/etc目錄下 查看centos-release
[root@localhost ~]# ansible server -m command -a 'chdir=/etc cat centos-release'
10.91.156.209 | CHANGED | rc=0 >>
CentOS Linux release 7.6.1810 (Core) 


Shell模塊

功能

和command相似,用shell執行命令

注意:調用bash執行命令 類似cat /tmp/test.md | awk -F‘|’ ‘{print 1,1,1,2}’ &> /tmp/example.txt這些複雜命令,即使使用shell也可能會失敗,解決辦法:寫到腳本時,copy到遠程,執行,再把需要的結果拉回執行命令的機器

文檔

[root@localhost ~]# ansible-doc -s shell
- name: Execute shell commands on targets
  shell:
      chdir:                 # Change into this directory before running the command.
      cmd:                   # The command to run followed by optional arguments.
      creates:               # A filename, when it already exists, this step will *not* be run.
      executable:            # Change the shell used to execute the command. This expects an absolute path to the executable.
      free_form:             # The shell module takes a free form command to run, as a string. There is no actual parameter named 'free form'. See the examples on how to use this module.
      removes:               # A filename, when it does not exist, this step will *not* be run.
      stdin:                 # Set the stdin of the command directly to the specified value.
      stdin_add_newline:     # Whether to append a newline to stdin data.
      warn:                  # Whether to enable task warnings.

示例

  1. 將shell模塊代替command,設爲默認模塊。編輯/etc/ansible/ansible.cfg文件
# default module name for /usr/bin/ansible
#module_name = command
module_name = shell
  1. 打印主機的hostname。對比發現command模塊輸出有問題,shell可以正常打印
[root@localhost ~]# ansible server -m command -a 'echo $HOSTNAME'
10.91.156.209 | CHANGED | rc=0 >>
$HOSTNAME
[root@localhost ~]# ansible server -m shell -a 'echo $HOSTNAME'
10.91.156.209 | CHANGED | rc=0 >>
node



Script模塊

功能

在遠程主機上運行ansible服務器上的腳本

文檔

[root@localhost ~]# ansible-doc -s script
- name: Runs a local script on a remote node after transferring it
  script:
      chdir:                 # Change into this directory on the remote node before running the script.
      cmd:                   # Path to the local script to run followed by optional arguments.
      creates:               # A filename on the remote node, when it already exists, this step will *not* be run.
      decrypt:               # This option controls the autodecryption of source files using vault.
      executable:            # Name or path of a executable to invoke the script with.
      free_form:             # Path to the local script file followed by optional arguments.
      removes:               # A filename on the remote node, when it does not exist, this step will *not* be run.

示例

[root@localhost ~]# cat test.sh 
#!/bin/sh

echo sever HostName is `hostname`

[root@localhost ~]# ansible server -m script -a 'test.sh'
10.91.156.209 | CHANGED => {
   
           
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 10.91.156.209 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 10.91.156.209 closed."
    ], 
    "stdout": "sever HostName is node\r\n", 
    "stdout_lines": [
        "sever HostName is node"
    ]
}

Copy模塊

功能

ansible服務器主控端複製文件到遠程主機

[root@localhost ~]# ansible-doc -s copy
- name: Copy files to remote locations
  copy:
  .....

示例

#如目標存在,默認覆蓋,此處指定先備份
ansible websrvs -m copy -a “src=/root/test1.sh dest=/tmp/test2.sh    owner=wang  mode=600 backup=yes” 
#指定內容,直接生成目標文件    
ansible websrvs -m copy -a "content='test line1\ntest line2' dest=/tmp/test.txt"
#複製/etc/下的文件,不包括/etc/目錄自身
ansible websrvs -m copy -a “src=/etc/ dest=/backup”


Fetch模塊

功能

從遠程主機提取文件至ansible的主控端,copy相反,目前不支持目錄



File模塊

功能

設置文件屬性

常見參數

參數 含義
group 文件所屬組
mode 文件權限
owner 文件擁有者
path 需要管理的文件路徑(必選)
recurse 遞歸設置(當state取值爲directory)
src 文件的鏈接地址 (只當state值爲link或hard時設置)
state absent:目錄會遞歸刪除,文件會被刪除,符號鏈接會被取消鏈接
directory:創建目錄
hard 創建或修改硬鏈接 link 創建或修改軟鏈接
touch:如果path指定的文件不存在,則創建


示例

[root@localhost ~]# ansible server -m file -a 'path=/root/test.txt state=touch'
10.91.156.209 | CHANGED => {
   
                
    "ansible_facts": {
   
                
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/root/test.txt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}
[root@localhost ~]# ansible server -a 'ls -l'
10.91.156.209 | CHANGED | rc=0 >>
...
-rw-r--r--. 1 root root         0 12月 24 16:51 test.txt



unarchive模塊

功能

解包解壓縮

實現有兩種用法:
1、將ansible主機上的壓縮包傳到遠程主機後解壓縮至特定目錄,設置copy=yes
2、將遠程主機上的某個壓縮包解壓縮到指定路徑下,設置copy=no

常見參數

  • copy:默認爲yes,當copy=yes,拷貝的文件是從ansible主機複製到遠程主機上,如果設置爲copy=no,會在遠程主機上尋找src源文件
  • remote_src:和copy功能一樣且互斥,yes表示在遠程主機,不在ansible主機,no表示文件在ansible主機上
  • src:源路徑,可以是ansible主機上的路徑,也可以是遠程主機上的路徑,如果是遠程主機上的路徑,則需要設置copy=no
  • dest:遠程主機上的目標路徑
  • mode:設置解壓縮後的文件權限

示例

# 創建壓縮包
[root@localhost ~]# tar -czvf testDir.tar.gz testDir/
testDir/
testDir/test.sh
# 將壓縮包拷至遠程主機 /root 目錄下並解壓
[root@localhost ~]# ansible server -m unarchive -a 'src=./testDir.tar.gz dest=/root copy=yes'
10.91.156.209 | CHANGED => {
   
                  
    "ansible_facts": {
   
                  
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "dest": "/root", 
    "extract_results": {
   
                  
        "cmd": [
            "/usr/bin/gtar", 
            "--extract", 
            "-C", 
            "/root", 
            "-z", 
            "-f", 
            "/root/.ansible/tmp/ansible-tmp-1608812600.88-13937-63576563579965/source"
        ], 
        "err": "", 
        "out": "", 
        "rc": 0
    }, 
    "gid": 0, 
    "group": "root", 
    "handler": "TgzArchive", 
    "mode": "0550", 
    "owner": "root", 
    "secontext": "system_u:object_r:admin_home_t:s0", 
    "size": 244, 
    "src": "/root/.ansible/tmp/ansible-tmp-1608812600.88-13937-63576563579965/source", 
    "state": "directory", 
    "uid": 0
}

# 查看遠程主機解壓結果
[root@localhost ~]# ansible server -a 'ls -l /root/testDir/'
10.91.156.209 | CHANGED | rc=0 >>
總用量 4
-rwxr-xr-x. 1 root root 47 12月 24 14:31 test.sh



Archive模塊

功能

打包壓縮

示例

# 將目標主機 /roor/testDir 目錄壓縮至 /root/testDir.tar.gz 權限爲 644
[root@localhost ~]# ansible server -m archive -a 'path=/root/testDir/ dest=/root/testDir.tar.gz format=gz mode=644'
10.91.156.209 | CHANGED => {
   
                    
    "ansible_facts": {
   
                    
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "archived": [
        "/root/testDir/test.sh"
    ], 
    "arcroot": "/root/testDir/", 
    "changed": true, 
    "dest": "/root/testDir.tar.gz", 
    "expanded_exclude_paths": [], 
    "expanded_paths": [
        "/root/testDir/"
    ], 
    "gid": 0, 
    "group": "root", 
    "missing": [], 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 175, 
    "state": "file", 
    "uid": 0
}

[root@localhost ~]# ansible server -a 'ls -l /root'
10.91.156.209 | CHANGED | rc=0 >>
...
-rw-r--r--. 1 root root       175 12月 24 21:48 testDir.tar.gz


Hostname模塊

功能

管理主機名

參數

說明
name (必填)主機名稱
use 更新策略

示例

ansible server -m hostname -a “name=suhw” 


Cron模塊

功能

計劃任務

常用參數

參數 含義
minute
hour 小時
day
month
weekday 作業應該在一週的哪一天運行(週日-週六爲0-6)
job 任務路徑
disabled 是否禁用任務
user 應該修改crontab的特定用戶。如果沒有設置,這個參數默認使用’ root’。

示例

# 腳本內容:輸出當前時間至log文件
[root@localhost ~]# cat /root/date.sh 
#/!/bin/sh
date >> /root/date.log

# 先拷貝到目標主機上
[root@localhost ~]# ansible server -m copy -a "src=./date.sh dest=/root/date.sh mode=755"

# 將腳本每分鐘執行一次
[root@localhost ~]# ansible server -m cron -a "job=/root/date.sh minute=*/1 name=GetDate"
10.91.156.205 | CHANGED => {
   
                        
    "ansible_facts": {
   
                        
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "GetDate"
    ]
}

# 查看目標主機定時任務列表
[root@localhost ~]# ansible server -a 'crontab -l'
10.91.156.205 | CHANGED | rc=0 >>
#Ansible: GetDate
*/1 * * * * /root/date.sh
# 查看執行結果
[root@localhost ~]# ansible server -a 'cat /root/date.log'
10.91.156.205 | CHANGED | rc=0 >>
Fri Dec 25 19:48:01 CST 2020

# 使用 disabled 屬性取消該任務
[root@localhost ~]# ansible server -m cron -a "job=/root/date.sh minute=*/1 name=GetDate disabled=true"
10.91.156.205 | CHANGED => {
   
                        
    "ansible_facts": {
   
                        
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "GetDate"
    ]
}
# 再次查看發現已經註釋取消
[root@localhost ~]# ansible server -a 'crontab -l'
10.91.156.205 | CHANGED | rc=0 >>
#Ansible: GetDate
#*/1 * * * * /root/date.sh



Yum模塊

功能

管理軟件包,只支持RHELCentOSfedora,不支持Ubuntu其它版本

常用參數

參數 含義
name 包名或帶有版本的包說明符,如’ name-1.0’。
state 可選:absent, installed, latest, present, removed


Service模塊

功能

管理服務

常見參數

參數 含義
name 包名或帶有版本的包說明符,如’ name-1.0’。
state 可選:started 、stopped 、 restarted 、 reloaded
enabled 是否開機啓動

示例

# 關閉遠程主機docker服務
[root@localhost ~]# ansible server -m service -a 'name=docker state=stopped'


User模塊

功能

管理用戶

示例

# 添加用戶
[root@localhost ~]# ansible server -m user -a 'name=test01 uid=8888 home=/home/test01 group=root'
...
[root@localhost ~]# ansible server -a 'getent passwd test01'
10.91.156.205 | CHANGED | rc=0 >>
test01:x:8888:0::/home/test01:/bin/bash

# 刪除 test01 用戶並刪除家目錄
[root@localhost ~]# ansible server -m user -a 'name=test01 state=absent remove=yes'



Group模塊

功能

管理用戶組

示例

#創建組
ansible websrvs -m group  -a 'name=nginx gid=88 system=yes'
#刪除組
ansible websrvs -m group  -a 'name=nginx state=absent'


Lineinfile模塊

功能

相當於sed,可以修改文件內容。

ansible在使用sed進行替換時,經常會遇到需要轉義的問題,而且ansible在遇到特殊符號進行替換時,存在問題,無法正常進行替換 。其實在ansible自身提供了兩個模塊:lineinfile模塊和replace模塊,可以方便的進行替換

示例

ansible all -m   lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=enforcing'"
ansible all -m lineinfile  -a 'dest=/etc/fstab state=absent regexp="^#"'


Replace模塊

功能

該模塊有點類似於sed命令,主要也是基於正則進行匹配和替換

示例

ansible all -m replace -a "path=/etc/fstab regexp='^(UUID.*)' replace='#\1'"  
ansible all -m replace -a "path=/etc/fstab regexp='^#(.*)' replace='\1'"


Setup模塊

功能

setup 模塊來收集主機的系統信息,這些 facts 信息可以直接以變量的形式使用,但是如果主機較多,會影響執行速度,可以使用

gather_facts: no

來禁止 Ansible 收集 facts 信息

常見參數

參數 說明
filter 按照key過濾輸出結果,支持通配符
gather_timeout 設置收集數據的超時時間

示例

[root@localhost ~]# ansible server -m setup -a 'filter=ansible_virtualization_type'
10.91.156.205 | SUCCESS => {
   
                                      
    "ansible_facts": {
   
                                      
        "ansible_virtualization_type": "kvm", 
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false
}

可不加filter獲取全部信息後,找到自己所需的字段,再通過filter方式獲取指定字段



















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章