ansible安装及使用
0. 环境说明
环境 | 版本 |
---|---|
操作系统 | CentOS Linux release 7.6.1810 虚拟机 |
ansible版本 | ansible 2.4.2.0 |
1. 配置SSH免密通信 - “ssh-keygen”的基本用法
参考文档:配置SSH免密通信 - “ssh-keygen”的基本用法
ssh-keygen 生成公钥密码
本文使用的测试机器为虚拟机:
A服务器(192.168.65.129)-master
B服务器 (192.168.65.130)-slave
服务器A-master | 服务器B-slave |
---|---|
192.168.65.129 | 192.168.65.130 |
ssh-keygen工具生成 私钥文件 id_rsa ,公钥文件 id_rsa.pub 秘钥对在A机上执行
ssh-copy-id 把A机的公钥发给B,在A机上执行
[root@localhost ansible_129]# ssh-keygen -t rsa -f ~/.ssh/id_rsa -C "ansible_test"
# ~密钥类型 ~密钥文件路径及名称 ~备注信息
# 执行 ssh-keygen -t rsa -f ~/.ssh/id_rsa -C "ansible_test" 时,一直会车就可以了。
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase): #回车
Enter same passphrase again: #回车
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is: #回车
SHA256:a157SKmB8IFgTEEhan0fR0ImtCM1v8Y0eMQl2ngVr+A ansible_test
The key's randomart image is:
+---[RSA 2048]----+
|.+=o.=o*.=. |
|..= . %.= . |
|.o + O X . . |
|. = X * . |
| o ES. . |
| + ..o |
| o+.. |
| o..... |
| . .. |
+----[SHA256]-----+
[root@localhost ansible_129]#
查看ssh-keygen生成的秘钥对
[root@localhost ansible_129]# ll
总用量 24
-rw------- 1 root root 394 10月 14 14:15 authorized_keys #存放其他机器公钥,可使其他服务器免密登陆本服务器,可复制其他master服务器中id_rsa.pub中内容到此文件,注意换行符
-rw------- 1 root root 1675 10月 22 21:01 id_rsa #本机私钥
-rw-r--r-- 1 root root 394 10月 22 21:01 id_rsa.pub #本机公钥
-rw------- 1 root root 353 10月 19 10:33 known_hosts #每个访问过的公钥记录在内
[root@lishuaijie .ssh]#
ssh-copy-id把A的公钥发送给B
默认用法是: ssh-copy-id root@192.168.65.130
下面命令已指定要拷贝的本地文件、远程主机的IP+用户名+端口号
[root@localhost ansible_129]# ssh-copy-id -i ~/.ssh/id_rsa.pub -p 22 root@192.168.65.130
# 指定要拷贝的本地文件、远程主机的IP+用户名+端口号
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host '192.168.65.129 (192.168.65.130)' can't be established.
ECDSA key fingerprint is SHA256:X4FfRvAWWwjqHbPTYSV/FQIIVDJAsWq6CJEJQgjQxTs.
ECDSA key fingerprint is MD5:a8:ce:f5:5f:3e:9d:ac:79:8b:0d:2a:9c:44:89:70:96.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.65.130's password: #输入密码
Number of key(s) added: 1
Now try logging into the machine, with: "ssh -p '22' 'root@192.168.65.130'"
and check to make sure that only the key(s) you wanted were added.
[root@lishuaijie .ssh]# ssh -p '22' 'root@192.168.65.130' #已可以免密登陆
Last login: Sun Oct 20 05:06:34 2019 from 192.168.65.129
[root@localhost ~]#
这个过程就是 A服务器(192.168.65.129)-master 上的公钥文件 /root/.ssh/id_rsa.pub 中的内容,写入到 B服务器(192.168.65.130).-slave的**/root/.ssh/authorized_keys**中去。
也可以 直接复制黏贴 到B服务器(192.168.65.130).-slave的 /root/.ssh/authorized_keys中去
2. ansible下载及安装
ansible离线下载及安装
ansible_2.6.3.tar.gz我的CSND可下载 😃😃😃,需要3个CSND积分
也可以在https://releases.ansible.com/ansible/中下载最新的版本,嗯嗯,都行:(
离线安装方式
# tar -zxvf ansible_2.6.3.tar.gz
# cd ansible
# python setup.py install
ansible在线安装
在线安装命令,以Centos 7为例
# yum install -y ansible
3. ansible目录机构
配置文件: /etc/ansible/
执行文件目录: /usr/bin/
lib依赖库: /usr/lib/python2.7/site-packages/ansible/
help文件: /usr/lib/python2.7/site-packages/ansible
4. ansible远程连接方式
Inventory默认位置为/etc/ansible/hosts,但是一般都会使用 -i 参数进行指定,例如:
[root@localhost ansible_129]# ansible -i ./hosts all -m ping
192.168.65.130 | SUCCESS => {
"changed": false,
"ping": "pong"
}
[root@localhost ansible_129]#
Inventory 常用内置参数
参数 | 用途 | 例子 |
---|---|---|
ansible_ssh_host | 定义host ssh地址 | ansible_ssh_host=192.168.65.130 |
ansible_ssh_port | 定义hots ssh端口 | snsible_ssh_port=10011 |
ansible_ssh_user | 定义hosts ssh 认证用户 | ansible_ssh_user=cwk |
ansible_ssh_pass | 定义hosts ssh认证密码 | ansible_ssh_pass=123456 |
ansible_duso | 定义hosts sudo的用户 | ansible_sudo=michael |
ansible_sdo_pass | 定义hosts sudo密码 | ansible_sudo_pass=“123456” |
ansible_sudo_exe | 定义hosts duso 路径 | ansible_sudo_exe=/usr/bin/sudo |
ansible_ssh_private_key_file | 定义hosts私钥 | ansible_ssh_private_key_file=/root/.ssh/id_rsa |
ansible_shell_type | 定义hosts shell类型 | ansible_shell_type=bash |
ansible_python_interpreter | 定义hosts任务执行python的路径 | ansible_python_interpreter=/usr/bin/python2.6 |
ansible_interpreter | 定义hosts其他语言解析器路径 | ansible_interpreter=/usr/bin/ruby |
使用用户名密码
[vm]
192.168.65.130 ansible_ssh_user=root ansible_ssh_pass=123456 ansible_ssh_port=22 server_id=1
使用公钥
[vm]
192.168.65.130 ansible_ssh_user=root ansible_ssh_private_key_file=./id_rsa ansible_ssh_port=22 server_id=1
5. ansible-doc用法
查看帮助手册:ansible-doc -a
查指定模块的帮助:ansible-doc -s 模块名
ansible-doc -s setup 查看setup模块的帮助信息
ansible-doc -l
ansible-doc -s file
Options:
参数 | 释义 | 中文释义 |
---|---|---|
-a, --all | Show documentation for all modules | 显示所有模块 |
-C, --check | don’t make any changes; instead, try to predict some | 检测并不发生改变,可以预测一些错误用于测试使用 |
-h, --help | show this help message and exit | 显示帮助信息并退出 |
-l, --list | List available modules | 列出所有可用模块列表 |
-M MODULE_PATH, --module-path=MODULE_PATH | specify path(s) to module library (default=None) | 指定模块库的路径(默认值=None) |
-s, --snippet | Show playbook snippet for specified module(s) | 显示指定模块的playbook(剧本)代码段 |
-v, --verbose | verbose mode (-vvv for more, -vvvv to enable connection debugging) | 详细显示(-vvv 表示更详细,-vvvv 启用连接调试) |
–version | show program’s version number and exit | 显示程序的版本号并退出 |
例如需要查看copy模块
[root@localhost ansible_129]# ansible-doc -s copy
- name: Copies files to remote locations
copy:
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'.
backup: # Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
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.
decrypt: # This option controls the autodecryption of source files using vault.
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.
directory_mode: # When doing a recursive copy set the mode for the directories. If this is not set we will use the system defaults. The mode is only set on
directories which are newly created, and will not affect those that already existed.
follow: # This flag indicates that filesystem links in the destination, if they exist, should be followed.
force: # the default is `yes', which will replace the remote file when contents are different than the source. If `no', the file will only be
transferred if the destination does not exist.
group: # Name of the group that should own the file/directory, as would be fed to `chown'.
local_follow: # This flag indicates that filesystem links in the source tree, if they exist, should be followed.
mode: # Mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers (like 0644). 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'.
remote_src: # If `no', it will search for `src' at originating/master machine. If `yes' it will go to the remote/target machine for the `src'. Default is
`no'. Currently `remote_src' does not support recursive copying.
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.
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.
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.
validate: # The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in
the example below. The command is passed securely so shell features like expansion and pipes won't work.
6. ansible基本命令
ansible 的库文件hosts 和 秘钥id_rsa在同一文件夹
ansible的语法格式
标准格式:ansible <pattern_goes_here> -m <module_name> -a <arguments>
pattern_goes_here: 可以是某一个主机IP(如192.168.1.128)或者是hosts中的组名(web.server),192.168.1.*代表所有但是前提是hosts文件里面已经做好了定义如192.168.1.[1:254]这样就是执行的192.168.1.1-192.168.1.254,同时制定多个组或者多个ip使用;分割,用!表示非(如web.server:!data.server表示在web.server主机组里面但是不在data.server主机组里面的主机IP),用&表示交集部分,可以指定分组的下标或切片(如web.server[1],就是这个主机组第二个主机IP,需要主机的是超过了范围就无法匹配了),可以用~开头来使用正则(如:~(web|data).*\.server\.com)。需要注意的是如果系统用的是zsh,有这些类似于*,!,[等这些特殊符号需要用单引号包裹。
module_name: 要执行的模块名称,当然 -m 模块名称 这里在语句中是可选的,默认是command,如ansible all -a "/bin/echo hello"
arguments:要执行的命令语句
其他主要参数:
-u username #指定ssh连接的用户名,即执行后面命令的用户
-k #如果是普通用户运行ansible,当需要root权限执行的话,-k参数用来输入密码
-i inventory_file #指定所使用的用户组所在的文件,默认是/etc/ansible/hosts
-f number #指定并发数,并发量大的时候,提高该数字值,如 -f 10,默认是5个。
-t #输出结果保存路径
-K #sudo密码(如果执行命令需要使用sudo用户的话,需要-u执行用户,用-K执行输入sudo密码)
--private-key=key_name #如果是用非默认的id_rsa来当私钥的话,可以指定一个私钥文件。
模块
ping模块
[root@localhost ansible_129]# ansible -i ./hosts all -m ping
192.168.65.130 | SUCCESS => {
"changed": false,
"ping": "pong"
}
[root@localhost ansible_129]#
copy模块
拷贝服务器A上文件到 服务器B
[root@localhost ansible_129]# ansible vm -m copy -a "src=/root/zabbix-file/zabbix.yml dest=/home/dest owner=root group=root mode=755 backup=yes"
192.168.65.130 | SUCCESS => {
"backup_file": "/home/dest/zabbix.yml.19403.2019-10-16@10:52:31~",
"changed": true,
"checksum": "94ebcb24c6e52926597cbc292192ea8eb94fe8ff",
"dest": "/home/dest/zabbix.yml",
"gid": 0,
"group": "root",
"md5sum": "cea4573b31c40cd645475fc243b12663",
"mode": "0755",
"owner": "root",
"size": 2398,
"src": "/root/.ansible/tmp/ansible-tmp-1571223149.64-63657829646806/source",
"state": "file",
"uid": 0
}
[root@localhost ansible_129]#
backup参数 : 当远程主机的目标路径中已经存在同名文件, 并且与ansible主机中的文件内容不同时,是否对远程主机的文件进行备份,可选值有yes和no,当设置为yes时,会先备份远程主机中的文件,然后再将ansible主机中的文件拷贝到远程主机。
file模块
传建文件夹
[root@localhost ansible_129]# ansible 188.131.128.138 -m file -a 'path=/home/dest state=directory'
188.131.128.138 | SUCCESS => {
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/home/dest",
"size": 4096,
"state": "directory",
"uid": 0
}
[root@localhost ansible_129]#
touch生成文件
[root@localhost ansible_129]# ansible -i ./hosts 192.168.65.130 -m file -a 'path=/tmp/test state=touch'
192.168.65.130 | SUCCESS => {
"changed": true,
"dest": "/tmp/test",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"size": 0,
"state": "file",
"uid": 0
}
[root@localhost ansible_129]#
shell模块
[root@localhost ansible_129]# ansible -i ./hosts vm -m shell -a 'ls -l /home/dest'
192.168.65.130 | SUCCESS | rc=0 >>
total 146352
drwxrwxr-x 16 500 500 4096 Oct 19 20:54 ansible
-rw-r--r-- 1 root root 149850681 Oct 19 20:42 ansible_2.6.3.tar.gz
-rw-r--r-- 1 root root 0 Oct 16 14:09 modelshelltest1.log
-rw-r--r-- 1 root root 0 Oct 16 14:09 modelshelltest.log
drwxr-xr-x 2 root root 34 Oct 22 21:56 shanchu
-rwxr-xr-x 1 root root 2398 Oct 16 11:02 zabbix.yml
-rwxr-xr-x 1 root root 2406 Oct 16 11:02 zabbix.yml.19587.2019-10-16@11:02:19~
[root@localhost ansible_129]#
7. ansible-playbook语法
范例
[root@localhost playbook]# cat update_playbook.yml
- hosts: test
vars:
user_name: cwk
soft_version: 2.1
dest_decoder_path: /home/{{user_name}}/decoder
localhost_decoder_path: /home/cwk/decoder
ansible_path: /home/cwk/ansible
inventory_path: /home/cwk/ansible/ansible_scripts/inventory
tasks:
- name: 1.Copying newest docker image to Remote server....
synchronize: src={{localhost_decoder_path}}/cwk_server-gpu.v{{decoder_version}}.tar.gz dest={{dest_decoder_path}}/ mode=push
- name: 2.Copying scripts to Remote Server....
copy:
src: "{{ item }}"
dest: "{{ dest_decoder_path }}"
mode: 0777
with_fileglob:
- "{{ansible_path}}/ansible_scripts/*.sh"
- name: 2.1.Copying specific volumes file to dest.
copy: src={{inventory_path}}/{{server_id}}.volumes dest={{dest_decoder_path}}/volumes
- name: 3.Loading Docker image...
shell: "./load.sh {{decoder_version}}"
args:
chdir: "{{ dest_decoder_path }}"
- name: 4.Restart dockers
shell: "./remove_run_all.sh {{decoder_version}}"
args:
chdir: "{{ dest_decoder_path }}"
[root@localhost playbook]#
update_playbook.yml中用到的模块
synchronize模块
synchronize: src={{localhost_decoder_path}}/cwk_server-gpu.v{{decoder_version}}.tar.gz dest={{dest_decoder_path}}/ mode=push
[root@localhost playbook]# ansible-doc -s synchronize
[DEPRECATION WARNING]: [defaults]hostfile option, The key is misleading as it can also be a list of hosts, a directory or a list of paths . This feature will be removed in
version 2.8. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
- name: A wrapper around rsync to make common tasks in your playbooks quick and easy.
synchronize:
archive: # Mirrors the rsync archive flag, enables recursive, links, perms, times, owner, group flags and -D.
checksum: # Skip based on checksum, rather than mod-time & size; Note that that "archive" option is still enabled by default - the "checksum" option
will not disable it.
compress: # Compress file data during the transfer. In most cases, leave this enabled unless it causes problems.
copy_links: # Copy symlinks as the item that they point to (the referent) is copied, rather than the symlink.
delete: # Delete files in `dest' that don't exist (after transfer, not before) in the `src' path. This option requires `recursive=yes'.
dest: # (required) Path on the destination host that will be synchronized from the source; The path can be absolute or relative.
dest_port: # Port number for ssh on the destination host. Prior to ansible 2.0, the ansible_ssh_port inventory var took precedence over this value.
dirs: # Transfer directories without recursing
existing_only: # Skip creating new files on receiver.
group: # Preserve group
links: # Copy symlinks as symlinks.
mode: # Specify the direction of the synchronization. In push mode the localhost or delegate is the source; In pull mode the remote host in context
is the source.
owner: # Preserve owner (super user only)
partial: # Tells rsync to keep the partial file which should make a subsequent transfer of the rest of the file much faster.
perms: # Preserve permissions.
recursive: # Recurse into directories.
rsync_opts: # Specify additional rsync options by passing in an array.
rsync_path: # Specify the rsync command to run on the remote host. See `--rsync-path' on the rsync man page.
rsync_timeout: # Specify a --timeout for the rsync command in seconds.
set_remote_user: # put user@ for the remote paths. If you have a custom ssh config to define the remote user for a host that does not match the inventory user,
you should set this parameter to "no".
src: # (required) Path on the source host that will be synchronized to the destination; The path can be absolute or relative.
times: # Preserve modification times
use_ssh_args: # Use the ssh_args specified in ansible.cfg
verify_host: # Verify destination host key.
[root@localhost playbook]#
copy模块
copy:
src: "{{ item }}"
dest: "{{ dest_decoder_path }}"
mode: 0777
with_fileglob:
- "{{ansible_path}}/ansible_scripts/*.sh"
- name: 2.1.Copying specific volumes file to dest.
copy: src={{inventory_path}}/{{server_id}}.volumes dest={{dest_decoder_path}}/volumes
文件循环(with_file, with_fileglob)
with_file 是将每个文件的文件内容作为item的值
with_fileglob 是将每个文件的全路径作为item的值, 在文件目录下是非递归的, 如果是在role里面应用改循环, 默认路径是roles/role_name/files_directory
例如:
copy:
src: “{{ item }}”
dest: “{{ dest_decoder_path }}”
mode: 0777
with_fileglob:
- “{{ansible_path}}/ansible_scripts/*.sh”
Shell模块
- name: 3.Loading Docker image...
shell: "./load.sh {{decoder_version}}"
args:
chdir: "{{ dest_decoder_path }}"
- name: 4.Restart dockers
shell: "./stop_rm_run_all.sh {{decoder_version}}"
args:
chdir: "{{ dest_decoder_path }}"
args 模块特有的参数
chdir 执行shell命令前,首先进入指定的目录