0

I am creating a simple web server with Flask which will receive the request, do some processing and kick off a Terraform to build some resources in the cloud.

Not sure if this is the best way but I've got it working using subprocess call to trigger the terraform commands but now I want to capture the various Terraform stdout so I can do some logic/notification depending on the output/error.

Here is a sample of what I am trying to do:

try:
        error_code = subprocess.call([
                'terraform',
                'in1t',
                '-no-color',
                '-unknown-flag'
            ])
        print("Error Code: " + str(error_code))
        return jsonify(message='ok', status=200), 200
except OSError as x:
        print(x)
except Exception as e:
        print(e)
        return jsonify(message=e, status=400), 400

Now, just to illustrate what I am trying to do, this command terraform in1t is invalid (should be terraform init), so I wanted to capture the stdout/stderr:

Terraform has no command named "in1t". Did you mean "init"?

To see all of Terraform's top-level commands, run:
  terraform -help

Error Code: 1

How can I do that with the subprocess module?

CaioT
  • 1,973
  • 1
  • 11
  • 20
  • 2
    Use `run`, and look at its `stdout` and `stderr` keyword arguments. `call` is a convenience function equivalent to `run(...).returncode`. – chepner Aug 06 '21 at 17:14
  • that was very simple. I was able to use subprocess.run and capture_output=True. You can move your comment as an answer. Appreciated! – CaioT Aug 06 '21 at 17:20

0 Answers0