lsyf8 发表于 2018-7-30 12:38:12

ansible实战--批量创建运维账户

  一、ansible安装
  1、安装第三方epel源
  centos 5的epel
  #rpm -ivh http://mirrors.sohu.com/fedora-epel/5/x86_64/epel-release-5-4.noarch.rpm
  centos 6的epel
  #rpm -ivh http://mirrors.sohu.com/fedora-epel/6/x86_64/epel-release-6-8.noarch.rpm
  查看系统版本
  # cat /etc/issue

  CentOS>  Kernel \r on an \m
  由于是6版本所以安装6的epel
  2、安装ansible
  yum install ansible
  3、添加主机
  # ls /etc/ansible/
  其中ansible.cfg是配置文件,hosts是管理主机信息
  #cat /etc/ansible/hosts
  
  172.31.2.16
  172.31.2.17 ansible_ssh_port=2208
  ....
  ....
  ....
  4、测试
  #ansible all -m ping
  我遇到的问题如下:
  172.31.2.16 | FAILED >> {
  "failed": true,
  "msg": "Error: ansible requires a json module, none found!",
  "parsed": false
  }
  172.31.2.17 | FAILED >> {
  "failed": true,
  "msg": "Error: ansible requires a json module, none found!",
  "parsed": false
  }
  FAQ:
  1、查阅官方文档说python版本太低
  解决办法:登陆被管理机,升级python至2.6 或 yum install -y python-simplejson
  再次测试,返回如下,表示正常。
  172.31.2.16 | success >> {
  "changed": false,
  "ping": "pong"
  }
  172.31.2.17 | success >> {
  "changed": false,
  "ping": "pong"
  }
  2、默认ansible是使用key验证的,如果使用密码登陆的服务器,使用ansible的话,要不修改ansible.cfg配置文件的
ask_pass      = True给取消注释,要不就在运行命令时候加上-k,这个意思是-k, --ask-pass      ask
for SSH password
  3、如果客户端不在know_hosts里将会报错
  paramiko: The authenticity of host '172.16.2.86' can't be established.
  The ssh-rsa key fingerprint is dbbeccfb56be8dc7ce33c66897abb54f.
  Are you sure you want to continue connecting (yes/no)?
  如果想解决此问题,需要修改ansible.cfg的#host_key_checking = False取消注释
  4、如果出现
# ansible zabbix -m shell -a "echo $TERM" -u denglei --private-key=/root/denglei  
172.17.0.2 | FAILED => FAILED: not a valid DSA private key file
  
172.17.0.4 | FAILED => FAILED: not a valid DSA private key file
  需要你在最后添加参数-k
# ansible zabbix -m shell -a "echo $TERM" -u denglei --private-key=/root/denglei -k  
SSH password:
  
172.17.0.2 | success | rc=0 >>
  
xterm
  

  
172.17.0.4 | success | rc=0 >>
  
xterm
  二、ansible应用(http://www.tuicool.com/articles/AZVJ3qQ)
  1.查看ansible 支持的模块
  #ansible-doc -l
  2.查看ansible模块的使用方法(http://docs.ansible.com/list_of_all_modules.html)
  #ansible-doc -s xxx
  3.实例:批量创建维护账户
  # vi useradd.yml
  ---
  - hosts: all
  user: root
  sudo: no
  vars:
  #password: python -c 'import crypt; print crypt.crypt("devops1232", "fanghanyun")'
  user: fanghanyun
  tasks:
  - name: add user
  action: user name=` user ` password=faJxjj/6hKXPs update_password=always shell=/bin/bash home=/home/` user `
  tags:
  - user
  4.执行ansible-playbook
  #ansible-playbook useradd.yml
页: [1]
查看完整版本: ansible实战--批量创建运维账户