vars in palybook with roles

Hi All,

I have the bellow playbook.yml file but having some problems to use the vars defined under the vars_files section. If I comment out the vars the playbook runs but then the values are unknown to the roles tasks…

I have defined different environment and password variables to use accordingly with my host file for staging, I would like to be able to deploy the same way this setup for dev/qa/production by changing only the host file and the vars_files.


  1. vars_files:

    • vars/users.yml
  2. #Password $ Access keys

    • private_vars/staging-secret-vars.yml
  3. Enviroment values

    • vars/staging-us-east.yml
  4. Apply common configuration to all hosts

    • hosts: all
  5. user: root

  6. roles:

    • common
    • hosts: webservers
  7. user: root

  8. roles:

    • apache
    • web-moniroing
    • hosts: dbervers
  9. user: root

  10. roles:

    • mysql
    • data
    • db-monitoring

Can you please have a look and tell me how can I include the vars file under vars in the top level directory where I have the playbook ? any recommendations of doing this in a more efficient way is also welcome.

You noted the vars_files: section outside of your plays (which I suppose would yield an error).
You need to repeat them for every play, and note vars_files: on the same level as hosts:

Is there a way I could have the vars set for all plays like I’m trying ?

Sure.

You could move your variables into group_vars/all (or another group) as a file, and that will load in every playbook you use.

if group_vars/ , does must much the name of a group in the host file I’m running the playbook ?
can I have the group_var dir in a different location than /etc/ansible/group_var ?

It must match a name of the group the host is in, but does not have to be explicitly mentioned in the play. All hosts are automatically in the “all” group. For instance if you said “hosts: webservers”, the “all” variables are still loaded.

The group_vars directory can exist anywhere but is expected to be in the same place as your inventory file.

so like -i /here/is/my/inventory_file

would mean /here/is/my/group_vars/all

If you specify a “-i” as a directory path to use multiple inventory files at once, the group_vars then lives inside the directory.

thanks. besides using group_vars is there another alternative ?

Yes.

You can define them in your inventory file (less attractive, IMHO) or pull them from your external inventory data source.

group_vars is the best way.

thanks.