作者:邓聪聪

  查看ansible配置文件下的hosts的文件

[root@ansible-server scripts]# cat /etc/ansible/hosts
[test]
172.16.16.7
172.16.16.8
[root@ansible-server scripts]#

1.生成秘钥对

  ssh-keygen -t dsa -f ~/.ssh/id_dsa -P ''  -q  #生产密钥对,免交互,并安静输出

  这个命令会产生一个公钥(~/.ssh/id_dsa.pub)和密钥(~/.ssh/id_dsa),

  -t dsa:表示使用密钥的加密类型,可以为'rsa'和'dsa'

  -P '':表示不需要密码登录

  -f ~/.ssh/id_dsa:表示密钥存放的路径为${USER}/.ssh/id_dsa

  ssh-copy-id -i ~/.ssh/id_dsa.pub username@ip,hostname  #如果你是单台机器的话,可以使用这种方式把公钥文件传递到对方主机

  使用ansible实现轻量级的批量主机管理-LMLPHP //被控主机下的文件信息

2.使用ansible-playbook来生成推送ymal文件,批量推送

  这里使用到了authoried_keys模块,vi /opt/ssh_key.yaml 

# Using alternate directory locations:
- hosts: test //可以是组也可以是全部
user: root //推送所使用的用户 tasks:
- name: ssh-copy
authorized_key:
user=root
key="{{ lookup('file', '/root/.ssh/id_dsa.pub') }}"

3.测试

[root@ansible-server scripts]# ansible all -m command -a date
172.16.16.8 | SUCCESS | rc= >>
Mon Mar :: EST
172.16.16.7 | SUCCESS | rc= >>
Mon Mar :: EST
[root@ansible-server scripts]#

4.1ansible的各项命令参数的使用

  1.service  #管理的服务必须存在在/etc/init.d/下有的服务脚本

  name=service name  #服务的名称

  state=参数            #停止服务 服务状态信息为过去时 (stared/stoped/restarted/reloaded )

  案例:ansible test -m service -a "name=crond state=restarted"

  2.yum

  name=name       #指定安装的软件

  state=installed    #安装

  案例:ansible test -m yum -a "name=vim state=installed "

  3.copy #将/etc/hosts 文件 传输到各个服务器送,src=文件的源路径,dest=文件的目标路径

  案例:ansible test -m copy -a "src=/etc/hosts dest=/tmp/"

  4.script #脚本模块,在本地执行脚本时,将脚本中的内容传输到远程节点上运行

  案例:ansible all -m script -a "/root/ansible-server/scripts/batch_free.sh"

4.2.剧本格式示例

  剧本的检查 ansible-playbook --syntax-check name.ymal

  剧本彩排 ansible-playbook -C name.ymal

# Using alternate directory locations:
- hosts: test //冒号后面跟参数必须有空格
user: root tasks: //冒号后面没有参数的时候可以省略掉空格
- name: ssh-copy //名称,可以跟多个剧本
authorized_key:
user=root
key="{{ lookup('file', '/root/.ssh/id_dsa.pub') }}"

  使用Ansible的user模块批量修改远程客户机的用户密码 

[root@ansible-server ~]# vi /opt/root_passwd.yaml
---
- hosts: test
gather_facts: false
tasks:
- name: change user passwd
user: name={{ item.name }} password={{ item.chpass | password_hash('sha512') }} update_password=always
with_items:
- { name: 'root', chpass: '' }
- { name: 'test', chpass: '' }

  注意上面在yaml文件中修改了远程客户机的root用户密码, test用户密码.如果还想要修改其他用户密码, 则继续按照上面规则添加即可!

04-07 12:06
查看更多