ansible基礎與部分模塊應用
1. ansible特性:
- ansible糅合了眾多老牌運維工具的優點,基本上pubbet和saltstack能實現的功能全部能實現。
- 部署簡單:不需要在被管控主機上安裝任何客戶端,操作客戶端時直接運行命令。
- 基於python語言實現,有Paramiko, PyYAML和Jinja2三個關鍵模塊。
- 模塊化:調用特定模塊完成特定任務。可使用任意語言開發模塊,且支持自定義模塊。
- 使用yaml語言定制劇本playbook。
- 基於SSH作
2. ansible的模塊
- connection plugins:連接插件,通過ssh方式
- host inventory:主機清單,要管理的主機
- playbooks:劇本,yaml格式的配置文件
- core modules:核心模塊
- custom modules:自定義模塊
- plugins:插件
- email:發送郵件。
- loggings:記錄日誌
3. 安裝
ansible放置位置:
- 外網主機:可通過×××連接為內網主機進行管理
- 內網主機:直接管理
ansible的安裝:
配置好epel源,直接通過yum安裝
~]# yum -y install ansible
ansible的配置文件:/etc/ansible/ansible.cfg
ansible的主機清單:/etc/ansible/hosts
ansible的主程序:ansible、ansible-playbos、ansible-doc
4. ansible命令的使用:
[root@nfs ~]# ansible -h Usage: ansible <host-pattern> [options] Options: -a MODULE_ARGS, --args=MODULE_ARGS module arguments -C, --check don‘t make any changes; instead, try to predict some of the changes that may occur -h, --help show this help message and exit -m MODULE_NAME, --module-name=MODULE_NAME module name to execute (default=command) --syntax-check perform a syntax check on the playbook, but do not execute it -f FORKS, --forks=FORKS specify number of parallel processes to use (default=5) -u REMOTE_USER, --user=REMOTE_USER connect as this user (default=None) -c CONNECTION, --connection=CONNECTION connection type to use (default=smart)
5. 定義主機列表:
示例1. 通過直接指定主機名或IP地址定義主機列表。
# Ex 1: Ungrouped hosts, specify before any group headers.
## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10
示例2. 先定義組名,再在組下填入主機名或IP地址
# Ex 2: A collection of hosts belonging to the ‘webservers‘ group
## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110
# If you have multiple hosts following a pattern you can specify
# them like this:
# 如果有多個連續主機,也可用如下方法指定主機。
## www[001:006].example.com
示例3.
# Ex 3: A collection of database servers in the ‘dbservers‘ group
## [dbservers]
##
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57
# Here‘s another example of host ranges, this time there are no
# leading 0s:
## db-[99:101]-node.example.com
## 以上寫法可擴展為如下主機:
## db-99-nod.example.com
## db-100-nod.example.com
## db-101-nod.example.com
定義主機列表示例:
[root@nfs ~]# tail -2 /etc/ansible/hosts
np[1:2].lxk.com
nfs.lxk.com
獲取主機列表:
[root@nfs ~]# ansible all --list-hosts
hosts (3):
np1.lxk.com
np2.lxk.com
nfs.lxk.com
6. ansible的常用模塊:
獲取模塊幫助信息:
[root@nfs ~]# ansible-doc --help
Usage: ansible-doc [-l|-F|-s] [options] [plugin]
plugin documentation tool
Options:
-a, --all **For internal testing only** Show documentation for
all plugins. #內測使用
-h, --help show this help message and exit
-l, --list List available plugins 顯示可用插件
-s, --snippet Show playbook snippet for specified plugin(s)
## 顯示指定插件用法
獲取模塊列表:
~]# ansible-doc -l
6.1 ping模塊:探測遠程主機
[root@nfs ~]# ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong‘ on success
# 嘗試連接主機,若目標主機可用,就回應一個‘pong‘
ping:
data: # Data to return for the `ping‘ return value. If this parameter is set to `crash‘, the module will cause an exception.
示例1:向所有可控主機發起ping操作
[root@nfs ~]# ansible all -m ping
np2.lxk.com | SUCCESS => {
"changed": false,
"ping": "pong"
}
nfs.lxk.com | SUCCESS => {
"changed": false,
"ping": "pong"
}
np1.lxk.com | SUCCESS => {
"changed": false,
"ping": "pong"
}
示例2:data自定義回顯內容為abc
[root@nfs ~]# ansible all -m ping -a data=‘abc‘
np1.lxk.com | SUCCESS => {
"changed": false,
"ping": "abc"
}
np2.lxk.com | SUCCESS => {
"changed": false,
"ping": "abc"
}
nfs.lxk.com | SUCCESS => {
"changed": false,
"ping": "abc"
}
*示例3:data為crash時,顯示結果為false
[root@nfs ~]# ansible all -m ping -a data=‘crash‘
np1.lxk.com | FAILED! => {
"changed": false,
"module_stderr": "Shared connection to np1.lxk.com closed.\r\n",
"module_stdout": "Traceback (most recent call last):\r\n File \"/tmp/ansible_2DLaM3/ansible_module_ping.py\", line 84, in <module>\r\n main()\r\n File \"/tmp/ansible_2DLaM3/ansible_module_ping.py\", line 74, in main\r\n raise Exception(\"boom\")\r\nException: boom\r\n",
"msg": "MODULE FAILURE",
"rc": 1
}
nfs.lxk.com | FAILED! => {
"changed": false,
"module_stderr": "Shared connection to nfs.lxk.com closed.\r\n",
"module_stdout": "Traceback (most recent call last):\r\n File \"/tmp/ansible_imV6B2/ansible_module_ping.py\", line 84, in <module>\r\n main()\r\n File \"/tmp/ansible_imV6B2/ansible_module_ping.py\", line 74, in main\r\n raise Exception(\"boom\")\r\nException: boom\r\n",
"msg": "MODULE FAILURE",
"rc": 1
}
np2.lxk.com | FAILED! => {
"changed": false,
"module_stderr": "Shared connection to np2.lxk.com closed.\r\n",
"module_stdout": "Traceback (most recent call last):\r\n File \"/tmp/ansible_iocg2P/ansible_module_ping.py\", line 84, in <module>\r\n main()\r\n File \"/tmp/ansible_iocg2P/ansible_module_ping.py\", line 74, in main\r\n raise Exception(\"boom\")\r\nException: boom\r\n",
"msg": "MODULE FAILURE",
"rc": 1
}
6.2 command模塊:在遠程主機上運行命令
模塊用法:
對於command來說,要使用哪個命令,使用-a選項,直接給出命令本身即可。
例1:創建臨時文件
[root@nfs ~]# ansible all -m command -a "mktemp /tmp/abc.XXXX"
nfs.lxk.com | SUCCESS | rc=0 >>
/tmp/abc.Xyz7
np2.lxk.com | SUCCESS | rc=0 >>
/tmp/abc.lwqo
np1.lxk.com | SUCCESS | rc=0 >>
/tmp/abc.jjHW
例2:創建用戶
[root@nfs ~]# ansible all -m command -a "useradd user1" # 第一次創建成功
nfs.lxk.com | SUCCESS | rc=0 >>
np1.lxk.com | SUCCESS | rc=0 >>
np2.lxk.com | SUCCESS | rc=0 >>
[root@nfs ~]# ansible all -m command -a "useradd user1" #第二次創建相同用戶失敗
nfs.lxk.com | FAILED | rc=9 >>
useradd: user ‘user1‘ already existsnon-zero return code
np1.lxk.com | FAILED | rc=9 >>
useradd: user ‘user1‘ already existsnon-zero return code
np2.lxk.com | FAILED | rc=9 >>
useradd: user ‘user1‘ already existsnon-zero return code
用加條件判斷創建用戶失敗,因||是直接發給目標主機內核運行,不是經由shell運行,而||是shell的內置命令。
[root@nfs ~]# ansible all -m command -a "id user1 || useradd user1"
nfs.lxk.com | FAILED | rc=1 >>
id: extra operand ‘||’
Try ‘id --help‘ for more information.non-zero return code
np1.lxk.com | FAILED | rc=1 >>
id: extra operand ‘||’
Try ‘id --help‘ for more information.non-zero return code
np2.lxk.com | FAILED | rc=1 >>
id: extra operand ‘||’
Try ‘id --help‘ for more information.non-zero return code
6.3 shell模塊:在節點中執行命令
與command模塊很相似,所不同處是它是在shell下運行的。還可使用executable切換至指定node下運行命令。
例:加條件判斷創建用戶
[root@nfs ~]# ansible all -m shell -a "id user1 || useradd user1"
np2.lxk.com | SUCCESS | rc=0 >>
uid=1001(user1) gid=1001(user1) groups=1001(user1)
nfs.lxk.com | SUCCESS | rc=0 >>
uid=1000(user1) gid=1000(user1) groups=1000(user1)
np1.lxk.com | SUCCESS | rc=0 >>
uid=1000(user1) gid=1000(user1) groups=1000(user1)
6.4 group模塊:添加或刪除組
group模塊用法:
[root@nfs ~]# ansible-doc -s group
- name: Add or remove groups
group:
gid: # Optional `GID‘ to set for the group.是否使用自定義的id號
name: # (required) Name of the group to manage. 要管理的組名,必須要定義的。
state: # Whether the group should be present or not on the remote host. 狀態信息,決定是刪除還是添加。創建:present,刪除:absent
system: # If `yes‘, indicates that the group created is a system group. 是否創建系統用戶
示例:創建一個系統組
[root@nfs ~]# ansible np1.lxk.com -m group -a ‘name=mygrp gid=200 system=yes‘
np1.lxk.com | SUCCESS => {
"changed": true, #變更:成功
"gid": 200, #自定義組ID:200
"name": "mygrp", #組名:mygrp
"state": "present", #狀態:添加
"system": true #是否為系統用戶:是
}
示例:刪除組
[root@nfs ~]# ansible np1.lxk.com -m group -a ‘name=mygrp state=absent‘
np1.lxk.com | SUCCESS => {
"changed": true,
"name": "mygrp",
"state": "absent"
}
上面命令重復執行時,changed狀態為false。
[root@nfs ~]# ansible np1.lxk.com -m group -a ‘name=mygrp state=absent‘
np1.lxk.com | SUCCESS => {
"changed": false,
"name": "mygrp",
"state": "absent"
}
6.5 user模塊:管理用戶帳戶
模塊內置命令一堆,請自行查看,基本見名知意。
示例:創建一個用戶,名字為tom,用戶ID為2000,組名為mygrp,shell類型為/bin/bash,狀態為添加。
[root@nfs ~]# ansible np1.lxk.com -m user -a ‘name=tom state=present uid=2000 groups=mygrp shell=/bin/bash‘
np1.lxk.com | SUCCESS => {
"changed": true,
"comment": "",
"create_home": true,
"group": 2000,
"groups": "mygrp",
"home": "/home/tom",
"name": "tom",
"shell": "/bin/bash",
"state": "present",
"system": false,
"uid": 2000
}
示例:修改tom用戶的ID為2020,shell類型為/bin/tcsh
[root@nfs ~]# ansible np1.lxk.com -m user -a ‘name=tom state=present uid=2020 groups=mygrp shell=/bin/tcsh‘
np1.lxk.com | SUCCESS => {
"append": false,
"changed": true,
"comment": "",
"group": 2000,
"groups": "mygrp",
"home": "/home/tom",
"move_home": false,
"name": "tom",
"shell": "/bin/tcsh",
"state": "present",
"uid": 2020
}
6.6 copy模塊
用法:
[root@nfs ~]# ansible-doc -s copy
- name: Copies files to remote locations #復制一個或多個文件至遠程主機
copy:
dest: # (required) Remote absolute path where the file should be copied to. If `src‘ is a directory, this must be a directory too. If `dest‘ is a nonexistent path and if either `dest‘ ends with "/" or `src‘ is a directory, `dest‘ is created. If `src‘ and `dest‘ are files, the parent directory of `dest‘ isn‘t created: the task fails if it doesn‘t already exist.
#復制指定文件至目標遠程需要是絕對路徑。如果src是目錄,dest也必須是目錄。如果dest是一個不存在的路徑,並且dest不以/結尾或者src是個目錄,dest會自動創建。如果src和dest都是多個文件,dest的父目錄沒創建,復制就會失敗。
src: # Local path to a file to copy to the remote server; can be absolute or relative. If path is a directory, it is copied recursively. In this case, if path ends with "/", only inside contents of that directory are copied to destination. Otherwise, if it does not end with "/", the directory itself with all contents is copied. This behavior is similar to Rsync.
#本地需要復制到遠程主機的文件的路徑。可以是絕對路徑,也可以是相對路徑。如果路徑是個目錄,則遞歸復制。如果路徑以/結尾,只復制目錄下的文件至目標路徑。如果不以/結尾,則會把目錄以及其下的內容都復制至目標主機。這種行為類似於rsync。
content: # When used instead of `src‘, sets the contents of a file directly to the specified value. For anything advanced or with formatting also look at the template module.
#如果不使用src而使用content,把文件內容直接指定為content所指定的內容。然後剩下的懶得翻譯了。
owner: # Name of the user that should own the file/directory, as would be fed to `chown‘.
mode: # Mode the file or directory should be.
group: # Name of the group that should own the file/directory, as would be fed to `chown‘.
示例1:通過content指定文件內容並復制至目標主機(若不帶\n,不會自動換行)
[root@nfs ~]# ansible np2.lxk.com -m copy -a ‘dest=/tmp/textfile.txt content="hello,brother!\n"‘
np2.lxk.com | SUCCESS => {
"changed": true,
"checksum": "8634ff795ad950aa9c762c45cc8b07137248002a",
"dest": "/tmp/textfile.txt",
"gid": 0,
"group": "root",
"md5sum": "2252b10979e37d2884855832666fd811",
"mode": "0644",
"owner": "root",
"size": 15,
"src": "~None/.ansible/tmp/ansible-tmp-1528471338.21-89043902941123/source", #ansible會把給定的源生成一個臨時源當做源文件復制至目標位置。
"state": "file",
"uid": 0
}
目標主機查看文件內容:
[root@np2 ~]# cat /tmp/textfile.txt
hello,brother!
示例2:復制本地/etc/fstab至np1.lxk.com的/tmp目錄下,改名為fstab.txt,屬主改為user2,權限0600.(user2需先創建)
[root@nfs ~]# np1.lxk.com all -m copy -a ‘src=/etc/fstab dest=/tmp/fstab.txt owner=user2 mode=0600‘
np1.lxk.com | SUCCESS => {
"changed": true,
"checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"dest": "/tmp/fstab.txt",
"gid": 0,
"group": "root",
"md5sum": "5aee64ae648da49b3b16e2b9ea70d279",
"mode": "0600",
"owner": "user2",
"size": 595,
"src": "~None/.ansible/tmp/ansible-tmp-1528518314.71-128514426299583/source",
"state": "file",
"uid": 1024
}
查看目標主機上的文件:
[root@np1 ~]# ll /tmp
total 4
-rw------- 1 user2 root 595 Jun 9 12:25 fstab.txt
6.7 fetch模塊
[root@nfs ~]# ansible-doc -s fetch
- name: Fetches a file 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‘
#(必須項)要保存文件的目錄。如指定的目錄為/backup,遠程主機host.example.com上的/etc/profile文件會保存在本地/backup/host.example.com/etc/profile
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.
#遠程主機需要fetch的文件,必須是文件,不能是目錄。以後可能會支持目錄。
示例1:從遠程主機np1.lxk.com上復制/etc/fstab至本地/tmp目錄下
[root@nfs ~]# ansible np1.lxk.com -m fetch -a ‘src=/etc/fstab dest=/tmp/‘
np1.lxk.com | SUCCESS => {
"changed": true,
"checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"dest": "/tmp/np1.lxk.com/etc/fstab",
"md5sum": "5aee64ae648da49b3b16e2b9ea70d279",
"remote_checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"remote_md5sum": null
}
示例2:從所有可控的遠程主機上復制/etc/fstab至本地/tmp目錄下
[root@nfs ~]# ansible all -m fetch -a ‘src=/etc/fstab dest=/tmp/‘
np1.lxk.com | SUCCESS => {
"changed": false,
"checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"dest": "/tmp/np1.lxk.com/etc/fstab",
"file": "/etc/fstab",
"md5sum": "5aee64ae648da49b3b16e2b9ea70d279"
}
np2.lxk.com | SUCCESS => {
"changed": true,
"checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"dest": "/tmp/np2.lxk.com/etc/fstab",
"md5sum": "5aee64ae648da49b3b16e2b9ea70d279",
"remote_checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"remote_md5sum": null
}
nfs.lxk.com | SUCCESS => {
"changed": true,
"checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"dest": "/tmp/nfs.lxk.com/etc/fstab",
"md5sum": "5aee64ae648da49b3b16e2b9ea70d279",
"remote_checksum": "e634b64dbf499a1c2f14ade1dc9fc0d932b93093",
"remote_md5sum": null
}
查看本地目錄:
[root@nfs ~]# tree /tmp
/tmp
├── issue.txt
├── nfs.lxk.com
│?? └── etc
│?? └── fstab
├── np1.lxk.com
│?? └── etc
│?? └── fstab
└── np2.lxk.com
└── etc
└── fstab
6 directories, 4 files
6.8 file模塊:修改文件的屬性信息
[root@nfs ~]# ansible-doc -s file
- name: Sets attributes of files
file:
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). #在兩種情況下強制創建鏈接:源文件不存在(隨後會出現)或目標存在且是文件(將會取消path指定的文件並創建鏈接)
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‘). #改變文件或目錄的權限
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. Aliases: `dest‘, `name‘ #必須項。要修改的文件的路徑
recurse: # recursively set the specified file attributes (applies only to directories) #遞歸地設置文件屬性
src: # path of the file to link to (applies only to `state=link‘ and `state=hard‘). Will accept absolute, relative and nonexisting paths. Relative paths are not expanded.
#要鏈接到的文件路徑(只適用於“state=link”和“state=hard”)。將接受絕對路徑、相對路徑和不存在路徑。相對路徑沒有展開。
state: # 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‘, the file 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 `link‘, the symbolic link will be created or changed. Use `hard‘ for hardlinks. If `absent‘, directories will be recursively deleted, and files or symlinks will be unlinked. Note that `absent‘ will not cause `file‘ to fail if the `path‘ does not exist as the state did not change. 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).
#如果是目錄,父目錄不存在時會自動創建。
#如果是文件,文件不存在時不會創建。
#如果是鏈接,將會創建或者改變。
#如果是absent,目錄將會被遞歸刪除,文件或鏈接會被取消鏈接。
#如果是touch,不存在的文件將會被創建。目錄將會更改訪問時間和改變時間。
示例1:修改np1.lxk.com主機/tmp/fstab.txt的屬主為mygrp,權限為660
[root@nfs ~]# ansible np1.lxk.com -m file -a ‘path=/tmp/fstab.txt group=mygrp mode=0660‘
np1.lxk.com | SUCCESS => {
"changed": true,
"gid": 200,
"group": "mygrp",
"mode": "0660",
"owner": "user2",
"path": "/tmp/fstab.txt",
"size": 595,
"state": "file",
"uid": 1024
}
查看目標主機文件屬性:
[root@np1 ~]# ll -d /tmp/fstab.txt
-rw-rw---- 1 user2 mygrp 595 Jun 9 12:25 /tmp/fstab.txt
示例2:為np1.lxk.com主機的/tmp/fstab.txt創建軟鏈接/tmp/fstab.link
[root@nfs ~]# ansible np1.lxk.com -m file -a ‘path=/tmp/fstab.link src=/tmp/fstab.txt state=link‘
np1.lxk.com | SUCCESS => {
"changed": true,
"dest": "/tmp/fstab.link",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"size": 14,
"src": "/tmp/fstab.txt",
"state": "link",
"uid": 0
}
示例3:在np1.lxk.com的/tmp目錄下創建目錄file.dir,權限為770
[root@nfs ~]# ansible np1.lxk.com -m file -a ‘path=/tmp/file.dir mode=0770 state=directory‘
np1.lxk.com | SUCCESS => {
"changed": true,
"gid": 0,
"group": "root",
"mode": "0770",
"owner": "root",
"path": "/tmp/file.dir",
"size": 4096,
"state": "directory",
"uid": 0
}
6.9 get_url模塊:下載文件
示例:下載一個文件至np1.lxk.com的/tmp目錄下
[root@nfs ~]# ansible np1.lxk.com -m get_url -a ‘dest=/tmp/ url=https://mirrors.aliyun.com/centos/7.5.1804/paas/x86_64/openshift-origin36/jq-devel-1.5-1.el7.x86_64.rpm‘
np1.lxk.com | SUCCESS => {
"changed": true,
"checksum_dest": null,
"checksum_src": "c566cb3df854f4551da1ab7f642e96889b77439c",
"dest": "/tmp/jq-devel-1.5-1.el7.x86_64.rpm",
"gid": 0,
"group": "root",
"md5sum": "43f5092eadb4855fb780e67244d997df",
"mode": "0644",
"msg": "OK (6472 bytes)",
"owner": "root",
"size": 6472,
"src": "/tmp/tmpwix52V",
"state": "file",
"status_code": 200,
"uid": 0,
"url": "https://mirrors.aliyun.com/centos/7.5.1804/paas/x86_64/openshift-origin36/jq-devel-1.5-1.el7.x86_64.rpm"
}
查看目標主機/tmp下的文件:
[root@np1 ~]# ls /tmp
file.dir fstab.link fstab.txt jq-devel-1.5-1.el7.x86_64.rpm
6.10 cron模塊:創建周期性計劃任務
示例1:創建一個時間同步的任務,每5分鐘運行一次。
[root@nfs ~]# ansible np1.lxk.com -m cron -a "minute=*/5 job=‘/usr/sbin/ntpdate 192.168.200.254 &> /dev/null‘ name=timesync"
np1.lxk.com | SUCCESS => {
"changed": true,
"envs": [],
"jobs": [
"timesync"
]
}
目標主機上查看任務:
[root@np1 ~]# crontab -l
#Ansible: timesync #註明是由ansible生成的,標識名為timesync
*/5 * * * * /usr/sbin/ntpdate 192.168.200.254 &> /dev/null
示例2:刪除剛才創建的計劃任務
ansible刪除計劃任務是根據name所定義的名字來標識的。
[root@nfs ~]# ansible np1.lxk.com -m cron -a "state=absent name=timesync"
np1.lxk.com | SUCCESS => {
"changed": true,
"envs": [],
"jobs": []
}
查看目標主機計劃任務列表為空。
ansible基礎與部分模塊應用