0
votes

I am trying to deploy a lambda function using ansible playbook. Lambda code

import boto3
import os`enter code here`
ecs = boto3.client('ecs')
LAMBDA_ENV = ''
if 'stack_name' in os.environ:
    LAMBDA_ENV = os.environ.get['stack_name']

    def task(event,context):
    get_task_arn = ecs.list_tasks(
    cluster = LAMBDA_ENV,
    family= LAMBDA_ENV + '-Wallet-Scheduler',
    desiredStatus='RUNNING'
    )
    #print(get_task_arn)
    task = ''.join(get_task_arn['taskArns'])
    print(task)
    stop_task = ecs.stop_task(
    cluster = LAMBDA_ENV
    task = task,
    reason='test'
    )

The command i use to deploy the lambda function is

ansible-playbook -e stack_name=DEV playbook.yaml

How do i make sure the variable in python file LAMBDA_ENV changes to DEV,STAGE,PRD based on the environment when it gets deployed?

Ansible Playbook

- name: package python code to a zip file
  shell: |
    cd files/
    rm allet-restart.py
    zip file.zip  file.py

- name: Create lambda function
  lambda:
    name: '{{ stack_name | lower }}-lambda-function'
    state: present
    zip_file: 'files/file.zip'
    runtime: python2.7
    role: '{{ role_arn }}'
    timeout: 60
    handler: file.task
 with_items:
   - env_vars:
      stack_name: 'test'

register: wallet-restart

Deploying it from MacOS

2

2 Answers

0
votes

AWS Lambda supports environment parameters and the same can be accessed from lambda code.

With this, you can avoid hardcoding parameters inside the code.

"environment_variables" is the parameter using which you can add env variables for lambda

(Ref : https://docs.ansible.com/ansible/latest/modules/lambda_module.html)

If you are using python, you can access the lambda environment variables using python os module

import os
LAMBDA_ENV = ''
if 'ENV' in os.environ:
    LAMBDA_ENV = os.environ['ENV']

Hope this helps !!!

0
votes

You can use ansible template module to replace all the env variables for the python code in the lamda then zip all files using shell module and then invoke the lamda.

- name: template module
  template:
    src: 
    dest:

- name: zip the templated python code insde the zip
  shell: zip ...

- name: invoke lamda
  lamda:
  ....