Cannot get ansible to recognize group variables

一世执手 提交于 2019-12-04 10:08:51

EDIT:

To answer your question more specifically, please have a look at this github exemple project. This is, I think, what you tried to do. I might be wrong, but I think the problem comes from your inventory file. You actually named your group_vars files (staging) after your inventory filename (staging too). But, you must name it after the section inside your inventory file, which is, I suppose, localhost looking at your playbook.

Thus, this is what you should have:

hosts/staging:

[staging]
X.X.X.X

Here is, according to me, a more viable solution to organize your project. It is based on roles.

Directory structure:

.
├── group_vars
│   └── all
├── hosts
│   └── local
│   └── staging
│   └── prod
├── roles
│   └── exemple
│       └── tasks
│       └── vars
│           └── local.yml
│           └── staging.yml
│           └── prod.yml
└── site.yml

The group_vars/all could have an env variable:

# The application environment
# Possible values are : prod, staging or local
env: local

# Other global variables
...

Your inventory file:

[local]
X.X.X.X

[staging]
X.X.X.X

[prod]
X.X.X.X

Then, your playbook sites.yml could look like this:

---
- name: Server(s) configuration
  hosts: "{{env}}"
  roles:
    - exemple
  vars_files:
    - "roles/example/vars/{{env}}.yml"

Doing it this way gives you multiple benefits:

  • you can reuse the env variable anywhere in your project, in jinja templates or as a condition in tasks which is very practical;
  • your project is split into separate roles. It’s cleaner this way for big project (you can have an apache role, ssh role, etc.);
  • you can create env-specific variables in separate files in roles/exemple/vars/ directory.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!