playbook实现httpd服务安装与配置

开始前准备

建立template档案(template档案必须以.j2结尾)

[root@localhost project]# vim template/vhosts.j2 
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
<VirtualHost *:{{ port_name1 }}>
    DocumentRoot "/var/www/html/{{ service1_name }}"
    ServerName {{ service1_name }}.example.com
    ErrorLog "/var/log/httpd/{{ service1_name }}.example.com-error_log"
    CustomLog "/var/log/httpd/{{ service1_name }}.example.com-access_log
" common
</VirtualHost>


Listen {{ port_name2 }}
<VirtualHost *:{{ port_name2 }}>
    DocumentRoot "/var/www/html/{{ service2_name }}"
    ServerName {{ service2_name }}.example.com
    ErrorLog "/var/log/httpd/{{ service2_name }}.example.com-error_log"
    CustomLog "/var/log/httpd/{{ service2_name }}.example.com-access_log
" common
</VirtualHost>

playbook

---
- name: 配置yum与apache
  hosts: 192.168.190.133
  vars_files:
    - files/vars
  tasks:
    - name: 传输yum包并配置yum网络源
      copy:
        src: files/CentOS-Base.repo
        dest: /etc/yum.repos.d/
    - yum:
        name: httpd
        state: present
    - name: web服务器名
      lineinfile:
        path: /etc/httpd/conf/httpd.conf
        regexp: '^ServerName www.example.com:80'
        line: 'ServerName localhost:80'
    - name: 配置虚拟主机
      template:
        src: template/vhosts.j2
        dest: /etc/httpd/conf.d/vhosts.conf
    - name: 创建配置主页文件
      shell: cd /var/www/html && mkdir {{ service1_name }} {{ service2_name }}
    - copy:
        src: files/index1.html
        dest: /var/www/html/{{ service1_name }}/index.html
    - copy:
        src: files/index2.html
        dest: /var/www/html/{{ service2_name }}/index.html
    - name: 启用httpd服务
      service:
        name: httpd
        state: started
        enabled: yes
    - service:
        name: firewalld
        state: stopped
        enabled: no


[root@localhost playbook]# ansible-playbook --syntax-check apache_server.yml               检查语法

playbook: apache_server.yml
[root@localhost playbook]# ansible-playbook -C apache_server.yml         空执行检查。
......
PLAY RECAP *********************************************************************************************
192.168.190.133            : ok=8    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

[root@localhost playbook]# ansible-playbook apache_server.yml      正式执行apache_server.yml

PLAY RECAP *********************************************************************************************
192.168.190.133            : ok=8    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

[root@localhost conf.d]# curl 192.168.190.133             成功实现不同端口访问    
hello world
[root@localhost conf.d]# curl 192.168.190.133:81
你好世界

原文地址:https://www.cnblogs.com/sawyer95/p/13580372.html