ansible自动化运维

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
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值