Ansible常見模組
ansible中常用的模組詳解:
file模組
ansible內建的可以檢視模組用法的命令如下:
[root@ansible ~]# ansible-doc -s file - name: Manage files and file properties file: access_time: # This parameter indicates the time the file's access time should be set to. Should be `preserve' when no modification is required, `YYYYMMDDHHMM.SS' when using default time format, or `now'. Default is `None' meaning that `preserve' is the default for `state=[file,directory,link,hard]' and `now' is default for `state=touch'. access_time_format: # When used with `access_time', indicates the time format that must be used. Based on default Python format (see time.strftime doc). attributes: # The attributes the resulting file or directory should have. To get supported flags look at the man page for `chattr' on the target system. This string should contain the attributes in the same order as the one displayed by `lsattr'. The `=' operator is assumed as default, otherwise `+' or `-' operators need to be included in the string. follow: # This flag indicates that filesystem links, if they exist, should be followed. Previous to Ansible 2.5, this was `no' by default. force: # Force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the destination exists and is a file (so, we need to unlink the `path' file and create symlink to the `src' file in place of it). group: # Name of the group that should own the file/directory, as would be fed to `chown'. mode: # The permissions the resulting file or directory should have. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers. You must either add a leading zero so that Ansible's YAML parser knows it is an octal number (like `0644' or `01777') or quote it (like `'644'' or `'1777'') so Ansible receives a string and can do its own conversion from string into number. Giving Ansible a number without following one of these rules will end up with a decimal number which will have unexpected results. As of Ansible 1.8, the mode may be specified as a symbolic mode (for example, `u+rwx' or `u=rw,g=r,o=r'). As of Ansible 2.6, the mode may also be the special string `preserve'. When set to `preserve' the file will be given the same permissions as the source file. modification_time: # This parameter indicates the time the file's modification time should be set to. Should be `preserve' when no modification is required, `YYYYMMDDHHMM.SS' when using default time format, or `now'. Default is None meaning that `preserve' is the default for `state=[file,directory,link,hard]' and `now' is default for `state=touch'. modification_time_format: # When used with `modification_time', indicates the time format that must be used. Based on default Python format (see time.strftime doc). owner: # Name of the user that should own the file/directory, as would be fed to `chown'. path: # (required) Path to the file being managed. recurse: # Recursively set the specified file attributes on directory contents. This applies only when `state' is set to `directory'. selevel: # The level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. When set to `_default', it will use the `level' portion of the policy if available. serole: # The role part of the SELinux file context. When set to `_default', it will use the `role' portion of the policy if available. setype: # The type part of the SELinux file context. When set to `_default', it will use the `type' portion of the policy if available. seuser: # The user part of the SELinux file context. By default it uses the `system' policy, where applicable. When set to `_default', it will use the `user' portion of the policy if available. src: # Path of the file to link to. This applies only to `state=link' and `state=hard'. For `state=link', this will also accept a non-existing path. Relative paths are relative to the file being created (`path') which is how the Unix command `ln -s SRC DEST' treats relative paths. state: # If `absent', directories will be recursively deleted, and files or symlinks will be unlinked. In the case of a directory, if `diff' is declared, you will see the files and folders deleted listed under `path_contents'. Note that `absent' will not cause `file' to fail if the `path' does not exist as the state did not change. If `directory', all intermediate subdirectories will be created if they do not exist. Since Ansible 1.7 they will be created with the supplied permissions. If `file', without any other options this works mostly as a 'stat' and will return the current state of `path'. Even with other options (i.e `mode'), the file will be modified but will NOT be created if it does not exist; see the `touch' value or the [copy] or [template] module if you want that behavior. If `hard', the hard link will be created or changed. If `link', the symbolic link will be created or changed. If `touch' (new in 1.4), an empty file will be created if the `path' does not exist, while an existing file or directory will receive updated file access and modification times (similar to the way `touch' works from the command line). unsafe_writes: # Influence when to use atomic operation to prevent data corruption or inconsistent reads from the target file. By default this module uses atomic operations to prevent data corruption or inconsistent reads from the target files, but sometimes systems are configured or just broken in ways that prevent this. One example is docker mounted files, which cannot be updated atomically from inside the container and can only be written in an unsafe manner. This option allows Ansible to fall back to unsafe methods of updating files when atomic operations fail (however, it doesn't force Ansible to perform unsafe writes). IMPORTANT! Unsafe writes are subject to race conditions and can lead to data corruption.
file模組用來設定檔案屬性,並且建立或者刪除目錄,建立連線。
相關選項如下: force:需要在兩種情況下強制建立軟連結,一種是原始檔不存在,但之後會建立的情況下;另一種是目標軟連結已存在,需要先取消之前的軟鏈,然後建立新的軟鏈,有兩個選項:yes|no group:定義檔案/目錄的屬組 mode:定義檔案/目錄的許可權 owner:定義檔案/目錄的屬主 path:必選項,定義檔案/目錄的路徑 recurse:遞迴設定檔案的屬性,只對目錄有效 src:被連結的原始檔路徑,只應用於state=link的情況 dest:被連結到的路徑,只應用於state=link的情況 state: directory:如果目錄不存在,就建立目錄 file:即使檔案不存在,也不會被建立 link:建立軟連結 hard:建立硬連結 touch:如果檔案不存在,則會建立一個新的檔案,如果檔案或目錄已存在,則更新其最後修改時間 absent:刪除目錄、檔案或者取消連結檔案
利用file模組建立一個檔案:
[root@ansible ~]# ansible k8sservers -m file -a "path=/tmp/test state=touch owner=root group=root" 192.168.1.114 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "dest": "/tmp/test", "gid": 0, "group": "root", "mode": "0644", "owner": "root", "size": 0, "state": "file", "uid": 0 } 192.168.1.111 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "dest": "/tmp/test", "gid": 0, "group": "root", "mode": "0644", "owner": "root", "size": 0, "state": "file", "uid": 0 } 192.168.1.113 | CHANGED => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": true, "dest": "/tmp/test", "gid": 0, "group": "root", "mode": "0644", "owner": "root", "size": 0, "state": "file", "uid": 0 } [root@ansible ~]#
copy模組
主要的作用是複製檔案到遠端主機:
相關選項如下:
backup:在覆蓋之前,將原始檔備份,備份檔案包含時間資訊。有兩個選項:yes|no
content:用於替代“src”,可以直接設定指定檔案的值
dest:必選項。要將原始檔複製到的遠端主機的絕對路徑,如果原始檔是一個目錄,那麼該路徑也必須是個目錄
directory_mode:遞迴設定目錄的許可權,預設為系統預設許可權
force:如果目標主機包含該檔案,但內容不同,如果設定為yes,則強制覆蓋,如果為no,則只有當目標主機的目標位置不存在該檔案時,才複製。預設為yes
others:所有的file模組裡的選項都可以在這裡使用
src:被複制到遠端主機的本地檔案,可以是絕對路徑,也可以是相對路徑。如果路徑是一個目錄,它將遞迴複製。在這種情況下,如果路徑使用“/”來結尾,則只複製目錄裡的內容,如果沒有使用“/”來結尾,則包含目錄在內的整個內容全部複製,類似於rsync
示例如下:
[root@ansible ~]# ansible test -m copy -a "src=/etc/sysconfig dest=/test owner=root mode=600"
192.168.1.106 | CHANGED => {
"changed": true,
"dest": "/test/",
"src": "/etc/sysconfig"
}
[root@ansible ~]# ansible test -a "ls -l /test/"
192.168.1.106 | CHANGED | rc=0 >>
總用量 4
drwxr-xr-x. 5 root root 4096 7月 29 22:09 sysconfig
[root@ansible ~]#
[root@ansible ~]# ansible k8sservers -m copy -a "content='test1\ntest2' dest=/tmp/test.txt" 192.168.1.111 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "efc492233d97a1898c8f797904442e6b26758276",
"dest": "/tmp/test.txt",
"gid": 0,
"group": "root",
"md5sum": "5bdd30886cf6f00a7286ac6e7322a46e",
"mode": "0644",
"owner": "root",
"size": 11,
"src": "/root/.ansible/tmp/ansible-tmp-1596074441.523403-76201-249571230429455/source",
"state": "file",
"uid": 0
}
192.168.1.114 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "efc492233d97a1898c8f797904442e6b26758276",
"dest": "/tmp/test.txt",
"gid": 0,
"group": "root",
"md5sum": "5bdd30886cf6f00a7286ac6e7322a46e",
"mode": "0644",
"owner": "root",
"size": 11,
"src": "/root/.ansible/tmp/ansible-tmp-1596074441.5974753-76197-200420129308227/source",
"state": "file",
"uid": 0
}
192.168.1.113 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"checksum": "efc492233d97a1898c8f797904442e6b26758276",
"dest": "/tmp/test.txt",
"gid": 0,
"group": "root",
"md5sum": "5bdd30886cf6f00a7286ac6e7322a46e",
"mode": "0644",
"owner": "root",
"size": 11,
"src": "/root/.ansible/tmp/ansible-tmp-1596074441.5863822-76199-175841689491626/source",
"state": "file",
"uid": 0
}
[root@ansible ~]#
fetch模組
文件示例:
[root@ansible os]# ansible-doc -s fetch
- name: Fetch files from remote nodes
fetch:
dest: # (required) A directory to save the file into. For example, if the `dest' directory is `/backup' a `src' file named
`/etc/profile' on host `host.example.com', would be saved into
`/backup/host.example.com/etc/profile'. The host name is based on the inventory
name.
fail_on_missing: # When set to `yes', the task will fail if the remote file cannot be read for any reason. Prior to Ansible 2.5,
setting this would only fail if the source file was missing. The default was changed
to `yes' in Ansible 2.5.
flat: # Allows you to override the default behavior of appending hostname/path/to/file to the destination. If `dest' ends
with '/', it will use the basename of the source file, similar to the copy module.
This can be useful if working with a single host, or if retrieving files that are
uniquely named per host. If using multiple hosts with the same filename, the file
will be overwritten for each host.
src: # (required) The file on the remote system to fetch. This `must' be a file, not a directory. Recursive fetching may
be supported in a later release.
validate_checksum: # Verify that the source and destination checksums match after the files are fetched.
[root@ansible os]#
示例如下:
[root@ansible ~]# ansible k8sservers -m fetch -a 'src=/tmp/test dest=/tmp/os'
192.168.1.114 | CHANGED => {
"changed": true,
"checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
"dest": "/tmp/os/192.168.1.114/tmp/test",
"md5sum": "d41d8cd98f00b204e9800998ecf8427e",
"remote_checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
"remote_md5sum": null
}
192.168.1.111 | CHANGED => {
"changed": true,
"checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
"dest": "/tmp/os/192.168.1.111/tmp/test",
"md5sum": "d41d8cd98f00b204e9800998ecf8427e",
"remote_checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
"remote_md5sum": null
}
192.168.1.113 | CHANGED => {
"changed": true,
"checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
"dest": "/tmp/os/192.168.1.113/tmp/test",
"md5sum": "d41d8cd98f00b204e9800998ecf8427e",
"remote_checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
"remote_md5sum": null
}
[root@ansible ~]#
cron模組
我們知道crontab的主要作用就是制定定時計劃任務,cron模組的主要作用和crontab命令是一樣的。
我們知道在linux中新增一個計劃任務需要指定計劃任務執行的時間,執行的命令。而cron模組也是這樣。
[root@ansible ~]# ansible test -m cron -a 'name="custom job" minute=30 hour=2 day=* month=* weekday=1-5 job="sh tesh.sh"'
192.168.1.106 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"custom job"
]
}
[root@ansible ~]# ansible test -a 'crontab -l'
192.168.1.106 | CHANGED | rc=0 >>
#Ansible: custom job
30 2 * * 1-5 sh tesh.sh
[root@ansible ~]# ansible test -m cron -a 'name="custom job" minute=30 hour=2 day=* month=* weekday=1-5 job="sh tesh.sh" disabled=yes'
192.168.1.106 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": [
"custom job"
]
}
[root@ansible ~]# ansible test -a 'crontab -l'
192.168.1.106 | CHANGED | rc=0 >>
#Ansible: custom job
#30 2 * * 1-5 sh tesh.sh
[root@ansible ~]# ansible test -m cron -a 'name="custom job" state=absent'
192.168.1.106 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"envs": [],
"jobs": []
}
[root@ansible ~]# ansible test -a 'crontab -l'
192.168.1.106 | CHANGED | rc=0 >>
[root@ansible ~]#
yum 模組
可以執行yum命令
[root@ansible ~]# ansible test -m yum -a "name=httpd state=absent"
192.168.1.106 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"removed": [
"httpd"
]
},
"msg": "",
"rc": 0,
"results": [
"已載入外掛:fastestmirror\n正在解決依賴關係\n--> 正在檢查事務\n---> 軟體包 httpd.x86_64.0.2.4.6-93.el7.centos 將被 刪除\n--> 解決依賴關係完成\n\n依賴關係解決\n\n================================================================================\n Package 架構 版本 源 大小\n================================================================================\n正在刪除:\n httpd x86_64 2.4.6-93.el7.centos @base 9.4 M\n\n事務概要\n================================================================================\n移除 1 軟體包\n\n安裝大小:9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n 正在刪除 : httpd-2.4.6-93.el7.centos.x86_64 1/1 \n 驗證中 : httpd-2.4.6-93.el7.centos.x86_64 1/1 \n\n刪除:\n httpd.x86_64 0:2.4.6-93.el7.centos \n\n完畢!\n"
]
}
[root@ansible ~]# ansible test -m yum -a "name=httpd"
192.168.1.106 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"changes": {
"installed": [
"httpd"
]
},
"msg": "",
"rc": 0,
"results": [
"Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirror.upsi.edu.my\n * extras: centos.mirror.myduniahost.com\n * updates: centos.mirror.angkasa.id\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-93.el7.centos will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n httpd x86_64 2.4.6-93.el7.centos base 2.7 M\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 2.7 M\nInstalled size: 9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : httpd-2.4.6-93.el7.centos.x86_64 1/1 \n Verifying : httpd-2.4.6-93.el7.centos.x86_64 1/1 \n\nInstalled:\n httpd.x86_64 0:2.4.6-93.el7.centos \n\nComplete!\n"
]
}
[root@ansible ~]#
service模組
service模組主要用來對系統中的服務進行管理。
[root@ansible ~]# ansible-doc -s service
- name: Manage services
service:
arguments: # Additional arguments provided on the command line.
enabled: # Whether the service should start on boot. *At least one of state and enabled are required.*
name: # (required) Name of the service.
pattern: # If the service does not respond to the status command, name a substring to look for as would be found in the output
of the `ps' command as a stand-in for a status result. If the string is found, the
service will be assumed to be started.
runlevel: # For OpenRC init scripts (e.g. Gentoo) only. The runlevel that this service belongs to.
sleep: # If the service is being `restarted' then sleep this many seconds between the stop and start command. This helps to
work around badly-behaving init scripts that exit immediately after signaling a
process to stop. Not all service managers support sleep, i.e when using systemd this
setting will be ignored.
state: # `started'/`stopped' are idempotent actions that will not run commands unless necessary. `restarted' will always
bounce the service. `reloaded' will always reload. *At least one of state and
enabled are required.* Note that reloaded will start the service if it is not
already started, even if your chosen init system wouldn't normally.
use: # The service module actually uses system specific modules, normally through auto detection, this setting can force a
specific module. Normally it uses the value of the 'ansible_service_mgr' fact and
falls back to the old 'service' module when none matching is found.
[root@ansible ~]#
相關引數如下:
name: 指定服務的名稱。
state:指定對服務進行的操作,started, stopped, restarted, reloaded。【是對應動詞的過去分詞形式】
enabled: yes|no, 是否加入開機自啟動。
runlevel: 啟動的級別。
啟動對應伺服器上的httpd服務,如下:
[root@ansible ~]# ansible test -m service -a "name=httpd state=started"
192.168.1.106 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"name": "httpd",
"state": "started",
"status": {
"ActiveEnterTimestampMonotonic": "0",
"ActiveExitTimestampMonotonic": "0",
"ActiveState": "inactive",
"After": "basic.target tmp.mount system.slice network.target -.mount nss-lookup.target systemd-journald.socket remote-fs.target",
"AllowIsolate": "no",
"AmbientCapabilities": "0",
"AssertResult": "no",
"AssertTimestampM"
[root@ansible ~]# ansible test -a "ss -ntl"
192.168.1.106 | CHANGED | rc=0 >>
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 [::]:80 [::]:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 100 [::1]:25 [::]:*
[root@ansible ~]#
command模組
command 模組可以幫助我們在遠端主機上執行命令。
注意:使用 command 模組在遠端主機中執行命令時,不會經過遠端主機的 shell 處理,在使用 command 模組時,如果需要執行的命令中含有重定向、管道符等操作時,這些符號也會失效,比如”<”, “>”, “|”, “;” 和 “&” 這些符號,如果你需要這些功能,可以參考後面介紹的 shell 模組。還有一點需要注意,如果遠端節點是 windows 作業系統,則需要使用 win_command 模組。執行 ansible 時,不加 -m 預設使用 command ,可以在 /etc/ansible/ansible.cfg 中修改。
command模組的幾個選項如下:
相關選項如下:
creates:一個檔名,當該檔案存在,則該命令不執行
free_form:要執行的linux指令,這裡的free_form不需要寫成賦值的形式,直接寫要執行的命令即可。
chdir:在執行指令之前,先切換到該目錄
removes:一個檔名,當該檔案不存在,則該選項不執行
executable:切換shell來執行指令,該執行路徑必須是一個絕對路徑
例項如下:
[root@docker5 ~]# ansible -i /root/hosts all -a "w"
10.0.102.212 | SUCCESS | rc=0 >>
10:25:27 up 8 days, 13:04, 2 users, load average: 0.09, 0.03, 0.05
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root tty1 12Feb19 8days 0.01s 0.01s -bash
root pts/1 10.0.102.209 10:25 0.00s 0.12s 0.02s w
10.0.102.200 | SUCCESS | rc=0 >>
10:25:30 up 9 days, 17:52, 3 users, load average: 0.05, 0.04, 0.06
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root tty1 11Feb19 9days 0.01s 0.01s -bash
root pts/1 172.16.100.19 08:02 2:19m 0.02s 0.01s /usr/local/mysql/bin/mysql -uroot -px xxxx
root pts/2 10.0.102.209 10:25 0.00s 0.16s 0.03s w
10.0.102.162 | SUCCESS | rc=0 >>
10:25:30 up 9 days, 17:52, 3 users, load average: 0.16, 0.05, 0.06
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root tty1 11Feb19 9days 0.07s 0.07s -bash
root pts/1 172.16.100.19 08:02 2:20m 0.03s 0.01s /usr/local/mysql/bin/mysql -uroot -px xxxx
root pts/2 10.0.102.209 10:25 1.00s 0.21s 0.03s w
[root@docker5 ~]# ansible -i /root/hosts all -a "w creates=/tmp/test"
10.0.102.212 | SUCCESS | rc=0 >>
skipped, since /tmp/test exists
10.0.102.200 | SUCCESS | rc=0 >>
skipped, since /tmp/test exists
10.0.102.162 | SUCCESS | rc=0 >>
skipped, since /tmp/test exists
[root@docker5 ~]#
上面已經提到過command模組不能執行管道,而shell模組可以,因此在平時使用時習慣使用shell模組。
command與shell比較的一個例項
script模組
script 模組可以幫助我們在遠端主機上執行 ansible 管理主機上的指令碼,也就是說,指令碼一直存在於 ansible 管理主機本地,不需要手動拷貝到遠端主機後再執行。
script模組的用法如下:
[root@docker5 tasks]# ansible-doc -s script
- name: Runs a local script on a remote node after transferring it
script:
chdir: # cd into this directory on the remote node before running the script
creates: # a filename, when it already exists, this step will *not* be run.
decrypt: # This option controls the autodecryption of source files using vault.
free_form: # (required) Path to the local script file followed by optional arguments. There is no parameter actually named 'free form'; see the
examples!
removes: # a filename, when it does not exist, this step will *not* be run.
[root@docker5 tasks]#
把本地的指令碼在遠端主機上執行。這個命令的選項和command差不多,不同的是這裡執行的是shell指令碼而已。
示例:
[root@ansible ~]# ansible k8sservers -m script -a 'test.sh'
192.168.1.114 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.1.114 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.1.114 closed."
],
"stdout": "1245\r\n",
"stdout_lines": [
"1245"
]
}
192.168.1.111 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.1.111 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.1.111 closed."
],
"stdout": "1245\r\n",
"stdout_lines": [
"1245"
]
}
192.168.1.113 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.1.113 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.1.113 closed."
],
"stdout": "1245\r\n",
"stdout_lines": [
"1245"
]
}
[root@ansible ~]#
hostname模組
示例如下:
[root@ansible ~]# ansible 192.168.1.106 -m hostname -a 'name=test'
192.168.1.106 | CHANGED => {
"ansible_facts": {
"ansible_domain": "",
"ansible_fqdn": "test",
"ansible_hostname": "test",
"ansible_nodename": "test",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"name": "test"
}
[root@ansible ~]# ansible 192.168.1.106 -a 'hostname'
192.168.1.106 | CHANGED | rc=0 >>
test
[root@ansible ~]#
unarchive模組
這個模組的主要作用就是解壓。模組有兩種用法:
1:如果引數copy=yes,則把本地的壓縮包拷貝到遠端主機,然後執行壓縮。
2:如果引數copy=no,則直接解壓遠端主機上給出的壓縮包。
creates:指定一個檔名,當該檔案存在時,則解壓指令不執行
dest:遠端主機上的一個路徑,即檔案解壓的路徑
grop:解壓後的目錄或檔案的屬組
list_files:如果為yes,則會列出壓縮包裡的檔案,預設為no,2.0版本新增的選項
mode:解決後文件的許可權
src:如果copy為yes,則需要指定壓縮檔案的源路徑
owner:解壓後文件或目錄的屬主
例項如下:
[root@ansible ~]# ansible test -m unarchive -a 'src=/root/ansible-tower-setup-bundle-latest.el8.tar.gz dest=/tmp/ copy=yes'
192.168.1.106 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/tmp/",
"extract_results": {
"cmd": [
"/usr/bin/gtar",
"--extract",
"-C",
"/tmp/",
"-z",
"-f",
"/root/.ansible/tmp/ansible-tmp-1596078884.6408756-78125-191332661192420/source"
],
"err": "",
"out": "",
"rc": 0
},
"gid": 0,
"group": "root",
"handler": "TgzArchive",
"mode": "01777",
"owner": "root",
"secontext": "system_u:object_r:tmp_t:s0",
"size": 4096,
"src": "/root/.ansible/tmp/ansible-tmp-1596078884.6408756-78125-191332661192420/source",
"state": "directory",
"uid": 0
}
[root@ansible ~]# ansible test -a 'ls -l /tmp'
192.168.1.106 | CHANGED | rc=0 >>
總用量 0
drwx------. 2 root root 41 7月 29 23:17 ansible_command_payload_WjHpfT
drwxr-xr-x. 6 root root 190 6月 17 06:50 ansible-tower-setup-bundle-3.7.1-1
drwxr-xr-x. 2 root root 6 7月 21 12:02 hsperfdata_root
drwx------. 3 root root 17 7月 27 10:29 systemd-private-ea6ae227571847ce8735c60bd0441345-chronyd.service-XFjVs3
drwxr-xr-x. 3 root root 18 7月 21 08:46 tomcat.1157605043846008267.8083
drwxr-xr-x. 3 root root 18 7月 21 08:44 tomcat.4359714464398435032.8080
drwxr-xr-x. 3 root root 18 7月 21 08:46 tomcat.8798180483937495567.8082
drwx------. 2 root root 6 7月 27 10:29 vmware-root_784-2966103535
drwx------. 2 root root 6 7月 19 10:49 vmware-root_789-4290756532
drwx------. 2 root root 6 7月 26 11:03 vmware-root_804-2991071810
與之相對的壓縮命令的模組是archive。
archive壓縮命令
檢視其文件用法如下:
[root@docker5 tasks]# ansible-doc -s archive
- name: Creates a compressed archive of one or more files or trees
archive:
attributes: # Attributes the file or directory should have. To get supported flags look at the man page for `chattr' on the target system. This string should contain the attributes in
the same order as the one displayed by `lsattr'.
dest: # The file name of the destination archive. This is required when `path' refers to multiple files by either specifying a glob, a directory or multiple paths in a list.
exclude_path: # Remote absolute path, glob, or list of paths or globs for the file or files to exclude from the archive
format: # The type of compression to use. Support for xz was added in version 2.5.
group: # Name of the group that should own the file/directory, as would be fed to `chown'.
mode: # Mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers (like `0644' or `01777'). Leaving off the leading
zero will likely have unexpected results. As of version 1.8, the mode may be specified as a symbolic mode (for example, `u+rwx' or
`u=rw,g=r,o=r').
owner: # Name of the user that should own the file/directory, as would be fed to `chown'.
path: # (required) Remote absolute path, glob, or list of paths or globs for the file or files to compress or archive.
remove: # Remove any added source files and trees after adding to archive.
selevel: # Level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. `_default' feature works as for `seuser'.
serole: # Role part of SELinux file context, `_default' feature works as for `seuser'.
setype: # Type part of SELinux file context, `_default' feature works as for `seuser'.
seuser: # User part of SELinux file context. Will default to system policy, if applicable. If set to `_default', it will use the `user' portion of the policy if available.
unsafe_writes: # Normally this module uses atomic operations to prevent data corruption or inconsistent reads from the target files, sometimes systems are configured or just broken in
ways that prevent this. One example are docker mounted files, they cannot be updated atomically and can only be done in an unsafe manner.
This boolean option allows ansible to fall back to unsafe methods of updating files for those cases in which you do not have any other
choice. Be aware that this is subject to race conditions and can lead to data corruption.
示例如下:
[root@ansible ~]# ansible test -m archive -a "path=/test/ format=gz dest=/tmptest.tar.gz"
192.168.1.106 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"archived": [
"/test/sysconfig/ip6tables-config",
"/test/sysconfig/iptables-config",
"/test/sysconfig/ebtables-config",
"/test/sysconfig/nftables.conf",
"/test/sysconfig/run-parts",
"/test/sysconfig/crond",
"/test/sysconfig/grub",
"/test/sysconfig/selinux",
"/test/sysconfig/cpupower",
"/test/sysconfig/kdump",
"/test/sysconfig/samba",
"/test/sysconfig/firewalld",
"/test/sysconfig/sshd",
"/test/sysconfig/chronyd",
"/test/sysconfig/atd",
"/test/sysconfig/raid-check",
"/test/sysconfig/smartmontools",
"/test/sysconfig/irqbalance",
"/test/sysconfig/man-db",
"/test/sysconfig/kernel",
"/test/sysconfig/network",
"/test/sysconfig/anaconda",
"/test/sysconfig/svnserve",
"/test/sysconfig/memcached",
"/test/sysconfig/rsyslog",
"/test/sysconfig/ansible-tower",
"/test/sysconfig/network-scripts/ifcfg-ens192"
],
"arcroot": "/test/",
"changed": true,
"dest": "/tmptest.tar.gz",
"expanded_exclude_paths": [],
"expanded_paths": [
"/test/"
],
"gid": 0,
"group": "root",
"missing": [],
"mode": "0644",
"owner": "root",
"secontext": "unconfined_u:object_r:etc_runtime_t:s0",
"size": 6613,
"state": "file",
"uid": 0
}
[root@ansible ~]# ansible test -a "ls -l / |grep tmptest "
192.168.1.106 | CHANGED | rc=0 >>
-rw-r--r--. 1 root root 6613 7月 29 23:47 tmptest.tar.gz
[root@ansible ~]#
因為源目錄裡面有兩個檔案,但是上面的壓縮只壓縮了一個檔案。
replace模組
這個模組可以根據我們指定的正則表示式替換檔案的匹配的內容。
先看一個例子:
- name: change the start script
#shell: sed -i "s/^datadir=/datadir=\/data\/mysql/" /etc/init.d/mysqld
replace: path=/etc/init.d/mysqld replace="datadir={{ datadir_name }}" regexp="^datadir=" backup=yes#安裝MySQL的時候,需要修改MySQL的啟動指令碼,配置datadir引數,這裡兩行的作用是一樣的。只是在執行playbook的時候,使用shell模組會報出警告說建議使用replcae模組。#模組引數如下:path: 指定遠端主機要替換的檔案的路徑。regexp: 指定在檔案中匹配的正則表示式,上面匹配以“datadir=”開頭的行replace: 指定替換的檔案,就是把上面正則匹配到的檔案,替換成這裡的內容。backup:表示在對檔案操作之前是否備份檔案。
示例:
[root@ansible ~]# ansible test -a 'cat /etc/fstab'
192.168.1.106 | CHANGED | rc=0 >>
#
# /etc/fstab
# Created by anaconda on Tue May 19 01:18:20 2020
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root / xfs defaults 0 0
UUID=27c0e916-7156-4ec3-b5e8-d4a32c43850f /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0
[root@ansible ~]# ansible test -m replace -a "path=/etc/fstab regexp='^(UUID.*)' replace='#\1' "
192.168.1.106 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"msg": "1 replacements made"
}
[root@ansible ~]# ansible test -a 'cat /etc/fstab'
192.168.1.106 | CHANGED | rc=0 >>
#
# /etc/fstab
# Created by anaconda on Tue May 19 01:18:20 2020
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root / xfs defaults 0 0
#UUID=27c0e916-7156-4ec3-b5e8-d4a32c43850f /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0
[root@ansible ~]#
反向操作:
[root@ansible ~]# ansible test -m replace -a "path=/etc/fstab regexp='^#(UUID.*)' replace='\1' "
192.168.1.106 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"msg": "1 replacements made"
}
[root@ansible ~]# ansible test -a 'cat /etc/fstab'
192.168.1.106 | CHANGED | rc=0 >>
#
# /etc/fstab
# Created by anaconda on Tue May 19 01:18:20 2020
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root / xfs defaults 0 0
UUID=27c0e916-7156-4ec3-b5e8-d4a32c43850f /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0
[root@ansible ~]#
lineinfile模組
這個模組會遍歷文字中每一行,然後對其中的行進行操作。
path引數 :必須引數,指定要操作的檔案。
line引數 : 使用此引數指定文字內容。
regexp引數 :使用正則表示式匹配對應的行,當替換文字時,如果有多行文字都能被匹配,則只有最後面被匹配到的那行文字才會被替換,當刪除文字時,如果有多行文字都能被匹配, 這麼這些行都會被刪除。
state引數:當想要刪除對應的文字時,需要將state引數的值設定為absent,absent為缺席之意,表示刪除,state的預設值為present。
backrefs引數:預設情況下,當根據正則替換文字時,即使regexp引數中的正則存在分組,在line引數中也不能對正則中的分組進行引用,除非將backrefs引數的值設定為yes。 backrefs=yes表示開啟後向引用,這樣,line引數中就能對regexp引數中的分組進行後向引用了,這樣說不太容易明白,可以參考後面的示例命令理解。backrefs=yes 除了能夠開啟後向引用功能,還有另一個作用,預設情況下,當使用正則表示式替換對應行時,如果正則沒有匹配到任何的行,那麼line對應的內容會被插入到文字的末尾, 不過,如果使用了backrefs=yes,情況就不一樣了,當使用正則表示式替換對應行時,同時設定了backrefs=yes,那麼當正則沒有匹配到任何的行時, 則不會對檔案進行任何操作,相當於保持原檔案不變。
insertafter引數:藉助insertafter引數可以將文字插入到“指定的行”之後,insertafter引數的值可以設定為EOF或者正則表示式,EOF為End Of File之意,表示插入到文件的末尾, 預設情況下insertafter的值為EOF,如果將insertafter的值設定為正則表示式,表示將文字插入到匹配到正則的行之後,如果正則沒有匹配到任何行,則插入到檔案末尾, 當使用backrefs引數時,此引數會被忽略。
insertbefore引數:藉助insertbefore引數可以將文字插入到“指定的行”之前,insertbefore引數的值可以設定為BOF或者正則表示式,BOF為Begin Of File之意, 表示插入到文件的開頭,如果將insertbefore的值設定為正則表示式,表示將文字插入到匹配到正則的行之前,如果正則沒有匹配到任何行,則插入到檔案末尾, 當使用backrefs引數時,此引數會被忽略。
backup引數:是否在修改檔案之前對檔案進行備份。
create引數 :當要操作的檔案並不存在時,是否建立對應的檔案。
示例如下:
[root@ansible ~]# ansible test -a "cat /etc/selinux/config"
192.168.1.106 | CHANGED | rc=0 >>
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=enforcing
# SELINUXTYPE= can take one of three values:
# targeted - Targeted processes are protected,
# minimum - Modification of targeted policy. Only selected processes are protected.
# mls - Multi Level Security protection.
SELINUXTYPE=targeted
[root@ansible ~]# ansible test -m lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=enforcing1'"
192.168.1.106 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"backup": "",
"changed": true,
"msg": "line replaced"
}
[root@ansible ~]# ansible test -a "cat /etc/selinux/config"
192.168.1.106 | CHANGED | rc=0 >>
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=enforcing1
# SELINUXTYPE= can take one of three values:
# targeted - Targeted processes are protected,
# minimum - Modification of targeted policy. Only selected processes are protected.
# mls - Multi Level Security protection.
SELINUXTYPE=targeted
setup模組
用來收集資訊
"ansible_distribution": "CentOS",
"ansible_distribution_file_parsed": true,
"ansible_distribution_file_path": "/etc/redhat-release",
"ansible_distribution_file_variety": "RedHat",
"ansible_distribution_major_version": "7",
"ansible_distribution_release": "Core",
"ansible_distribution_version": "7.8",
[root@ansible ~]# ansible all -m setup -a 'filter="ansible_distribution_version"'
192.168.1.106 | SUCCESS => {
"ansible_facts": {
"ansible_distribution_version": "7.8",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
192.168.1.114 | SUCCESS => {
"ansible_facts": {
"ansible_distribution_version": "7.8",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
192.168.1.111 | SUCCESS => {
"ansible_facts": {
"ansible_distribution_version": "7.8",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
192.168.1.113 | SUCCESS => {
"ansible_facts": {
"ansible_distribution_version": "7.8",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
192.168.1.117 | SUCCESS => {
"ansible_facts": {
"ansible_distribution_version": "7.8",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
}
[root@ansible ~]#