ansible中基于区域的基于环境的动态vars文件加载

region based environment based dynamic vars file loading in ansible

我想根据区域和环境类型在 ansible 中加载特定的 var 文件。 我有一个 playbook,它通过以下类型的配置一次创建多个 ec2 实例 -

---
- hosts: local
  gather_facts: true
  any_errors_fatal: true
  vars_files:
    - group_vars/ec2.yml

  roles:
    - role-for-instance-1-creation
    - role-for-instance-1-creation

但问题是..根据用户要求,它可能会在欧盟地区创建一次实例,其他时间在美国地区创建实例。 ec2.yml 包含与 ec2 角色相关的变量,这些变量可能因地区而异,也取决于环境,是生产还是测试。但是我找不到办法。

我需要某种结构..假设用户提供了额外的变量,而 运行 剧本像 --extra-vars "environment=prod location=EU" 剧本将在特定区域创建 ec2 实例,读取特定的 ec2.yml 文件,如 ec2_prod_EU.yml

ec2_testing_US.yml

或者以更好的方式从特定目录加载 vars 文件

group_vars/prod/ec2-EU.yml
group_vars/testing/ec2-US.yml

我该怎么做.. include_vars 是一种选择,但有没有更好的方法来实现它。提前致谢

我把所有的信息都放在 group_vars/all 中,所以 localhost 会自动拥有它需要的变量。所以文件 group_vars/all/infrastructure.yml 可能如下所示:

environments:
- environment: prod
  region: us-east1
  servers:
  - type: app
    count: 50
    instance_type: m4.xlarge
  - type: data
    count: 15
    instance_type: m4.xlarge
- environment: test
  region: us-west2
  servers:
  - type: app
    count: 5
    instance_type: m4.xlarge
  - type: data
    count: 3
    instance_type: m4.xlarge

现在,您的 ec2 调用必须循环执行所有这些操作。

---
- hosts: localhost
  connection: local
  gather_facts: false
  tasks:
  - name: Provision a set of instances
    ec2:
        instance_type: "{{ item.1.instance_type }}"
        image: "{{ image }}"
        region: "{{ item.0.region }}"
        vpc_subnet_id: "{{ subnets[item.0.env] }}"
        tenancy: "{{ tenancy }}"
        group_id: "{{ group_id }}"
        key_name: "{{ key_name }}"
        wait: true
        instance_tags:
           Type: "{{ item.1.type }}"
           Env: "{{ item.0.env }}"
        count_tag:
           Type: "{{ item.1.type }}"
           Env: "{{ item.0.env }}"
        exact_count: "{{ item.1.count }}"
    with_subelements:
      - "{{ environments }}"
      - servers

您还需要设置一些其他内容。我不知道你的环境,但这就是我为 ACA (a.k.a., Obamacare) 构建 EC2 服务器的方式。

我是通过以下方式完成的- 有条件地在角色上添加 vars 文件和我在执行剧本时传递的条件参数 -

- name: dynamic ec2 yml load
  include_vars:
        file: group_vars/test/ec2_us_test_session_host_1.yml
  when: environment_use == 'test' and location == 'us'
  tags:
          - ec2-creation 

并在调用剧本时 -

ansible-playbook my-playbook.yml --extra-vars "source_ami=${Source_AMI} Description_new_hosts=${description} environment_use=${environment_use} location=${location} availability_zone=${AZ} subnet=${subnet}"