首页 > 解决方案 > 多环境中的 Ansible

问题描述

我想知道是否有人可以建议我如何使用 ansible 管理多个环境变量。想象一下我有开发和分期。我有以下结构:

.
├── inventories
│   ├── development
│   │   ├── group_vars
│   │   │   └── all.yml
│   │   └── hosts
│   └── staging
│       ├─── group_vars
│       │   └── all.yml
│   │   └── hosts
├── roles
└── test.yml

在每个 all.yml 文件中,我都有一个这样的变量:

变量:名称:“发展”

我想知道如何根据要在命令行(-i env=development)上设置的参数来加载值的最佳方法。

在 test.yml 中,我有这个:


- name: test playbook
  hosts: localhost
  connection: local
 
  tasks:
    - name: 
      debug: 
        var: name

当我执行时,我得到了这个:

ansible-playbook -i inventories/development/ test.yml  -vvv
....
ok: [localhost] => {
    "name": "VARIABLE IS NOT DEFINED!: 'name' is undefined"
}

我是 ansible 的新手,我发现了数千种不同的方法,我想知道最好的方法是什么?因为我有点迷路了:( :(

问候,

标签: ansibleansible-inventory

解决方案


我猜我们的项目与您的需求相似。组织方式如下:

.
group_vars folder
├── all.yml # variables common for all envs (creds for example)
├── development.yml # variables for development env
└── staging.yml # variables for staging env
|
invenory_file.yml # file which stoers your managed hosts list devided by groups
├── [development]
│   ├── dev.host1.name # development host#1 with vars applied from development.yml
│   ├── dev.host2.name # development host#2 with vars applied from development.yml
│   └── dev.host3.name # development host#3 with vars applied from development.yml
├── [staging]
│   ├── staging.host1.name # staging host#1 with vars applied from staging.yml
│   ├── staging.host2.name # staging host#2 with vars applied from staging.yml
│   └── staging.host3.name # staging host#3 with vars applied from staging.yml
|
roles

主要思想是,您拥有针对不同环境的带有变量的单独文件,并且您将主机组织在清单文件中的环境组中。因此,group_vars 中文件的变量将应用于在 Inventory 中分组的正确主机。

这是检查 Ansible 组的组织方式的常用链接: https ://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html


推荐阅读