使用Ansible部署LAMP環境
前言
這兩天學習了Ansible, 在部署實驗環境真的很好用, 今天向大家分享如何使用Ansible部署LAMP環境, 本文不對Ansible的基本使用作解釋, 有興趣的可以查看 馬哥教育翻譯: Ansible中文權威指南
實驗環境
今天實驗環境比較簡單, 所以就不畫圖了
主機 | IP地址 | 功用 |
---|---|---|
ansible.anyisalin.com | 172.16.1.2 | 控制主機 |
web.anyisalin.com | 172.16.1.3 | httpd和php |
data.anyisalin.com | 172.16.1.4 | MySQL |
實驗步驟
配置ssh公鑰認證
ansible是agentless類的工具, 通過ssh管理遠程主機, 我們需要配置基於公鑰認證的ssh
[root@ansible ~]# ssh-keygen -P '' -f ~/.ssh/id_rsa -t rsa #生成公鑰
[root@ansible ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub 172.16.1.3
[root@ansible ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub 172.16.1.4
安裝ansible
由於ansible的rpm包只有在epel源主提供, 但是一些所依賴組件卻在官方的base2中, 所以我們使用阿里雲的鏡像站
[root@ansible ~]# wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
[root@ansible ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo
[root@ansible ~]# yum install ansible --nogpgcheck -y &> /dev/null && echo success #安裝ansible
success
配置host iventory
將我們所要管理的主機添加到配置文件中
[root@ansible ~]# vim /etc/ansible/hosts #按需添加以下字段到指定配置文件中
[webservers] #組名
172.16.1.3 #IP
[dataserver]
172.16.1.4
創建YAML文件
我們通過playbook來指揮主機運行特定操作
注意: 筆者的配置只針對筆者的環境, 如需使用請自行修改
[root@ansible ~]# vim lamp.yml #創建YAML格式的文件
- hosts: webservers
remote_user: root
tasks:
- name: Install Apache Httpd
yum: name=` item ` state=present disable_gpg_check=yes
with_items:
- httpd
- php
- php-mysql
- name: Install Configuration File
template: src=/root/httpd.conf dest=/etc/httpd/conf/httpd.conf
notify:
- restart httpd
- name: Start Httpd Service
service: enabled=true name=httpd state=started
handlers:
- name: restart httpd
service: name=httpd state=restart
- hosts: dataserver
remote_user: root
tasks:
- name: Install MySQL Server
yum: name=mysql-server state=present disable_gpg_check=yes
- name: Install Configuration File
template: src=/etc/my.cnf dest=/etc/my.cnf
notify:
- restart MySQL
- name: Start MySQL Server
service: name=mysqld state=started
handlers:
- name: restart MySQL
service: name=mysqld state=restarted
運行Ansible-Playbook並測試
總結
其實還可以使用role實現, 但是我們這裏不做介紹, Ansible上手真的簡單, ansible-doc命令查看的幫助也淺顯易懂, 寫這篇博客前mysql_user模塊我是不會使用的, 寫到最後的時候隨便試一下就成功了, 看來ansible的入門真的很容易。
作者水平很低, 如果有錯誤及時指出, 如果你覺得本文寫的好請點一波贊~(≧▽≦)/~
作者: AnyISaIln QQ: 1449472454
感謝: MageEdu