详细步骤参考:Ansible的介绍与安装
编写playbook
安装并配置yum源 [root@ansible playbook]# vim playbook.yml --- - name: download CentOS 7 yum hosts: 192.168.86.132 tasks: - name: download yum get_url: url: https://mirrors.aliyun.com/repo/Centos-7.repo dest: /etc/yum.repos.d 修改yum源的配置文件 - name: change CetnOS 7 yum file hosts: 192.168.86.132 tasks: - name: change CentOS 7 yum file command: sed -i 's/\$releasever/7/g' /etc/yum.repos.d/Centos-7.repo 安装httpd服务 - name: install httpd hosts: 192.168.86.132 tasks: - name: install httpd yum: name: httpd state: present 修改httpd的配置文件 - name: change configuration file hosts: 192.168.86.132 tasks: - name: change configuration file command: sed -i 's/#ServerName www.example.com:80/ServerName www.example.com:80/g' /etc/httpd/conf/httpd.conf 添加站点 - name: add index hosts: 192.168.86.132 tasks: - name: add index shell: cd /var/www/html/ && mkdir test xxx && cd test && echo "hello tom" > index.html && cd ../xxx && echo "helo cwt" > index.html 配置虚拟主机 - name: add VirtualHost hosts: 192.168.86.132 vars_files: - vars/httpd_port1 - vars/httpd_port2 tasks: - name: add VirtualHost template: src: files/httpd-vhosts.conf dest: /etc/httpd/conf.d/httpd-vhosts.conf //编写变量文件,变量文件要放在vars目录下,规范管理 [root@ansible vars]# cat httpd_port1 httpd_port1: 80 [root@ansible vars]# cat httpd_port2 httpd_port2: 81 //这一步需要在ansible主机上手动编写虚拟主机配置文件,并引用变量 <VirtualHost *:{{ httpd_port1 }}> DocumentRoot "/var/www/html/test" ServerName test.example.com ErrorLog "/var/log/httpd/test.example.com-error_log" CustomLog "/var/log/httpd/test.example.com-access_log" common </VirtualHost> Listen {{ httpd_port2 }} <VirtualHost *:{{ httpd_port2 }}> DocumentRoot "/var/www/html/xxx" ServerName xxx.example.com ErrorLog "/var/log/httpd/xxx.example.com-error_log" CustomLog "/var/log/httpd/xxx.example.com-access_log" common </VirtualHost> 启动服务 - name: start httpd hosts: 192.168.86.132 tasks: - name: start httpd service: name: httpd state: started enabled: yes注:建议所有任务全部写在一个playbook中,避免文件太多
执行playbook [root@ansible playbook]# ansible-playbook playbook.yml PLAY [download CentOS 7 yum] ********************************************************************************************************************************************* ... ... 192.168.86.132 : ok=14 changed=6 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 打开浏览器测试