1.建立角色目录 mkdir -pv /etc/ansible/roles/httpd/{files,templates,tasks,handlers,vars,meta,default}

2.建立主任务,主要四个步骤包括: 安装包, 复制模拟配置文件 启动服务 通知:当配置文件修改时通知重启/重载配置文件

[root@ansible ~]# vi /etc/ansible/roles/httpd/tasks/main.yml 
 - name: httpd install                      #安装包                                  
   yum: name=httpd state=installed
   when: ansible_os_family == "RedHat"
 - name: install configfile                #复制模拟配置文件
   template: src=/etc/ansible/roles/httpd/templates/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
   tags: conf
   notify: restart httpd                   #通知:当配置文件修改时通知重启/重载配置文件
 - name: start httpd                       #启动服务
   service: name=httpd state=started enabled=yes

3.当收到通知时重启服务

[root@ansible ~]# vi /etc/ansible/roles/httpd/handlers/main.yml
 - name: restart httpd     #注意收到通知名称必须和发出通知名称一样
   service: name=httpd state=restarted  

4.配置好服务配置文件 httpd 配置文件 1.要将原配置文件复制到roles/httpd/templates 下,且文件名为j2 cp /etc/httpd/conf/httpd.conf /etc/ansible/roles/httpd/templates/httpd.conf.j2

2..编辑httpd配置文件

vi /etc/ansible/roles/httpd/templates/httpd.conf.j2
 Listen {{ ansible_ens33.ipv4.address }}:80    #监听地址参数
 ServerName {{ ansible_nodename }}:80          #server_name

5.建设好调用角色的playbook文件

vi /etc/ansible/playbooks/httpd.yml 
  - hosts: tcsrvs
  remote_user: root
  roles:
  - httpd