Suku Suku - 2 months ago 77
YAML Question

Creating a dynamic role in ansible

After going through several documentation I concluded that, I can't use

with_items
for
roles
.

So, I created a
filter_plugin
to generate a list of dictionaries for roles.

Here is my
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",
}


I want to generate above roles dynamically and for that I created a
filter_plugin
which generates a list of dictionaries and that is working right.

Here is my 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}


My plan was to generate roles like following:

roles: "{{ EC2_REGIONS | vpcroles }}"


where
EC2_REGIONS
is
['ap-southeast-2', 'us-east-1']


But roles are not working in that way.

I am getting following error:

ERROR! A malformed role declaration was encountered.


Any thoughts/ideas ?

Answer

My colleague showed me a way to achieve a dynamic role. Here is that.

Directory Structure:

- vpc.yml
|
- roles/vpc/tasks/main.yml
|
- roles/vpc/tasks/real.yml

Play - 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 }}"}

Role - roles/vpc/tasks/main.yml:

- include: real.yml ec2_region="{{ _region }}"
  with_items: "{{ ec2_regions }}"
  loop_control:
    loop_var: _region

And then added my tasks in roles/vpc/tasks/real.yml