pythonfabricpython-fabric-2

Got "401 Client Error: Unauthorized" when execute st2 command with fabric 2


in fabric 1.14.0, below codes works well

from fabric.api import run, settings, hide
theCmd = 'st2 run core.http url="http://httpbin.org/get"'
user='<my account>'
ss_host='<stackstorm host>'
ss_bast='<stackstorm bastion>'
with settings(user=user, host_string=ss_host, gateway=ss_bast):
    ss_result = run(theCmd)

However, when I switched it to fabric2(2.5.0), below code doesn't work:

from fabric import Connection
theCmd = 'st2 run core.http url="http://httpbin.org/get"'
user='<my account>'
ss_host='<stackstorm host>'
ss_bast='<stackstorm bastion>'
with Connection(host=ss_host, user=user, gateway=Connection(host=ss_bast)) as ss_conn:
    response = ss_conn.run('ls -la', warn=True, hide=True)
    response = ss_conn.run(theCmd)

The first command(ls -la) succeeded, which means the connection was created successfully, but the second command failed with below error

ERROR: 401 Client Error: Unauthorized
MESSAGE: Unauthorized - One of Token or API key required. for url: http://127.0.0.1:9101/v1/actions/core.http

Traceback (most recent call last):
  File "test/test_ss.py", line 12, in <module>
    response = ss_conn.run(theCmd)
  File "<decorator-gen-3>", line 2, in run
  File "venv/lib/python3.7/site-packages/fabric/connection.py", line 30, in opens
    return method(self, *args, **kwargs)
  File "venv/lib/python3.7/site-packages/fabric/connection.py", line 721, in run
    return self._run(self._remote_runner(), command, **kwargs)
  File "venv/lib/python3.7/site-packages/invoke/context.py", line 101, in _run
    return runner.run(command, **kwargs)
  File "venv/lib/python3.7/site-packages/invoke/runners.py", line 363, in run
    return self._run_body(command, **kwargs)
  File "venv/lib/python3.7/site-packages/invoke/runners.py", line 422, in _run_body
    return self.make_promise() if self._asynchronous else self._finish()
  File "venv/lib/python3.7/site-packages/invoke/runners.py", line 489, in _finish
    raise UnexpectedExit(result)
invoke.exceptions.UnexpectedExit: Encountered a bad command exit code!

Command: 'st2 run core.http url="http://httpbin.org/get"'

Exit code: 1

Did I miss any setting?


Solution

  • in fabric 2, you have to generate token and set ST2_AUTH_TOKEN in env. Then execute the rest commands

    with Connection(host=ss_host, user=user, gateway=Connection(host=ss_bast), inline_ssh_env=True) as ss_conn:
        token = ss_conn.run('st2 auth <username> -p <password> -t', hide=True).stdout.strip()
        ss_conn.config.run.env = {"ST2_AUTH_TOKEN": token}