一、部署之前先进行多主机免密:
#配置ssh免密
例如主机A想免密ssh登陆主机B(10.4.7.11),在主机A上执行如下命令:
ssh-copy-id root@10.4.7.11 #提示输入主机B的密码,回车完成免密。如果还有C和D主机 依次在主机A执行ssh-copy-id root@C和Dip既可,(因为我们规划将主机A作为ansible服务端因此需要对其它节点的主机免密访问)
说明:如果报错可能是由于主机A没有公钥,在主机A上执行ssh-keygen命令生成一个(一直回车就行),
然后在重新执行ssh-copy-id root@10.4.7.11 这一步即可
二、在主机A上部署Ansible(主机A作为Ansible管理主机)
#添加repo
[root@dw01 ~]# yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
#yum安装ansilbe
[root@dw01 ~]# yum install ansible -y
[root@dw01 ~]# rpm -qa ansible
#检查ansible版本
[root@dw01 ~]# ansible --version
ansible 2.9.2
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Aug 4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]
三.添加主机清单
[root@dw01 ~]# vim /etc/ansible/hosts
[all]
10.4.7.10
10.4.7.11
四、测试ansible
ping模块用于测试ansible与被受控端的连通性
[root@m01 ~]# ansible all -m ping
10.4.7.10 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong" }
10.4.7.11 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
changed": false,
"ping": "pong" }
五、基于密码连接
// 方式一、主机+端口+密码
vim /etc/ansible/hosts
[webservers]
10.0.0.41 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='123456'
10.0.0.51 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass='123456'
六、ansible简单运用
#主机A上批量执行iptables策略其中的all就是/etc/ansible/hosts中添加的模块:
ansible all -m shell -all "iptables -t nat -I OUTPUT -d 10.100.31.19 -p tcp -m tcp --dport 1521 -j DNAT --to-destination 10.100.91.45:1521"
all,是我们编辑hosts中的模块要对应
#批量添加多个主机hosts
ansible k8s -m shell -a "echo '119.3.222.170 ptah.kxjlcc.com' >> /etc/hosts"
# 复制本地文件的到远程主机
ansible k8s -m copy -a 'src=/root/m.sh dest=/tmp/a.sh'
# 修改文件的权限
ansible k8s -m copy -a 'src=/root/m.sh dest=/tmp/a.sh mode=755'
# 直接将文本内容注入到远程主机的文件中
ansible k8s -m copy -a "content='白云深处有人家\n' dest=/tmp/b.txt"
#在远程机器上创建文件夹
ansible k8s -m file -a 'path=/lzmly2 state=directory'
#用来在远程机器上创建文件
ansible k8s -m file -a 'path=/root/q.txt state=touch'
#创建软连接src是源地址,path是目标地址
ansible k8s -m file -a 'path=/tmp/f src=/etc/fstab state=link'
#用来删除文件或者文件夹
ansible k8s -m file -a 'path=/data/zdw state=absent'
#批量修改主机密码
ansible-playbook root_passwd.yaml
#ansible有自己的语法可以将自己的需求写成yaml文件,然后使用ansible-playbook 命令执行
例如以下是root_passwd.yaml文件内容,作为参考
---
- hosts: all
sudo: yes
remote_user: xxxx
gather_facts: false
tasks:
- name: change user passwd
user: name={{ item.user }} password={{ item.password | password_hash('sha512') }} update_password=always
with_items:
- { user: 'xxxx', password: 'xxxddd....' }
- { user: 'ddd', password: 'xxxddd....' } #多个用户继续加