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命令的使用:
[[email protected] ~]# 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
定义主机列表示例:
[[email protected] ~]# tail -2 /etc/ansible/hosts
np[1:2].lxk.com
nfs.lxk.com
获取主机列表:
[[email protected] ~]# ansible all --list-hosts
hosts (3):
np1.lxk.com
np2.lxk.com
nfs.lxk.com
6. ansible的常用模块:
获取模块帮助信息:
[[email protected] ~]# 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模块:探测远程主机
[[email protected] ~]# 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操作
[[email protected] ~]# 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
[[email protected] ~]# 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
[[email protected] ~]# 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:创建临时文件
[[email protected] ~]# 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:创建用户
[[email protected] ~]# 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 >>
[[email protected] ~]# 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的内置命令。
[[email protected] ~]# 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下运行命令。
例:加条件判断创建用户
[[email protected] ~]# 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模块用法:
[[email protected] ~]# 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. 是否创建系统用户
示例:创建一个系统组
[[email protected] ~]# 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 #是否为系统用户:是
}
示例:删除组
[[email protected] ~]# ansible np1.lxk.com -m group -a ‘name=mygrp state=absent‘
np1.lxk.com | SUCCESS => {
"changed": true,
"name": "mygrp",
"state": "absent"
}
上面命令重复执行时,changed状态为false。
[[email protected] ~]# 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,状态为添加。
[[email protected] ~]# 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
[[email protected] ~]# 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模块
用法:
[[email protected] ~]# 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,不会自动换行)
[[email protected] ~]# 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
}
目标主机查看文件内容:
[[email protected] ~]# cat /tmp/textfile.txt
hello,brother!
示例2:复制本地/etc/fstab至np1.lxk.com的/tmp目录下,改名为fstab.txt,属主改为user2,权限0600.(user2需先创建)
[[email protected] ~]# 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
}
查看目标主机上的文件:
[[email protected] ~]# ll /tmp
total 4
-rw------- 1 user2 root 595 Jun 9 12:25 fstab.txt
6.7 fetch模块
[[email protected] ~]# 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目录下
[[email protected] ~]# 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目录下
[[email protected] ~]# 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
}
查看本地目录:
[[email protected] ~]# 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模块:修改文件的属性信息
[[email protected] ~]# 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
[[email protected] ~]# 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
}
查看目标主机文件属性:
[[email protected] ~]# 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
[[email protected] ~]# 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
[[email protected] ~]# 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目录下
[[email protected] ~]# 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下的文件:
[[email protected] ~]# ls /tmp
file.dir fstab.link fstab.txt jq-devel-1.5-1.el7.x86_64.rpm
6.10 cron模块:创建周期性计划任务
示例1:创建一个时间同步的任务,每5分钟运行一次。
[[email protected] ~]# 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"
]
}
目标主机上查看任务:
[[email protected] ~]# crontab -l
#Ansible: timesync #注明是由ansible生成的,标识名为timesync
*/5 * * * * /usr/sbin/ntpdate 192.168.200.254 &> /dev/null
示例2:删除刚才创建的计划任务
ansible删除计划任务是根据name所定义的名字来标识的。
[[email protected] ~]# ansible np1.lxk.com -m cron -a "state=absent name=timesync"
np1.lxk.com | SUCCESS => {
"changed": true,
"envs": [],
"jobs": []
}
查看目标主机计划任务列表为空。
原文地址:http://blog.51cto.com/11975865/2126725