ansible 常用模块
1) 主机连通性
# 批量添加SSH认证
# 场景一:所有机器密码相同 资源有限 一台机器做测试
cat /etc/ansible/hosts
[testserver]
172.16.66.3
# 执行命令
ansible all -m authorized_key -a "user=root key='{{ lookup('file','/root/.ssh/id_rsa.pub')}}' path='/root/.ssh/authorized_keys' manage_dir=no" --ask-pass -c paramiko
# 命令说明
user=root #将秘钥推送到远程主机的哪个用户下
key='{{ lookup('file','/root/.ssh/id_rsa.pub')}}' #指定要推送的秘钥文件所在的路径
path='/root/.ssh/authorized_keys' #将秘钥推送到远程主机的哪个目录下并重命名
manage_dir=no #指定模块是否应该管理authorized_keys文件所在的目录,如果设置为yes,模块会创建目录,以及设置一个已存在目录的拥有者和权限。如果通过 path 选项,重新指定了一个 authorized key 文件所在目录,那么应该将该选项设置为 no
exclusive [default: no]: #是否移除 authorized_keys 文件中其它非指定 key
state (Choices: present, absent) [Default: present]: #present 添加指定 key 到 authorized_keys 文件中;absent 从 authorized_keys 文件中移除指定 key
ansible 主机执行命令前后
[root@centos yamls]# cat ~/.ssh/known_hosts
[root@centos yamls]# ansible all -m authorized_key -a "user=root key='{{ lookup('file','/root/.ssh/id_rsa.pub')}}' path='/root/.ssh/authorized_keys' manage_dir=no" --ask-pass -c paramiko
SSH password:
paramiko: The authenticity of host '172.16.66.3' can't be established.
The ssh-rsa key fingerprint is 30c04551d32ab8fba5048d95c52ed674.
Are you sure you want to continue connecting (yes/no)?
yes
172.16.66.3 | SUCCESS => {
"changed": true,
"comment": null,
"exclusive": false,
"gid": 0,
"group": "root",
"key": "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAoaMcFjOTjlNUbtReh3jo7GOTTXTZ8g2H0Jo9FadLuOQGhH9zMRL/6hsIlzD2U/HwutdKnpK7tUBVymdYovNq/+/1BJHnD+yVlvGTaQuWJhooOTMKU/p+JKH/Vc0+jbS2qUEXQCtXVl4LEUwCSCA7mjR+N5g2loxpxLd1+3BKN/tzwWGQpNnFWmEYnBJK25O1n3lfOFQdks/yl2ayu5pUwh1Unvel+znCDx4NgOEcRmOwAZu+bGn4XY1S9ra1uPaOquNjJBb59aEPuEu6F0camXsOrrhhz52Su2f4C3jV8eejydqaiqd3OsiFZ90XzVN5+8bhwqJp6o1xql7DUDillw== root@centos",
"key_options": null,
"keyfile": "/root/.ssh/authorized_keys",
"manage_dir": false,
"mode": "0600",
"owner": "root",
"path": "/root/.ssh/authorized_keys",
"secontext": "unconfined_u:object_r:ssh_home_t:s0",
"size": 394,
"state": "file",
"uid": 0,
"unique": false,
"user": "root",
"validate_certs": true
}
[root@centos yamls]# cat ~/.ssh/known_hosts
172.16.66.3 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDB9VclxxCDjq2A2oRwiIT9wplvJxPaew3OxRD8DpTZLCAD9zQfoaH+S6ddk30kp/lHoxxM1E1L61w4SYj1f9qN/iR3p4urWKNrWwOILUhoyfmNMcXpeu6QOHTQwh462cNNU4hgpvi/jAV8tIAley1PpXweu9xjCK0yDMgbfJaqUdOxmXjW93mF3qNh4aRHQageKSck0K/WesyUKpWS+FRXs5Eirobk0F0tMfjCfWhMouFxbbOC2y+CXfG3rg+viHjuZC+QsX47YUpqhvXUUCyyadxVRxSnmKAYWdIy4/1TtIqI7UhO4eZB9Ops4Act6WDMrHooPR2295+aqlBJVBkX
[root@centos yamls]#
# 可见被管理主机的秘钥被拿回
被管理主机执行命令前后
# 执行命令前
[root@centos7 .ssh]# cat authorized_keys
# 执行命令后
[root@centos7 .ssh]# cat authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAoaMcFjOTjlNUbtReh3jo7GOTTXTZ8g2H0Jo9FadLuOQGhH9zMRL/6hsIlzD2U/HwutdKnpK7tUBVymdYovNq/+/1BJHnD+yVlvGTaQuWJhooOTMKU/p+JKH/Vc0+jbS2qUEXQCtXVl4LEUwCSCA7mjR+N5g2loxpxLd1+3BKN/tzwWGQpNnFWmEYnBJK25O1n3lfOFQdks/yl2ayu5pUwh1Unvel+znCDx4NgOEcRmOwAZu+bGn4XY1S9ra1uPaOquNjJBb59aEPuEu6F0camXsOrrhhz52Su2f4C3jV8eejydqaiqd3OsiFZ90XzVN5+8bhwqJp6o1xql7DUDillw== root@centos
[root@centos7 .ssh]#
# 可见ansible主机的公钥已经过来了
#场景二 多台主机密码不同
Ansible主机配置文件
[testserver]
ansible_ssh_user="root" ansible_ssh_host=172.16.66.3 ansible_ssh_port=22 ansible_ssh_pass="你的root密码"
编写推送公钥的YML
[root@centos yamls]# cat push-ssh.yaml
# Using alternate directory localtions
- hosts: '*'
user: root
tasks:
- name: ssh-copy
authorized_key:
user=root
key="{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"
tags:
- sshkey
[root@centos yamls]#
# 使用 playbook将公钥推送到客户机
[root@centos yamls]# ansible-playbook push-ssh.yaml
PLAY [*] **********************************************************************************************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************************************************************************************
fatal: [ansible_ssh_user=root]: FAILED! => {"msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host."}
to retry, use: --limit @/etc/ansible/yamls/push-ssh.retry
PLAY RECAP ********************************************************************************************************************************************************************************************************
ansible_ssh_user=root : ok=0 changed=0 unreachable=0 failed=1
# ansible 默认配置可能会出现以上报错
# 原因是:初始ssh访问客户机的时候,都会有检验公钥的提示。只要配置禁用即可
# 配置文件修改
[root@centos yamls]# vim /etc/ansible/ansible.cfg
# uncomment this to disable SSH key host checking
host_key_checking = False
[root@centos yamls]# grep 'host_key_checking' /etc/ansible/ansible.cfg
host_key_checking = False
[root@centos yamls]# ansible-playbook push-ssh.yaml
PLAY [*] **********************************************************************************************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************************************************************************************
ok: [ansible_ssh_user=root]
TASK [ssh-copy] ***************************************************************************************************************************************************************************************************
changed: [ansible_ssh_user=root]
PLAY RECAP ********************************************************************************************************************************************************************************************************
ansible_ssh_user=root : ok=2 changed=1 unreachable=0 failed=0
# 可见执行成功
# 测试是否推送公钥成功
[root@centos yamls]# ansible all -m command -a date
ansible_ssh_user=root | SUCCESS | rc=0 >>
Thu Mar 19 12:51:17 CST 2020
# 被管理主机查看公钥
[root@centos7 .ssh]# echo "" > authorized_keys
[root@centos7 .ssh]# cat authorized_keys
[root@centos7 .ssh]# cat authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAoaMcFjOTjlNUbtReh3jo7GOTTXTZ8g2H0Jo9FadLuOQGhH9zMRL/6hsIlzD2U/HwutdKnpK7tUBVymdYovNq/+/1BJHnD+yVlvGTaQuWJhooOTMKU/p+JKH/Vc0+jbS2qUEXQCtXVl4LEUwCSCA7mjR+N5g2loxpxLd1+3BKN/tzwWGQpNnFWmEYnBJK25O1n3lfOFQdks/yl2ayu5pUwh1Unvel+znCDx4NgOEcRmOwAZu+bGn4XY1S9ra1uPaOquNjJBb59aEPuEu6F0camXsOrrhhz52Su2f4C3jV8eejydqaiqd3OsiFZ90XzVN5+8bhwqJp6o1xql7DUDillw== root@centos
[root@centos7 .ssh]#
##### 注意 #####
因为推送公钥,所以hosts配置在推送完后需要修
由原来
[testserver]
ansible_ssh_user="root" ansible_ssh_host=172.16.66.3 ansible_ssh_port=22 ansible_ssh_pass="你的root密码"
改为
[testserver]
172.16.66.3
#ansible_ssh_user="root" ansible_ssh_host=172.16.66.3 ansible_ssh_port=22 ansible_ssh_pass="你的root密码"
2) command 模块
# 上面添加主机时有用过,这里不做介绍
3)shell 模块
[root@centos yamls]# ansible all -m shell -a 'cat /etc/passwd |grep "nginx"'
ansible_ssh_user=root | SUCCESS | rc=0 >>
nginx:x:998:996:Nginx web server:/var/lib/nginx:/sbin/nologin
[root@centos yamls]#
4)copy 模块
# -m 指定copy模块,-a 指定要执行的文件源目和权限,-o 一行显示
[root@centos yamls]# ansible all -m copy -a 'src=/etc/hosts dest=/tmp/hosts owner=root group=root mode=644' -o
ansible_ssh_user=root | CHANGED => {"changed": true, "checksum": "2c90e08f470a6873b7bc89a883b0ad4984427ff6", "dest": "/tmp/hosts", "gid": 0, "group": "root", "md5sum": "79952221467013992305ccbf7509c1f3", "mode": "0644", "owner": "root", "secontext": "unconfined_u:object_r:admin_home_t:s0", "size": 177, "src": "/root/.ansible/tmp/ansible-tmp-1583372585.64-237919936359978/source", "state": "file", "uid": 0}
[root@centos yamls]#
# 给定内容并生成文件
[root@centos yamls]# ansible all -m copy -a 'content="I am keer\n" dest=/data/name mode=666'
# 内容修改并覆盖备份
[root@centos yamls]# ansible web -m copy -a 'content="I am keerya\n" backup=yes dest=/data/name mode=666'
5)file 模块
# 创建目录
[root@centos yamls]# ansible web -m file -a 'path=/data/app state=directory'
# 创建连接文件
[root@centos yamls]# ansible web -m file -a 'path=/data/bbb.jpg src=aaa.jpg state=link'
# 删除文件
[root@centos yamls]# ansible web -m file -a 'path=/data/a state=absent'
6)fetch 模块
该模块用于从远程某主机获取(复制)文件到本地。
有两个选项:
dest:用来存放文件的目录
src:在远程拉取的文件,并且必须是一个file,不能是目录
[root@centos yamls]# ansible web -m fetch -a 'src=/data/hello dest=/data'
7)cron 模块
该模块适用于管理cron计划任务的。
其使用的语法跟我们的crontab文件中的语法一致,同时,可以指定以下选项:
day= #日应该运行的工作( 1-31, , /2, )
hour= # 小时 ( 0-23, , /2, )
minute= #分钟( 0-59, , /2, )
month= # 月( 1-12, *, /2, )
weekday= # 周 ( 0-6 for Sunday-Saturday,, )
job= #指明运行的命令是什么
name= #定时任务描述
reboot # 任务在重启时运行,不建议使用,建议使用special_time
special_time #特殊的时间范围,参数:reboot(重启时),annually(每年),monthly(每月),weekly(每周),daily(每天),hourly(每小时)
state #指定状态,present表示添加定时任务,也是默认设置,absent表示删除定时任务
user # 以哪个用户的身份执行
# 添加计划任务
[root@centos yamls]# ansible all -m cron -a 'name="ntp update every 5 min" minute=*/5 job="/sbin/ntpdate 172.16.66.3 &> /dev/null"'
# 效果如下
[root@centos7 ansible-tmp-1583349606.75-217018389291924]# crontab -l
#Ansible: ntp update every 5 min
*/5 * * * * /sbin/ntpdate 172.16.66.3 &> /dev/null
# 删除计划任务
① 查看
[root@centos yamls]# ansible web -m shell -a 'crontab -l'
② 删除
[root@centos yamls]# ansible web -m cron -a 'name="df everyday" hour=15 job="df -lh >> /tmp/disk_total &> /dev/null" state=absent'
③ 确认
[root@centos yamls]# ansible web -m shell -a 'crontab -l'
8)yum 模块
[root@centos yamls]# ansible all -m yum -a 'name=ntpdate state=latest' -o
ansible_ssh_user=root | CHANGED => {"changed": true, "msg": "", "rc": 0, "results": ["Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.huaweicloud.com\n * epel: hkg.mirror.rackspace.com\n * extras: mirrors.huaweicloud.com\n * updates: mirrors.huaweicloud.com\nResolving Dependencies\n--> Running transaction check\n---> Package ntpdate.x86_64 0:4.2.6p5-29.el7.centos will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package Arch Version Repository Size\n================================================================================\nInstalling:\n ntpdate x86_64 4.2.6p5-29.el7.centos base 86 k\n\nTransaction Summary\n================================================================================\nInstall 1 Package\n\nTotal download size: 86 k\nInstalled size: 121 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : ntpdate-4.2.6p5-29.el7.centos.x86_64 1/1 \n Verifying : ntpdate-4.2.6p5-29.el7.centos.x86_64 1/1 \n\nInstalled:\n ntpdate.x86_64 0:4.2.6p5-29.el7.centos \n\nComplete!\n"]}
[root@centos yamls]#
# 安装完成后即可返回安装结果
# 被管理机器查看,安装过程中会出现ansible进程
[root@centos7 .ssh]# ps aux | grep yum
root 9843 0.0 0.1 113180 1204 pts/1 Ss+ 13:02 0:00 /bin/sh -c /usr/bin/python /root/.ansible/tmp/ansible-tmp-1583372682.51-231059300419736/yum.py && sleep 0
root 9854 0.0 0.8 189984 8280 pts/1 S+ 13:02 0:00 /usr/bin/python /root/.ansible/tmp/ansible-tmp-1583372682.51-231059300419736/yum.py
root 9855 0.3 3.5 825392 35792 pts/1 Sl+ 13:02 0:00 /usr/bin/python /tmp/ansible_byQQVA/ansible_module_yum.py
root 9890 0.0 0.0 112712 960 pts/0 S+ 13:04 0:00 grep --color=auto yum
[root@centos7 .ssh]# rpm -qa ntpdate
ntpdate-4.2.6p5-29.el7.centos.x86_64
9)service 模块
# 启动
[root@centos7 .ssh]# ansible all -m service -a 'name=nginx state=started enabled=true'
# 关闭
[root@centos7 .ssh]# ansible web -m service -a 'name=nginx state=stopped'
10)user 模块
该模块主要是用来管理用户账号。
其主要选项如下:
comment # 用户的描述信息
createhome # 是否创建家目录
force # 在使用state=absent时, 行为与userdel –force一致.
group # 指定基本组
groups # 指定附加组,如果指定为(groups=)表示删除所有组
home # 指定用户家目录
move_home # 如果设置为home=时, 试图将用户主目录移动到指定的目录
name # 指定用户名
non_unique # 该选项允许改变非唯一的用户ID值
password # 指定用户密码
remove # 在使用state=absent时, 行为是与userdel –remove一致
shell # 指定默认shell
state # 设置帐号状态,不指定为创建,指定值为absent表示删除
system # 当创建一个用户,设置这个用户是系统用户。这个设置不能更改现有用户
uid # 指定用户的uid
# 例:添加一个用户并指定其 uid
[root@centos7 .ssh]# ansible all -m user -a 'name=keer uid=11111'
例:删除用户
# [root@centos7 .ssh]# ansible all -m user -a 'name=keer state=absent' 11)group 模块
# 新建组
[root@centos7 .ssh]# ansible all -m group -a 'name=sanguo gid=12222'
# 删除组
[root@centos7 .ssh]# ansible all -m group -a 'name=sanguo state=absent'
12)script 模块
# 该模块用于将本机的脚本在被管理端的机器上运行
[root@centos7 .ssh]# ansible web -m script -a '/tmp/df.sh
13)setup 模块
# 该模块主要用于收集信息,是通过调用facts组件来实现的。
# facts组件是Ansible用于采集被管机器设备信息的一个功能,我们可以使用setup模块查机器的所有facts信息,可以使用filter来查看指定信息。整个facts信息被包装在一个JSON 格式的数据结构中,ansible_facts是最上层的值。
# facts就是变量,内建变量 。每个主机的各种信息,cpu颗数、内存大小等。会存在facts中的某个变量中。调用后返回很多对应主机的信息,在后面的操作中可以根据不同的信息来做不 同的操作。如redhat系列用yum安装,而debian系列用apt来安装软件。
# ① 查看信息
# 我们可以直接用命令获取到变量的值,具体我们来看看例子
[root@centos7 .ssh]# ansible all -m setup -a 'filter="*mem*"'
# ② 保存信息
[root@centos7 .ssh]# ansible all -m setup -a 'filter="*mem*"' --tree /tmp/facts