Ansible--常用模塊使用


ansible命令解釋

通過ansible命令執⾏的任務稱為ad-hoc命令(任務),其實它是相對playbook⽽⾔的。通常,命令⾏⽤來實現ansible的批量管理功能,playbook⽤來實現批量⾃動化功能。
執行:ansible --help 查看具體的使用幫助
幫助參數詳細說明:

----------------------------------------------------------------------------------------------------------------
[普通選項]
-a MODULE_ARGS
--args=MODULE_ARGS
傳遞參數給模塊

--ask-vault-pass
詢問vault的密碼

-B SECONDS
--background=SECONDS
異步后台⽅式執⾏任務,並在指定的秒數后超時,超時會殺掉任務的進程。默認是同步,即保持長連接,它會等待
所有執⾏完畢(即阻塞模式)。但有時候是沒必要這樣的,⽐如某些命令的執⾏時間⽐ssh的超時時間還長。如果
不指定超時秒數,將以同步⽅式運⾏任務

-P POLL_INTERVAL
--poll=POLL_INTERVAL
異步模式下輪詢任務的時間間隔,默認60秒

-C
--check
不對遠程主機做一些改變,而是預測某些可能發生的改變(檢查功能)

-e EXTRA_VARS
--extra-vars=EXTRA_VARS
配置額外的配置變量(key=value或者YAML/JSON格式)

-f FORKS
--forks=FORKS
指定並行處理的進程數量,默認5個

-h
--help
顯示幫助信息

-i INVENTORY
--inventory-file=INVENTORY
指定inventory⽂件,多個⽂件使⽤逗號分隔。默認為/etc/ansible/hosts

-l SUBSET
--limit=SECONDS
使⽤額外的匹配模式來篩選⽬標主機列表。
此處的匹配模式是在已有匹配模式下進⾏的,所以是更嚴格的篩選。例如指定了主機組的情況下,使⽤-l選項從中只選⼀台主機進⾏控制

--list-hosts
不會執行任何操作,而是列出匹配到的主機列表

-m MODULE_NAME
--module-name=MODULE_NAME
指定要執行的模塊名,默認的模塊為"command"

--new-vault-password-file=NEW_VAULT_PASSWORD_FILE
new vault password f ile f or rekey

-o
--one-line
簡化輸出(一行輸出模式)

--output-OUTPUT_FILE
output f ile name f or encrypt or decrypt; use - f or stdout

--syntax-check
檢查playbook的語法,不會執行

-t TREE
--tree=TREE
記錄輸出到此⽬錄中(測試時以每個host名如IP地址為⽂件名記錄,結果記錄到對應的⽂件中)。
此選項在ansible巨慢的時候(如瞬間應該返回的命令還需要10多秒才完成)有奇⽤,或者將ansible的結果重
定向到某個⽂件中也能解決,為什么如此,我也不明⽩(表⾯看來和輸出⽅式有關系),多次親測有效。

--vault-password-file=VAULT_PASSWORD_FILE
指定vault密碼文件

-v
--verbose
輸出詳細信息,-vvv和-vvvv輸出更詳細的信息

--version
顯示ansbile的版本

----------------------------------------------------------------------------------------------------------------
[以下是連接選項,⽤於控制誰以及如何連接主機]
-k
--ask-pass
詢問連接時的密碼

--private-key=KEY_FILE
--key-file=KEY_FILE
使用文件來認證SSH連接的過程

-u REMOTE_USER
--user=REMOTE_USER
使用指定的用戶名進行連接

-c CINNECTION
--connection=CINNECTION
連接類型,默認為ssh。paramiko (SSH), ssh, winrm and local. local is mostly usef ul f or crontab or kickstarts.

-T TIMEOUT
--time=TIMEOUT
連接的超時時間,單位為秒,默認10秒

--ssh-common-args=SSH_COMMON_ARGS
指定傳遞給sftp/scp/ssh等⼯具的通⽤額外參數

--sftp-extra-args=SFTP_EXTRA_ARGS
指定只傳遞給sftp的額外參數,如-f

--scp-extra-args=SCP_EXTRA_ARGS
指定只傳遞給scp的額外參數,如-l

--ssh-extra-args=SSH_EXTRA_ARGS
指定只傳遞給ssh的額外參數,如-R

----------------------------------------------------------------------------------------------------------------
[以下是權限控制選項:控制在⽬標主機上以什么⾝份和權限運⾏任務]
-s
--sudo
為運行ansible命令的用戶提升權限為sudo_user的權限,此命令已經報廢,使用become代替

-u SUDO_USER
--sudo-user=SUDO_USER
期望的sudo_user,默認為root,已報廢,使用become代替

-S
--su
使⽤su的⽅式執⾏操作,已廢棄,使⽤become替代

-R SU_USER
--su-user=SU_USER
使⽤此user的su執⾏操作,默認為root,已廢棄,使⽤become替代

-b
--become
使用become的方式升級權限

--become-method=BECOME_METHOD
指定提升權限的方式,可選以下⼏種:sudo/su/pbrun/pf exec/doas/dzdo/ksu/runas值

--become-user=BECOME_USER
要提升為哪個user的權限,默認為root

--ask-sudo-pass
詢問sudo密碼,已廢棄,使⽤become替代

--ask-su-pass
詢問su的密碼,已廢棄,使⽤become替代

-K
--ask-become-pass
詢問become提升權限時的密碼

----------------------------------------------------------------------------------------------------------------

常用模塊

ping 模塊

用途:嘗試連接被控制端主機,成功返回pong(ping--pong是一對的)
使用方法:

[root@ansible ~]# ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong' on success
  ping:
      data:                  # Data to return for the `ping' return value. If this parameter is set to `crash', the module will cause an exception.

 示例:

[root@ansible ~]# ansible all -m ping
192.168.192.131 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.192.130 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.192.129 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.192.128 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
參數all代表被控制端的所有主機

command 模塊

用途:默認ansible使⽤的模塊是command,即可以執⾏⼀些shell命令
使用方法:

[root@ansible ~]# ansible-doc -s command
- name: Executes a command on a remote node
  command:
      argv:                  # 允許用戶以列表和字符串的形式提供命令,不能同時使用,也不必須提供其中一種
      chdir:                 # 在執行命令之前,先cd到指定的目錄下
      creates:               # 用於判斷命令是否要執行,如果指定的文件存在(可以使用通配符)存在,則不執行
      free_form:             # 默認的選項,這里只是顯示,實際上是沒有的
      removes:               # 用於判斷命令是否要執行,如果指定的文件存在(可以使用通配符)不存在,則不執行
      stdin:                 # 將命令的stdin直接設置為指定值
      warn:                  # 設置command的警告信息(在/etc/ansible/ansible.cfg中有配置項)

示例:

不加參數執行
[root@ansible ~]# ansible all -a "ls"
192.168.192.130 | CHANGED | rc=0 >>
anaconda-ks.cfg
haha.txt

192.168.192.129 | CHANGED | rc=0 >>
anaconda-ks.cfg
haha.txt
rc.local

chdir參數
[root@ansible ~]# ansible all -a "chdir=/etc/ssh ls"              
192.168.192.129 | CHANGED | rc=0 >>
moduli
ssh_config
sshd_config
ssh_host_ecdsa_key
ssh_host_ecdsa_key.pub
ssh_host_ed25519_key
ssh_host_ed25519_key.pub
ssh_host_rsa_key
ssh_host_rsa_key.pub

192.168.192.130 | CHANGED | rc=0 >>
moduli
ssh_config
sshd_config
ssh_host_ecdsa_key
ssh_host_ecdsa_key.pub
ssh_host_ed25519_key
ssh_host_ed25519_key.pub
ssh_host_rsa_key
ssh_host_rsa_key.pub

creates參數
[root@ansible ~]# ansible all -a "touch haha.txt creates=/root/haha.txt"         
192.168.192.129 | SUCCESS | rc=0 >>
skipped, since /root/haha.txt exists

192.168.192.130 | SUCCESS | rc=0 >>
skipped, since /root/haha.txt exists

removes參數
[root@ansible ~]# ansible all -a "touch haha1.txt removes=/root/haha1.txt"
192.168.192.130 | SUCCESS | rc=0 >>
skipped, since /root/haha1.txt does not exist

192.168.192.129 | SUCCESS | rc=0 >>
skipped, since /root/haha1.txt does not exist

溫馨提示:
command不能解析變量(如$HOME)和某些操作符("<", ">", "|", ";"以及"&"),所以明確要使⽤這些不可解析的操作符時,使⽤shell模塊來代替command

shell 模塊

用途:shell和command的⽤法基本⼀樣,實際上shell模塊執⾏命令的⽅式是在遠程使⽤/bin/sh來執⾏的,如/bin/sh ping
使用方法:

[root@ansible ~]# ansible-doc -s shell
- name: Execute commands in nodes.
  shell:
      chdir:                 # 在執行命令之前,先cd到指定的目錄下
      creates:               # 用於判斷命令是否要執行,如果指定的文件存在(可以使用通配符)存在,則不執行
      executable:            # 不再使⽤默認的/bin/sh解析並執⾏命令,⽽是使⽤此處指定的命令解析(例如使⽤expect解析expect腳本。必須為絕對路徑)
      free_form:             # 默認的選項,這里只是顯示,實際上是沒有的
      removes:               # 用於判斷命令是否要執行,如果指定的文件存在(可以使用通配符)不存在,則不執行
      stdin:                 # 將命令的stdin直接設置為指定值
      warn:                  # 設置command的警告信息(在/etc/ansible/ansible.cfg中有配置項)

示例:

不加參數執行
[root@ansible ~]# ansible all -m shell -a "ls"
192.168.192.129 | CHANGED | rc=0 >>
anaconda-ks.cfg
haha.txt
rc.local

192.168.192.130 | CHANGED | rc=0 >>
anaconda-ks.cfg
haha.txt

chdir參數
[root@ansible ~]# ansible all -m shell -a "chdir=/etc/ ls | grep ssh" 
192.168.192.129 | CHANGED | rc=0 >>
ssh

192.168.192.130 | CHANGED | rc=0 >>
ssh

creates參數
[root@ansible ~]# ansible all -a "touch haha.txt creates=/root/haha.txt"         
192.168.192.129 | SUCCESS | rc=0 >>
skipped, since /root/haha.txt exists

192.168.192.130 | SUCCESS | rc=0 >>
skipped, since /root/haha.txt exists

removes參數
[root@ansible ~]# ansible all -a "touch haha1.txt removes=/root/haha1.txt"
192.168.192.130 | SUCCESS | rc=0 >>
skipped, since /root/haha1.txt does not exist

192.168.192.129 | SUCCESS | rc=0 >>
skipped, since /root/haha1.txt does not exist

使用在command下不能用的操作符
[root@ansible ~]# ansible all -m shell -a "echo '2131' > haha.txt && cat haha.txt"
192.168.192.130 | CHANGED | rc=0 >>
2131

192.168.192.129 | CHANGED | rc=0 >>
2131

注意:
在ansible中使⽤shell或command模塊⼀定要注意,它們默認不滿⾜冪等性,很多操作會重復執⾏,但有些操作是不允許重復執⾏的。
例如mysql的初始化命令mysql_install_db,它只能在第⼀次配置的過程中初始化⼀次,其他任何時候如⾮需要則不允許執⾏。
解決方式:
這時候要實現冪等性,可以通過模塊的creates和removes選項進⾏判斷,但⽆論如何,在執⾏這兩個模塊的時候都需要考慮要執⾏的命令是否應該實現冪等性

script 模塊

用途:script模塊用於控制遠程主機執行腳本,在執行腳本前,ansible會將本地腳本傳輸到遠程主機,然后在執行,在執行腳本的時候,其采用的是遠程主機上的shell環境
使用方法:

[root@ansible ~]# ansible-doc -s script
- name: Runs a local script on a remote node after transferring it
  script:
      chdir:                 # 在遠程執⾏腳本前先切換到此⽬錄下
      creates:               # 當此⽂件存在時,不執⾏腳本。可⽤於實現冪等性。
      decrypt:               # 此選項使用vault控制源文件的自動解密(對使用ansible-vault encrypt 文件名.yml 進行加密的文件解密)
      executable:            # 不再使⽤默認的/bin/sh解析並執⾏命令,⽽是使⽤此處指定的命令解析(例如使⽤expect解析expect腳本。必須為絕對路徑)
      free_form:             # 本地待執⾏的腳本路徑、選項、參數。之所以稱為free_form,是因為它是腳本名+選項+參數。
      removes:               # 當此⽂件不存在時,不執⾏腳本。可⽤於實現冪等性。

示例:

新建一個腳本在ansible管理主機上
[root@ansible ~]# cat test.sh 
#!/bin/bash
echo "Test script module"

不加參數執行
[root@ansible ~]# ansible all -m script -a "test.sh"
192.168.192.130 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.192.130 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.192.130 closed."
    ], 
    "stdout": "Test script module\r\n", 
    "stdout_lines": [
        "Test script module"
    ]
}
192.168.192.129 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.192.129 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.192.129 closed."
    ], 
    "stdout": "Test script module\r\n", 
    "stdout_lines": [
        "Test script module"
    ]
}

chdir參數
[root@ansible ~]# ansible all -m script -a "chdir=/etc/ ./test.sh"
192.168.192.130 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.192.130 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.192.130 closed."
    ], 
    "stdout": "Test script module\r\n", 
    "stdout_lines": [
        "Test script module"
    ]
}
192.168.192.129 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.192.129 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.192.129 closed."
    ], 
    "stdout": "Test script module\r\n", 
    "stdout_lines": [
        "Test script module"
    ]
}

其他的參數的使用方法都和shell的參數一樣,這里就不列舉了!!!

copy 模塊

用途:copy模塊的作用就是拷貝文件,將 ansible 管理主機上的文件拷貝到遠程主機中
使用方法:

[root@ansible ~]# ansible-doc -s copy
- name: Copies files to remote locations
  copy:
      backup:                # 拷貝的同時也創建⼀個包含時間戳信息的備份⽂件,默認為no,可以指定為backup=yes做文件備份
      content:               # 當用content代替src參數的時候,可以把content指定的內容直接寫到一個文件
      decrypt:               # 此選項使用vault控制源文件的自動解密(對使用ansible-vault encrypt 文件名.yml 進行加密的文件解密)
      dest:                  # ⽬標路徑,只能是絕對路徑,如果拷貝的⽂件是⽬錄,則⽬標路徑必須也是⽬錄
      directory_mode:        # 當對⽬錄做遞歸拷貝時,設置了directory_mode將會使得只拷貝新建⽂件舊⽂件不會被拷貝。默認未設置.
      follow:                # 是否追蹤到鏈接的源⽂件(follow=yes|on)
      force:                 # 設置為yes(默認)時,將覆蓋遠程同名⽂件。設置為no時,忽略同名⽂件的拷貝。
      group:                 # 指定文件拷貝到遠程主機后的屬組,但是遠程主機上必須有對應的組,否則會報錯
      local_follow:          # 是否遵循本地機器中的文件系統鏈接(local_follow=yes|on)
      mode:                  # 設置遠程⽂件的權限。使⽤數值表⽰時不能省略第⼀位,如0644。也可以使⽤'u+rwx'或'u=rw,g=r,o=r'等⽅式設置
      owner:                 # 設置遠程⽂件的所有者
      remote_src:            # 如果yes它會從目標機上搜索src文件(remote_src=yes|on)
      src:                   # 拷貝本地源⽂件到遠程,可使⽤絕對路徑或相對路徑。如果路徑是⽬錄,且⽬錄后加了斜杠"/",則只會拷貝⽬錄中的內容到遠程,如果⽬錄后不加斜杠,則拷貝⽬錄本⾝和⽬錄內的內容到遠程
      unsafe_writes:         # 是否以不安全的方式進行,可能導致數據損壞(unsafe_writes=yes|on)
      validate:              # 復制前是否檢驗需要復制目的地的路徑

示例:

這里做一些常用選項的示例

1)不加參數執行(將本地主機上的/root/ansible/ansible-copy-module.sh拷貝到被控端主機/root/ansible/下)
[root@ansible ansible]# ansible all -m copy -a 'src=/root/ansible/ansible-copy-module.sh dest=/root/ansible'     
192.168.192.129 | CHANGED => {
    "changed": true, 
    "checksum": "9e4af9ed468fc3e4bcac3dc3022bb30a9cb85e01", 
    "dest": "/root/ansible", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "10b9ac730043f12b56be19b32746abff", 
    "mode": "0644", 
    "owner": "root", 
    "size": 28, 
    "src": "/root/.ansible/tmp/ansible-tmp-1545791911.48-195372218323444/source", 
    "state": "file", 
    "uid": 0
}
在管理主機上對ansible-copy-module.sh進行修改,然后在執行下面的拷貝前備份

2)backup參數:將本地主機上的/root/ansible/ansible-copy-module.sh拷貝到被控端主機/root/ansible/下(拷貝前備份,這里的備份是在被控制端進行的)
[root@ansible ansible]# ansible all -m copy -a 'src=/root/ansible/ansible-copy-module.sh dest=/root/ansible backup=yes'
192.168.192.129 | CHANGED => {
    "backup_file": "/root/ansible.4061.2018-12-26@10:40:11~", 
    "changed": true, 
    "checksum": "ac0d55a766b74d8e24a4b028fe5b162a1f026522", 
    "dest": "/root/ansible", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "f4cb7616d498638b01f81d164ebc64e4", 
    "mode": "0644", 
    "owner": "root", 
    "size": 42, 
    "src": "/root/.ansible/tmp/ansible-tmp-1545792010.33-171875446599908/source", 
    "state": "file", 
    "uid": 0
}
在上面可以看到backup_file這個參數,后面就是備份的路徑(在被控制端主機上查看)

3)owner、group、mode參數
拷貝文件對文件權限和屬主屬組進行改變
[root@ansible ansible]# ansible all -m copy -a 'src=/root/ansible/ansible-copy-module.sh dest=/root/ansible/ owner=sshd group=sshd mode=0644'
192.168.192.129 | CHANGED => {
    "changed": true, 
    "checksum": "ac0d55a766b74d8e24a4b028fe5b162a1f026522", 
    "dest": "/root/ansible/ansible-copy-module.sh", 
    "gid": 74, 
    "group": "sshd", 
    "md5sum": "f4cb7616d498638b01f81d164ebc64e4", 
    "mode": "0644", 
    "owner": "sshd", 
    "size": 42, 
    "src": "/root/.ansible/tmp/ansible-tmp-1545792376.05-245560382140658/source", 
    "state": "file", 
    "uid": 74
}
查看權限
[root@ansible ansible]# ansible all -m shell -a "ls -l /root/ansible/ansible-copy-module.sh"
192.168.192.129 | CHANGED | rc=0 >>
-rw-r--r-- 1 sshd sshd 42 Dec 26 10:46 /root/ansible/ansible-copy-module.sh

4)content參數
將內容直接寫到被控端指定的文件中
[root@ansible ansible]# ansible all -m copy -a "content='my name is zhujingzhi' dest=/root/ansible/my.txt"
192.168.192.129 | CHANGED => {
    "changed": true, 
    "checksum": "4f138d7333fe41ecc4cd8bb08a55c92b9952a65f", 
    "dest": "/root/ansible/my.txt", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "9a6e5e1b3273e1ba2dbec06cc4fd8a0c", 
    "mode": "0644", 
    "owner": "root", 
    "size": 21, 
    "src": "/root/.ansible/tmp/ansible-tmp-1545792591.83-125843029198237/source", 
    "state": "file", 
    "uid": 0
}
查看文件
[root@ansible ansible]# ansible all -m shell -a "cat /root/ansible/my.txt"
192.168.192.129 | CHANGED | rc=0 >>
my name is zhujingzhi!

5)force參數
是否忽略遠程同名文件(默認yes)
[root@ansible ansible]# ansible all -m copy -a "src=/root/ansible/my.txt dest=/root/ansible/my.txt force=no"        
192.168.192.129 | SUCCESS => {
    "changed": false, 
    "dest": "/root/ansible/my.txt", 
    "src": "/root/ansible/my.txt"
}

template 模塊

用途:template模塊⽤法和copy模塊⽤法基本⼀致,它主要⽤於復制配置⽂件
使用方法:

[root@ansible ~]# ansible-doc -s template
- name: Templates a file out to a remote server
  template:
      backup:                # 拷貝的同時也創建⼀個包含時間戳信息的備份⽂件,默認為no
      block_end_string:      # 標記塊結束的字符串.
      block_start_string:    # 標記塊開頭的字符串.
      dest:                  # 遠程節點上的絕對路徑,用於放置template文件
      follow:                # 是否追蹤到鏈接的源⽂件(follow=yes|on)
      force:                 # 設置為yes (默認)時,將覆蓋遠程同名⽂件。設置為no時,忽略同名⽂件的拷貝
      group:                 # 設置遠程⽂件的所屬組
      lstrip_blocks:         # 如果將其設置為真正的前導空格,那么制表符將從行開始剝離到塊。將此選項設置為True需要Jinja2版本>=2.7
      mode:                  # 設置遠程⽂件的權限。使⽤數值表⽰時不能省略第⼀位,如0644。也可以使⽤'u+rwx' or 'u=rw,g=r,o=r'等⽅式設置
      newline_sequence:      # 指定用於模板文件的換行序列.
      output_encoding:       # 改變dest指定模板文件的編碼,默認為utf8.
      owner:                 # 設置遠程⽂件的所有者
      src:                   # ansible控制器上Jinja2格式的模板所在位置,可以是相對或絕對路徑.
      trim_blocks:           # 如果將此設置為True,則刪除塊后的第一個換行(塊,而不是變量標記!).
      unsafe_writes:         # 是否以不安全的方式進行,可能導致數據損壞(unsafe_writes=yes|on)
      validate:              # 在復制到⽬標主機后但放到⽬標位置之前,執⾏此選項指定的命令,⼀般⽤於檢查配置⽂件語法,語法正確則保存到⽬標位置,如果要引⽤⽬標⽂件名,則使⽤%s
      variable_end_string:   # 打印語句結尾的字符串.
      variable_start_string: # 打印語句開頭的字符串

 示例:

[root@ansible ~]# ansible all -m template -a "src=/etc/nginx/nginx.conf dest=/etc/nginx/nginx.conf mode=0770 owner=root group=root backup=yes validate='nginx -t -c %s'"
192.168.192.129 | CHANGED => {
    "backup_file": "/etc/nginx/nginx.conf.6179.2018-12-26@11:32:00~", 
    "changed": true, 
    "checksum": "ccc2942c816b4caae696e39dd0b079f97df6cd1a", 
    "dest": "/etc/nginx/nginx.conf", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "96f714838028dea291bcd59b1447e46f", 
    "mode": "0770", 
    "owner": "root", 
    "size": 2468, 
    "src": "/root/.ansible/tmp/ansible-tmp-1545795118.58-264966235377818/source", 
    "state": "file", 
    "uid": 0
}
上的示例我測試的是nginx的配置文件,所以要提前安裝nginx
[root@ansible ~]# ansible all -m shell -a "yum -y install epel-release && yum -y install nginx"

fetch 模塊

用途:從被控遠端機器上拉取文件(和COPY模塊整好相反)
使用方法:

使用方法:
[root@ansible ~]# ansible-doc -s fetch
- name: Fetches a file from remote nodes
  fetch:
      dest:                  # 本地存儲拉取⽂件的⽬錄。例如dest=/data,src=/etc/fstab,遠程主機名host.exp.com,則保存的路徑為/data/host.exp.com/etc/fstab。
      fail_on_missing:       # 當設置為yes時,如果拉取的源⽂件不存在,則此任務失敗。默認為no.
      flat:                  # 改變拉取后的路徑存儲⽅式。如果設置為yes,且當dest以"/"結尾時,將直接把源⽂件的basename存儲在dest下。顯然,應該考慮多個主機拉取時的⽂件覆蓋情況。
      src:                   # 遠程主機上的源⽂件。只能是⽂件,不⽀持⽬錄。在未來的版本中可能會⽀持⽬錄遞歸拉取.
      validate_checksum:     # fetch到⽂件后,檢查其md5和源⽂件是否相同

 示例:

1) src、dest參數
拉取后的存儲路徑:/root/ansible/192.168.192.129/root/ansible/fetch.sh
[root@ansible ~]# ansible all -m fetch -a "src=/root/ansible/fetch.sh dest=/root/ansible/"     
192.168.192.129 | CHANGED => {
    "changed": true, 
    "checksum": "1d4eef5c77eacf079216ac851ebdde39c7c735ce", 
    "dest": "/root/ansible/192.168.192.129/root/ansible/fetch.sh", 
    "md5sum": "2442ddbfcb138987feedad26be9eccd8", 
    "remote_checksum": "1d4eef5c77eacf079216ac851ebdde39c7c735ce", 
    "remote_md5sum": null
}
2) flat參數
拉取后的存儲路徑:/root/ansible/fetch.sh
[root@ansible ~]# ansible all -m fetch -a "src=/root/ansible/fetch.sh dest=/root/ansible/ flat=yes"
192.168.192.129 | CHANGED => {
    "changed": true, 
    "checksum": "1d4eef5c77eacf079216ac851ebdde39c7c735ce", 
    "dest": "/root/ansible/fetch.sh", 
    "md5sum": "2442ddbfcb138987feedad26be9eccd8", 
    "remote_checksum": "1d4eef5c77eacf079216ac851ebdde39c7c735ce", 
    "remote_md5sum": null
}

3) 使用變量的方式按照變量值存儲
拉取后的存儲路徑:/root/ansible/192.168.192.129/fetch.sh
[root@ansible ~]# ansible all -m fetch -a "src=/root/ansible/fetch.sh dest=/root/ansible/{{inventory_hostname}}/ flat=yes"
192.168.192.129 | CHANGED => {
    "changed": true, 
    "checksum": "1d4eef5c77eacf079216ac851ebdde39c7c735ce", 
    "dest": "/root/ansible/192.168.192.129/fetch.sh", 
    "md5sum": "2442ddbfcb138987feedad26be9eccd8", 
    "remote_checksum": "1d4eef5c77eacf079216ac851ebdde39c7c735ce", 
    "remote_md5sum": null
}
{{inventory_hostname}}表示:192.168.192.129

 

file 模塊

用途:管理文件、目錄的屬性,也可以創建文件或者目錄
使用方法:

在file模塊中state參數是十分重要的

[root@ansible ~]# ansible-doc -s file
- name: Sets attributes of files
  file:
      follow:                       # 是否遵循目的機器中的文件系統鏈接(可選值為:yes|on)
      force:                        # 當state=link的時候,可配合此參數強制創建鏈接文件,當force=yes時,表示強制創建鏈接文件
                                    # 不過強制創建鏈接文件分為三種情況。情況一:當要創建的鏈接文件指向的源文件並不存在時,使用此參數,可以先強制創建出鏈接文件。
                                    # 情況二:當要創建鏈接文件的目錄中已經存在與鏈接文件同名的文件時,將force設置為yes,會將同名文件覆蓋為鏈接文件,相當於刪除同名文件,創建鏈接文件。
                                    # 情況三:當要創建鏈接文件的目錄中已經存在與鏈接文件同名的文件,並且鏈接文件指向的源文件也不存在,這時會強制替換同名文件為鏈接文件
      group:                        # 設置遠程⽂件的所屬組
      mode:                         # 設置遠程⽂件的權限。使⽤數值表⽰時不能省略第⼀位,如0644。也可以使⽤
      owner:                        # 設置遠程⽂件的所有者
      path:                         # 必須的參數,用於指定要操作的文件或者目錄
      recurse:                      # 當要操作的文件為目錄,將recurse設置為yes,可以遞歸的修改目錄中的文件屬性
      src:                          # 當state設置為link或者hard時,表示我們想要創建一個軟鏈接或者硬鏈接,所以,我們必須指明軟鏈接或硬鏈鏈接的哪個文件,通過src參數即可指定鏈接源
      state:                        # 此參數非常靈活,其對應的值需要根據情況設定。比如,我們想要在遠程主機上創建/testdir/a/b目錄,那么則需要設置path=/testdir/a/b,
                                    # 但是,我們無法從”/testdir/a/b“這個路徑看出b是一個文件還是一個目錄,ansible也同樣無法單單從一個字符串就知道你要創建文件還是目錄,所以,我們需要通過state參數進行說明
                                    # state=directory:表示創建目錄,如果path指定的不存在則被創建
                                    # state=touch:創建文件
                                    # state=link:創建軟鏈接文件
                                    # state=hard:創建硬鏈接文件
                                    # state=absent:刪除文件(刪除時不用區分目標是文件、目錄、還是鏈接)
      unsafe_writes:                # 是否以不安全的方式進行,可能導致數據損壞(unsafe_writes=yes|on)

 示例:

1)state=directory參數(創建目錄)
[root@ansible ~]# ansible all -m file -a "path=/root/file state=directory owner=root group=root mode=0777"   
192.168.192.129 | CHANGED => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "path": "/root/file", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}
查看結果(很明顯創建了一個file的目錄)
[root@ansible ~]# ansible all -m shell -a "ls -l /root/ | grep file"
192.168.192.129 | CHANGED | rc=0 >>
drwxrwxrwx  2 root root    6 Dec 26 14:33 file

2)state=touch參數(創建文件)
[root@ansible ~]# ansible all -m file -a "path=/root/file/file.txt state=touch owner=root group=root mode=0655"
192.168.192.129 | CHANGED => {
    "changed": true, 
    "dest": "/root/file/file.txt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0655", 
    "owner": "root", 
    "size": 0, 
    "state": "file", 
    "uid": 0
}
查看結果(很明顯創建了一個file的文件)
[root@ansible ~]# ansible all -m shell -a "ls -l /root/file/file.txt"
192.168.192.129 | CHANGED | rc=0 >>
-rw-r-xr-x 1 root root 0 Dec 26 14:36 /root/file/file.txt

3)state=link(創建軟鏈接文件)
[root@ansible ~]# ansible all -m file -a "path=/root/file/file.txt src=/root/ansible/my.txt state=link owner=root group=root mode=0655" 
192.168.192.129 | CHANGED => {
    "changed": true, 
    "dest": "/root/file/file.txt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 20, 
    "src": "/root/ansible/my.txt", 
    "state": "link", 
    "uid": 0
}
查看結果(已經發現/root/file/file.txt已經鏈接到/root/ansible/my.txt)
[root@ansible ~]# ansible all -m shell -a "ls -l /root/file/"    
192.168.192.129 | CHANGED | rc=0 >>
total 0
lrwxrwxrwx 1 root root 20 Dec 26 14:46 file.txt -> /root/ansible/my.txt

溫馨提示:這里需要注意的是src指定的鏈接文件要存在,如果不存在也想先創建的話要加上force=yes參數

4)state=hard(創建硬鏈接文件)
[root@ansible ~]# ansible all -m file -a "path=/root/file/file1.txt src=/root/haha.txt state=hard owner=root group=root mode=0655" 
192.168.192.129 | CHANGED => {
    "changed": true, 
    "dest": "/root/file/file1.txt", 
    "gid": 0, 
    "group": "root", 
    "mode": "0655", 
    "owner": "root", 
    "size": 5, 
    "src": "/root/haha.txt", 
    "state": "hard", 
    "uid": 0
}
查看結果(查看兩個文件的內容是否一樣)
[root@ansible ~]# ansible all -m shell -a "cat /root/file/file1.txt && cat /root/haha.txt"
192.168.192.129 | CHANGED | rc=0 >>
2131
2131

5)state=absent(刪除文件)
[root@ansible ~]# ansible all -m file -a "path=/root/file/file1.txt state=absent"
192.168.192.129 | CHANGED => {
    "changed": true, 
    "path": "/root/file/file1.txt", 
    "state": "absent"
}
查看結果(/root/file/file1.txt已經被刪除)
[root@ansible ~]# ansible all -m shell -a "ls -l /root/file"
192.168.192.129 | CHANGED | rc=0 >>
total 0
lrwxrwxrwx 1 root root 20 Dec 26 14:46 file.txt -> /root/ansible/my.txt

6)force參數
在創建軟鏈接時src指定的文件不存在,可以添加force=yes參數,先創建軟鏈接
/root/ansible/file.txt 不存在
[root@ansible ~]# ansible all -m file -a "path=/root/file/file1.txt src=/root/ansible/file.txt state=link owner=root group=root mode=0655 force=yes"
 [WARNING]: Cannot set fs attributes on a non-existent symlink target. follow should be set to False to avoid this.
 # 這個警告可以使用follow=no參數取消掉

192.168.192.129 | CHANGED => {
    "changed": true, 
    "dest": "/root/file/file1.txt", 
    "src": "/root/ansible/file.txt", 
    "state": "absent"
}
查看結果(雖然/root/ansible/file.txt文件不存在,但是軟鏈接也是創建成功的)
[root@ansible ~]# ansible all -m shell -a "ls -l /root/file/"         
192.168.192.129 | CHANGED | rc=0 >>
total 0
lrwxrwxrwx 1 root root 22 Dec 26 14:59 file1.txt -> /root/ansible/file.txt

rsync 模塊

在ansible中rsync模塊的名字叫synchronize

用途:synchronize模塊⽤於實現rsync的簡單版常⽤功能,它⽆法實現完整版的rsync,畢竟rsync功能太多太細致。如果要使⽤rsync,還是應該使⽤command或shell模塊來調⽤rsync命令
使用方法:

使用方法:
[root@ansible ~]# ansible-doc -s synchronize
- name: A wrapper around rsync to make common tasks in your playbooks quick and easy.
  synchronize:
      archive:               # 等價於rsync的"-a"選項,即使⽤歸檔模式。它等價於rsync的"-rtopgDl"選項。值為yes/no.
      checksum:              # 是否對文件進行校驗(在archive(歸檔)開啟的時候checksum也是開啟的).
      compress:              # 是否開啟壓縮,默認是開啟的.
      copy_links:            # 同步的時候是否復制符號鏈接.
      delete:                # 刪除源中沒有但是目標存在的文件,使兩邊的數據內容一致,已推送為主需要設置參數recursive=yes結合使用.
      dest:                  # 目標文件及目錄
      dest_port:             # 目標主機上的ssh的端口
      dirs:                  # 不使用遞歸的方式傳送目錄
      existing_only:         # receiver(接收端)沒有的文件不同步,但仍會傳輸,只是臨時文件重組后不重命名而已.
      group:                 # 保留所屬組屬性
      link_dest:             # 在rsync期間向硬鏈接添加目標
      links:                 # 拷貝鏈接文件自身
      mode:                  # 指定推(push)還是拉(pull)的傳輸模式
      owner:                 # 保留所有者屬性
      partial:               # 等價於'--partial'選項,默認rsync在傳輸中斷時會刪除傳輸了一半的文件,指定該選項將保留這個部分不完整的文件,使得下次傳輸時可以直接從未完成的數據塊開始傳輸.
      perms:                 # 保留權限屬性.
      private_key:           # 指定基於ssh的rsync連接的私鑰 (例如 `~/.ssh/id_rsa')
      recursive:             # 遞歸到目錄中的文件.
      rsync_opts:            # 指定額外的rsync選項,使用數組的方式傳遞這些選項.
      rsync_path:            # 等價於'--rsync-path'選項,目的是啟動遠程rsync,例如可以指定[--rsync-path=rsync],甚至[--rsync-path=cd /tmp/c && rsync],當不指定rsync的路徑時,默認是/usr/bin/rsync.
      rsync_timeout:         # 指定rsync在多久時間內沒有數據傳輸就超時退出.
      set_remote_user:       # 主要用於/etc/ansible/hosts中定義或默認使用的用戶與rsync使用的用戶不同的情況.
      src:                   # (必選)指定待傳輸的源⽂件。可以是相對路徑,也可以是絕對路徑.
      times:                 # 保留mtime屬性
      use_ssh_args:          # 使用ansible.cfg中配置的ssh_args
      verify_host:           # 對目標主機進行ssh的host key驗證

 示例:

溫馨提示:在使用synchronize模塊的時候需要在管理機和被控制端的遠程服務器上安裝rsync,保證在管理機和被控制端的遠程服務器上有rsync的命令
安裝rsync:yum -y install rsync
1) 簡簡單單(指定src和dest)
[root@ansible ~]# ansible all -m synchronize -a "src=/root/rsyncfile/ dest=/root/rsyncfile/"
192.168.192.129 | CHANGED => {
    "changed": true, 
    "cmd": "/usr/bin/rsync --delay-updates -F --compress --archive --rsh=/usr/bin/ssh -S none -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null --out-format=<<CHANGED>>%i %n%L /root/rsyncfile/ 192.168.192.129:/root/rsyncfile/", 
    "msg": "cd+++++++++ ./\n<f+++++++++ 123\n<f+++++++++ 313\n<f+++++++++ 31323\n", 
    "rc": 0, 
    "stdout_lines": [
        "cd+++++++++ ./", 
        "<f+++++++++ 123", 
        "<f+++++++++ 313", 
        "<f+++++++++ 31323"
    ]
}
查看結果
[root@ansible ~]# ansible all -m shell -a "ls -l /root/rsyncfile"   
192.168.192.129 | CHANGED | rc=0 >>
total 0
-rw-r--r-- 1 root root 0 Dec 26 15:55 123
-rw-r--r-- 1 root root 0 Dec 26 15:55 313
-rw-r--r-- 1 root root 0 Dec 26 15:55 31323

2) 把本地的/root/rsyncfile目錄以及里面除了.txt結尾的文件同步到遠程服務器的/root目錄里面,並且同步/root/rsyncfile目錄以及文件的屬性,還要刪除本地沒有但遠程主機有的文件
/root/rsyncfile目錄下的內容
[root@ansible ~]# ll rsyncfile/
total 0
-rw-r--r-- 1 sshd sshd 0 Dec 26 15:55 123
-rw-r--r-- 1 sshd sshd 0 Dec 26 16:02 1.txt
-rw-r--r-- 1 sshd sshd 0 Dec 26 16:02 2.txx
-rw-r--r-- 1 sshd sshd 0 Dec 26 15:55 313
-rw-r--r-- 1 sshd sshd 0 Dec 26 15:55 31323
-rw-r--r-- 1 sshd sshd 0 Dec 26 16:02 3.txt
-rw-r--r-- 1 sshd sshd 0 Dec 26 16:02 4.py

[root@ansible ~]# ansible all -m synchronize -a "src=/root/rsyncfile dest=/root compress=yes delete=yes archive=yes rsync_opts=--exclude=*.txt"  
192.168.192.129 | CHANGED => {
    "changed": true, 
    "cmd": "/usr/bin/rsync --delay-updates -F --compress --delete-after --archive --rsh=/usr/bin/ssh -S none -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null --exclude=*.txt --out-format=<<CHANGED>>%i %n%L /root/rsyncfile 192.168.192.129:/root", 
    "msg": "cd+++++++++ rsyncfile/\n<f+++++++++ rsyncfile/123\n<f+++++++++ rsyncfile/2.txx\n<f+++++++++ rsyncfile/313\n<f+++++++++ rsyncfile/31323\n<f+++++++++ rsyncfile/4.py\n", 
    "rc": 0, 
    "stdout_lines": [
        "cd+++++++++ rsyncfile/", 
        "<f+++++++++ rsyncfile/123", 
        "<f+++++++++ rsyncfile/2.txx", 
        "<f+++++++++ rsyncfile/313", 
        "<f+++++++++ rsyncfile/31323", 
        "<f+++++++++ rsyncfile/4.py"
    ]
}

查看結果(可以看到同步過去的文件屬性都和源文件相同,並且沒有同步源文件里面以.txt結尾的兩個文件)
[root@ansible ~]# ansible all -m shell -a "ls -l /root/rsyncfile"
192.168.192.129 | CHANGED | rc=0 >>
total 0
-rw-r--r-- 1 sshd sshd 0 Dec 26 15:55 123
-rw-r--r-- 1 sshd sshd 0 Dec 26 16:02 2.txx
-rw-r--r-- 1 sshd sshd 0 Dec 26 15:55 313
-rw-r--r-- 1 sshd sshd 0 Dec 26 15:55 31323
-rw-r--r-- 1 sshd sshd 0 Dec 26 16:02 4.py

hostname 模塊

用途:管理配置主機名
使用方法:

[root@ansible ~]# ansible-doc -s hostname
- name: Manage hostname
  hostname:
      name:                  # 必選,主機名稱

示例:

溫馨提示:使用這個模塊存在一個問題就是一改主機名緊跟着應該是在這個清單里面的機器都會被改掉導致主機名完全相同
是有解決方法的,使用變量的方式進行更改

先針對一台主機進行修改主機名,了解其用法
[root@ansible ~]# ansible 192.168.192.129 -m hostname -a "name=ansible_node1"          
192.168.192.129 | CHANGED => {
    "ansible_facts": {
        "ansible_domain": "", 
        "ansible_fqdn": "ansible_node1", 
        "ansible_hostname": "ansible_node1", 
        "ansible_nodename": "ansible_node1"
    }, 
    "changed": true, 
    "name": "ansible_node1"
}
查看結果(發現主機名已經修改)
[root@ansible ~]# ansible 192.168.192.129 -m shell -a "hostname"
192.168.192.129 | CHANGED | rc=0 >>
ansible_node1

使用hostname模塊修改主機名是直接生效的並且是永久生效

yum 模塊

用途:使用yum包管理器管理包
使用方法:

[root@ansible ~]# ansible-doc -s yum
- name: Manages packages with the `yum' package manager
  yum:
      allow_downgrade:       # 是否允許給現有包的版本進行降級
      autoremove:            # 卸載包並且刪除其所有的依賴包,如果這個依賴包被其他包所依賴則不會刪除(authorremove=yes)
      bugfix:                # 如果bugfix=yes和state=latest則僅安裝已標記為與bug修復相關的更新
      conf_file:             # 指定yum.repo配置文件.
      disable_excludes:      # 禁用YUM配置文件中定義的排除(yum.repo文件中的某個塊). 
                             # disable_excludes=all 禁用所有排除
                             # disable_excludes=main 禁用yum.conf中的[main]中定義的排除
                             # disable_excludes=repoid 禁用未給定repo id定義的排除
      disable_gpg_check:     # 安裝包時禁止gpgcheck,僅在state=present或者latest時生效.
      disable_plugin:        # 禁用yum的Loaded plugins(使用yum repolist all | less 查看所有插件)
      disablerepo:           # 禁止指定的repo源,多個repo源使用逗號分隔
      download_only:         # 只下載指定的安裝包,不進行安裝.
      enable_plugin:         # 開啟yum的Loaded plugins(使用yum repolist all | less 查看所有插件).
      enablerepo:            # 明確使用那個repo源
      exclude:               # 排除那些包不安裝,僅在state=present或者latest時生效
      installroot:           # 指定yum安裝包的用戶,用此用戶安裝的只允許root和指定用戶使用
      list:                  # 類似於yum list.
      name:                  # (必選參數)指定包名,可以指定版本號,多個包可以使用逗號分隔
      releasever:            # Specifies an alternative release from which all packages will be installed.
      security:              # 如果設置為yes和state=latest,則只安裝標記為與安全相關的更新
      skip_broken:           # 跳過具有損壞的依賴包
      state:                 # 用於指定軟件包的狀態 ,默認值為present,表示確保軟件包已經安裝
                             # state=present安裝狀態(默認值)
                             # state=installed安裝狀態
                             # state=latest安裝狀態(安裝最新的版本)
                             # state=absent卸載狀態
                             # state=removed卸載狀態
      update_cache:          # 強制yum檢查緩存是否過期,並在需要時重新下載.僅在state=present或者latest時生效.
      update_only:           # 使用最新軟件包時,只更新已安裝的軟件包。不要安裝軟件包.僅在state=present或者latest時生效
      validate_certs:        # 這僅適用於使用https url作為rpm的源的情況。例如,用於localinstall。如果設置為no,則不會驗證SSL證書

示例:

使用nginx和telnet為例(對應 yum 源未開啟 gpg 驗證,所以需要設置 disable_gpg_check=yes)
這里輸出的東西太多了結果就不放到博客了(結果綠色和黃色都是執行成功了,紅色為錯誤)
1) state=present(安裝包)
[root@ansible ~]# ansible all -m yum -a "name=nginx disable_gpg_check=yes state=present"

2) state=installed(安裝包)
[root@ansible ~]# ansible all -m yum -a "name=nginx disable_gpg_check=yes state=installed"

3) state=latest(安裝最新的版本)
[root@ansible ~]# ansible all -m yum -a "name=nginx disable_gpg_check=yes state=latest"

4) state=absent(卸載包)
[root@ansible ~]# ansible all -m yum -a "name=nginx disable_gpg_check=yes state=absent"

5) state=removed(卸載包)
[root@ansible ~]# ansible all -m yum -a "name=nginx disable_gpg_check=yes state=removed"

6) enablerepo(明確使用那個repo源)
[root@ansible ~]# ansible all -m yum -a "name=telnet disable_gpg_check=yes enablerepo=local"

7) disablerepo(禁止指定的repo源,多個repo源使用逗號分隔)
[root@ansible ~]# ansible all -m yum -a "name=telnet disable_gpg_check=yes disablerepo=local"

更多模塊

更多模塊請點擊:https://www.cnblogs.com/brianzhu/p/10175477.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM