1、将yum源修改为阿里云(可选)
yum-config-manager --disable \*
cd /etc/yum.repos.d
rm -f ./*
wget http://mirrors.aliyun.com/repo/Centos-7.repo
yum repolist
2、准备一台控制机,两台被控制机,这里克隆两台机子当被控制机,最好都设置为命令行界面或者用其他操作界面
systemctl set-default multi-user.target
reboot
或
ctrl+alt+F2
3、配置控制机免密码ssh登录被控制机,clone1 192.168.0.130,clone2 192.168.0.131
ssh-keygen
ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.0.130
ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.0.131
4、控制机安装ansible
yum install -y ansible
ansible --version
5、在控制机创建ansible.cfg、inventory
#主配置文件:ansible.cfg
mkdir /root/ansible
vim /root/ansible/ansible.cfg
#内容如下:
[defaults]
inventory = /root/ansible/inventory
remote_user = root
#主机清单:inventory
vim /root/ansible/inventory
#内容如下:
localhost
[nodes]
192.168.0.130
192.168.0.131
6、命令行模式控制
cd /root/ansible
#将下面的inventory改为/root/ansible/inventory就不需要进入该目录
(如最后面查看ip命令)
- 查看/usr目录中的文件列表
ansible nodes -i inventory -m command -a 'ls /usr -lh'
- 在/root/目录中创建一个文件
ansible nodes -i inventory -m command -a 'touch /root/test.txt'
- 创建一个用户mary
ansible nodes -i inventory -m command -a 'useradd mary'
- 查看防火墙运行情况
ansible nodes -i inventory -m command -a 'systemctl status firewalld'
- 查看内存使用状况
ansible nodes -i inventory -m command -a 'free -h'
- 查看IP地址
ansible nodes -i /root/ansible/inventory -m command -a 'ip a'
7、剧本模式控制
a)创建剧本playbook
vim play.yaml
#内容如下:(这个剧本是为两台被控制机搭建LAMP平台)
---
- hosts: nodes
tasks:
- name: install httpd
yum:
name: httpd
state: installed
- name: start and enabel httpd
service:
name: httpd
state: started
enabled: yes
- name: firewalld setting
firewalld:
service: http
state: enabled
immediate: yes
permanent: true
- name: place a page
copy:
content: "Hello, world. This is {{ ansible_hostname }}.\n"
dest: /var/www/html/index.html
owner: apache
group: apache
mode: 0644
- name: setup a virtual host
template:
src: /root/ansible/config.j2
dest: /etc/httpd/conf.d/1.conf
owner: root
group: root
mode: 0644
- name: restart httpd
service:
name: httpd
state: restarted
b)创建模版文件config.j2
vim /root/ansible/config.j2
#内容如下:
<VirtualHost *:80>
DocumentRoot /var/www/html
ServerName localhost
</VirtualHost>
c)运行剧本
ansible-playbook --syntax-check play.yaml #查看文件语法格式是否出错,下图则为正常
ansible-playbook play.yaml
d)浏览器访问被控制机ip