How to dynamically or pre-generate ansible variables from an existing file in a specific format for AWS ECS

620 views Asked by At

I have a simple playbook which creates ECS Taskdefinition. example:

#variable file, vars.yml
---
containers:
- name: nash-test
  essential: true
  image: nash-test
  memory: 256
  portMappings:
  - containerPort: 8080
    hostPort: 80
    protocol: tcp
  environment:
  - name: USERNAME
    value: test-user
    name: PASSWORD
    value: pass123
    name: MYSQL
    value: mysqldb.com:3306

Below is the Playbook execution file main.yml

---
- hosts: localhost
  connection: local
  gather_facts: true
  vars_files:
   - ["vars.yml"]

  tasks:
  - name: Create task definition for ECS Cluster
    ecs_taskdefinition:
      state: present
      family: avinash-environment
      containers: "{{containers}}"
      region: us-east-1
    register: ecs_taskdef

This above model works fine....but i want to make some variables be used dynamically or pre-generated is also fine.

In my case, i have below file in my local directory

#containers_variables
name: USERNAME
value: test-user
name: PASSWORD
value: pass123
name: MYSQL
value: mysqldb.com:3306

then ansible variable file expected to look like this

#variable file, vars.yml
---
containers:
- name: nash-test
  essential: true
  image: nash-test
  memory: 256
  portMappings:
  - containerPort: 8080
    hostPort: 80
    protocol: tcp
  environment:
  - #the values from container_variables have to be populated or dynamically read for this list purpose

Is there any simplistic solution to this ?? i tried using ansible lookup module but im failing with formatting errors, which says "type=list" is being expected. Any ideas on these guys ???

1

There are 1 answers

0
nash On

it was a simple fix.... ;) i just changed the below and it worked, considering the source is in json format.

Before
    environment: 
    - "{{ lookup('file', '{{playbook_dir}}/environment.json') | from_json }}"

After
    environment: "{{ lookup('file', '{{playbook_dir}}/environment.json') | from_json }}"