在ansible中,基于区域环境的动态变量文件加载。

问题描述 投票:0回答:2

我想根据区域和环境类型在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角色相关的变量,这些变量可能会根据地区的不同而变化,也取决于环境的不同,是产品还是测试,但我找不到方法。

我需要某种结构......假设用户在运行playbook时提供了额外的变量,如 --extra-vars "environment=prod location=EU"而playbook会在specfic区域创建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是一个选项,但有什么更好的方法来实现它。先谢谢你

amazon-ec2 ansible ansible-inventory
2个回答
0
投票

我把所有的信息放在 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(也就是奥巴马医保)构建EC2服务器的方法。


0
投票

我是用下面的方式来做的--在角色和条件参数上有条件地添加vars文件,我在执行playbook的时候通过了--。

- 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}"
© www.soinside.com 2019 - 2024. All rights reserved.