the offending line appears to be errors on ansible roles

ansible-logo
ansible-logo

ansible errors:the offending line appears to be error。使用 roles 方式可以自动加载指定目录树中的vars, files, tasks, 和 handlers。在实际中执行playbook有上述错误出现,开始以为是缩进的问题,后来发现指定目录中的main.yml中会把目录的名字自动认为对应的key:value中的key,yml中应该去掉该key值!

按照ansible文档说明,使用roles时,需要创建对应的目录和默认的yml文件:main.yml:

目录结构:
site.yml
webservers.yml
fooservers.yml
roles/
   common/
     files/
     templates/
     tasks/
     handlers/
     vars/
     defaults/
     meta/
   webservers/
     files/
     templates/
     tasks/
     handlers/
     vars/
     defaults/
     meta/

创建目录:
mkdir -p webservers/{files,templates,tasks,handlers,vars,defaults,meta}

执行ansible-playbook命令后有The offending line appears to be的报错,具体如下:

$ ansible-playbook rolestest.yml
ERROR! The tasks/main.yml file for role 'webservers' must contain a list of tasks

The error appears to have been in '/opt/sudops.com/ansible/playbook/roles/webservers/tasks/main.yml': line 1, column 1, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

tasks:
^ here

具体修改:

$ vim /opt/sudops.com/ansible/playbook/roles/webservers/tasks/main.yml
tasks:
  - name: ensure apache is at the latest version
    yum:
      name: httpd
      state: latest
  - name: write the apache config file
    template:
      src: /opt/sudops.com/ansible/playbook/src/httpd.j2
      dest: /etc/httpd/conf/httpd.conf
    notify:
    - restart apache
  - name: ensure apache is running
    service:
      name: httpd
      state: started

$ vim /opt/sudops.com/ansible/playbook/roles/webservers/handlers/main.yml
handlers:
  - name: restart apache
    service:
      name: httpd
      state: restarted

$ cat /etc/ansible/hosts
[webservers]
172.30.0.70

$ cat rolestest.yml
---
- hosts: webservers
  remote_user: root
  roles:
    - webservers

修改后的执行结果:
$ ansible-playbook rolestest.yml

ansible-playbook-roles
ansible-playbook-roles