Run a role in loop for multiple Elastic Ips

Faizan
Wed, 17 Jan 2024 04:45:11 +0000
Get Help

I have written a global role to spin-up ec2 instance at the address: playbook/aws/spin-up-ec2/tasks/main.yaml and i am calling the role in a main file at the location playbook/servers/cluster/tasks/main.yaml to deploy three servers by calling the role in a loop for elastic_ips in the below fashion.
playbook/aws/spin-up-ec2/tasks/main.yaml

- name: test
  hosts: localhost
  become: false
  gather_facts: false
  vars_files:
   - "vars/{{ env }}/main.yaml"

  pre_tasks:
  - name: Set all
    add_host: hostname={{ item }} groupname=all-servers
    with_items: '{{ elastic_ips }}'

  - name: add new instance to host group at runtime
    add_host: hostname={{ item }} groupname=nodes
    with_items: '{{ elastic_ips[1:] }}'
  tasks:
    - name: Run the role for each elastic IP
      include_role:
        name: ../../roles/aws/spin-up-ec2-instance
      vars:
         elastic_ip: "{{ elastic_ips }}"
      loop: "{{ elastic_ips }}"

- name: On all servers
  hosts: all-servers
  become: false
  gather_facts: false

  roles:
   - install-dependencies
   - install-package
   - configure-package

- name: On all nodes
  hosts: nodes
  become: false
  gather_facts: false

  roles:
    - setup-cluster

I am using the variable file at the below location: playbook/servers/cluster/vars/<prod/uat>/main.yaml
The var file contains the some variables which are common for all the three servers. But there are some variables which are different for different instances. So i want these variables to be passed in the loop. I am not able to achieve this. The variables which are different for different instances are mentioned below;

ebs_tags:
  Name: server-1/2/3
  customer: abc
  cost_center: abc
  env_type: prod/uat
ec2_tags:
  Name: server-1/2/3
  customer: abc
  cost_center: abc
  env_type: prod/uat
server_name: "server-1/2/3"
elastic_ips:
  - 4.8.9.7
  - 4.6.6.3
  - 2.5.3.0

I have tried different approaches but i get errors like item is undefined or we were unable to convert to dict: dictionary requested, could not parse JSON or key=value.

Please help me resolve this issue and optimize the approach.
Note: I can’t use the host/inventory file also the playbook/aws/spin-up-ec2/tasks/main.yaml role is a global role and uses variables as defined in the var file. No changes can be made in the variable key parameter.

7 posts - 4 participants