2

I am developing a serverless app using Python and AWS-SAM-CLI. I am debugging my functions using ptvsd library. In order to attach a debugger, the following snippet has to be in the function code.

ptvsd.enable_attach(address=('0.0.0.0', 5890), redirect_output=True)
ptvsd.wait_for_attach()

Obviously, this code has to be removed before deploying the function to stage or production environment.

Is there a way to automate this during package/deploy step to not have to manually remove this snippet of code from each function before a deployment?

Tommy
  • 1,006
  • 3
  • 13
  • 26

1 Answers1

1

I would set an environment variable, let's say, DEV=true (the value here doesn't really matter) on your local environment and wrap that code around an IF statement.

if "DEV" in os.environ:
    ptvsd.enable_attach(address=('0.0.0.0', 5890), redirect_output=True)
    ptvsd.wait_for_attach()

The code is still there but will never be executed unless the environment variable is present.

Thales Minussi
  • 6,965
  • 1
  • 30
  • 48
  • 1
    Thanks! That could work, especially that there is already `AWS_SAM_LOCAL` variable that I can use for this purpose. The issue, however, is that `ptvsd` is still in my `rquirements.txt` file which is processed by `sam build` command and that means that the whole library still gets packaged and deployed even though it's not used or needed. – Tommy May 16 '19 at 14:09
  • 1
    I ended up rolling back my edit as it would fail on the import level. Ye, that's a good one now. I am not sure how you could do it as I am not a python developer myself. Would it be possible to only import it if it's dev, for example? In node.js, for example, you can `require` things pretty much whenever you want, not sure how it works in python though – Thales Minussi May 16 '19 at 14:19
  • so I ran a very simple script in python and I realised I can import things inside methods, like this: `def some_method(): import ptvsd // do your stuff`. You can then split your requirements.txt into multiple files which correspond to the environment you want to run on, so `dev` would contain `ptvsd` but `prod` would not. – Thales Minussi May 16 '19 at 14:22
  • 1
    Thanks again, at least I'm not missing something very obvious! I import after checking for `AWS_SAM_LOCAL` but the main issue now is with requirements.txt. I'm also new to python, but for what I can see `sam build` looks for a requirements.txt file that is in the same folder as the code of my lambda function. So I don't see another option than manually swapping requirements.txt files depending on whether I want to debug locally or package&deploy. Which is obviously a sub-optimal solution. – Tommy May 16 '19 at 15:49