【发布时间】:2023-01-26 22:09:27
【问题描述】:
我想使用 Ansible 设置服务器。这是我的文件结构:
group_vars/
all.yml
development.yml
production.yml
vault/
all.yml
development.yml
production.yml
playbooks/
development.yml
production.yml
roles/
common/
tasks/
main.yml
vars/
main.yml
ansible.cfg
hosts
这是我的ansible.cfg:
[defaults]
vault_password_file = ./vault_pass.txt
host_key_checking = False
inventory = ./hosts
development.yml 剧本:
- hosts: all
name: Development Playbook
become: true
roles:
- ../roles/common
vars_files:
- ../group_vars/development.yml
- ../group_vars/all.yml
- ../group_vars/vault/development.yml
- ../group_vars/vault/all.yml
以及common角色的tasks/main.yml文件:
# Set hostame
- name: Set hostname
become: true
ansible.builtin.hostname:
name: "{{ server.hostname }}"
# Set timezone
- name: Set timezone
become: true
community.general.timezone:
name: "{{ server.timezone }}"
# Update all packages
- name: Update all packages
become: true
ansible.builtin.apt:
upgrade: dist
update_cache: true
group_vars/all.yml 文件如下所示:
server:
hostname: "myhostname"
timezone: "Europe/Berlin"
使用 ansible-playbook playbooks/development.yml 运行剧本时,出现此错误:
fatal: [default]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'hostname'. 'dict object' has no attribute 'hostname'\n\nThe error appears to be in '/ansible/roles/common/tasks/main.yml': line 6, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n# Set hostame\n- name: Set hostname\n ^ here\n"}
有人可以向我解释为什么 vars_files 不起作用以及如何解决这个问题吗?
【问题讨论】:
-
您不应该使用
vars_files来包含来自group_vars的文件。 Ansible 会根据您游戏中的活动组和主机自动包含group_vars和host_vars中的文件。如果您想使用vars_files(或include_vars模块)手动包含文件,请将它们放在其他地方。 -
这就是我的假设,因为如果我去掉
vars_files部分,那么它就可以工作。但稍后在另一项任务中,我尝试从 vault/all.yml 访问一个变量。但是,那是行不通的。然后我如何/在哪里导入库中的三个文件?