在ansible中创建动态角色

Suk*_*uku 5 yaml ansible ansible-role

通过几个文件去后,我得出的结论是,我不能使用with_itemsroles.

所以,我创建了一个filter_plugin生成角色列表的列表.

这是我的Play:

---
- name: Boostrap vpc and subnets with route table
  hosts: localhost
  connection: local
  gather_facts: no
  pre_tasks:
    - include_vars: ec2_vars/common/regions.yml
    - include_vars: environment.yml
  roles:
    - {
        role: vpc,
        ec2_region: 'ap-southeast-2'
      }
    - {
        role: vpc,
        ec2_region: "ap-southeast-1",
      }
    - {
        role: vpc,
        ec2_region: "us-west-2",
      }
Run Code Online (Sandbox Code Playgroud)

我想动态生成上述角色,为此我创建了一个filter_plugin生成字典列表并且正常工作的角色.

这是我的插件:

# this is for generating vpc roles

def roles(ec2_regions):
    return [{'role': 'vpc', 'ec2_region': ec2_region} for ec2_region in ec2_regions]


class FilterModule(object):
    def filters(self):
        return {'vpcroles': roles}
Run Code Online (Sandbox Code Playgroud)

我的计划是生成以下角色:

roles: "{{ EC2_REGIONS | vpcroles }}"
Run Code Online (Sandbox Code Playgroud)

这里EC2_REGIONS['ap-southeast-2', 'us-east-1']

但是角色并没有以这种方式发挥作用.

我收到以下错误:

ERROR! A malformed role declaration was encountered.

有什么想法/想法吗?

Suk*_*uku 2

我的同事向我展示了一种实现动态的方法role。就是这样。

目录结构:

- vpc.yml
|
- roles/vpc/tasks/main.yml
|
- roles/vpc/tasks/real.yml
Run Code Online (Sandbox Code Playgroud)

玩 - vpc.yml

---
- name: Boostrap vpc and subnets with route table
  hosts: localhost
  connection: local
  gather_facts: no
  vars:
  pre_tasks:
    - include_vars: environment.yml
  roles:
    - { role: "vpc", ec2_regions: "{{ EC2_REGIONS }}"}
Run Code Online (Sandbox Code Playgroud)

角色 - roles/vpc/tasks/main.yml

- include: real.yml ec2_region="{{ _region }}"
  with_items: "{{ ec2_regions }}"
  loop_control:
    loop_var: _region
Run Code Online (Sandbox Code Playgroud)

然后将我的任务添加到roles/vpc/tasks/real.yml