1

Testing a basic Ansible roles setup but got an error on the first line of a role main.yml, I am sure it's something silly though

play.yml

- hosts: myhosts
  remote_user: myuser
  roles:
    - test

Directory structure

play.yml
roles/test/tasks/main.yml

main.yml

- hosts: all
  user: myuser
  gather_facts: no
  tasks:
  - name: ping all hosts
    ping:

When I run ansible-playbook play.yml, I get the error

The offending line appears to be:


- hosts: all
  ^ here

It looks like a simple YAML parse error but if I run ansible-playbook main.yml, it works fine, so not sure what's going on. Any thoughts?

Anthon
  • 69,918
  • 32
  • 186
  • 246
Bob
  • 8,424
  • 17
  • 72
  • 110
  • An (online) YAML validator will show you that this has nothing to do with YAML parse errors, but is an ansible related issue. http://yaml-online-parser.appspot.com/ – Anthon Nov 15 '16 at 13:44
  • Yeah, I already know it isn't a YAML issue because `ansible-playbook main.yml` works fine, I said it looks like a simple YAML parse error which indicates that the problem is elsewhere. – Bob Nov 15 '16 at 17:50

1 Answers1

2

You cannot specify hosts in roles/test/tasks/main.yml. The hosts are specified in the play.yml file.

roles/test/tasks/main.yml is used to define the actions you want Ansible to perform. In your case to ping hosts, it could simply look like:

 ---

 - ping:

This will perform the ping action on the hosts specified in your play.yml

Ansible has a set folder structure it can use to break down playbooks. The play.yml file, specifies which hosts to target and what roles to apply along with other top level controls.

Individual roles specified in the play.yml file are located in roles/X/, there is a certain folder structure that Ansible expects. It will look for tasks to run in the test role here roles/test/tasks/main.yml.

play.yml is just one playbook. You can create many in the same folder and call them with ansible-playbook.

The official documentation has a more detailed example of the recommended playbook directory structure

Steve E.
  • 9,003
  • 6
  • 39
  • 57
  • Thanks, that works but I should note that I cannot, as opposed to don't need to, specify the hosts in `main.yml`. I think Ansible is doing something basic like concatenating the 2 files and indenting the contents in `main.yml` per YAML specs. BTW, what's the `---` for? I am new to Ansible. – Bob Nov 15 '16 at 17:49
  • 1
    @Bob, you are right. I have updated the answer to be clearer and added a link to the official documentation which has a good example of folder layout. The --- is just part of the yaml syntax, it indicates the start of a document. It's good practice to use it, although it's not always strictly required. I would also recommend looking at [ansible galaxy](https://galaxy.ansible.com/) which has many example roles to experiment with. – Steve E. Nov 15 '16 at 23:15