Skip to content

Commit

Permalink
[AAP-7570] Add SSL support when connect to a controller (#326)
Browse files Browse the repository at this point in the history
Resolves AAP-7570
  • Loading branch information
bzwei authored Feb 2, 2023
2 parents 4a3c993 + d4e4440 commit e3b9c7b
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 9 deletions.
17 changes: 14 additions & 3 deletions ansible_rulebook/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,11 @@
--id=<i> Identifier
--worker Enable worker mode
--project-tarball=<p> Project tarball
--controller_url=<u> Controller API base url, e.g. http://host1:8080
--controller_token=<t> Controller API authentication token
--controller-url=<u> Controller API base url, e.g. http://host1:8080
--controller-token=<t> Controller API authentication token
--controller-ssl-verify=<v> How to verify SSL when connecting to the
controller, yes|no|<path to a CA bundle>,
default to yes for https connection
"""
import argparse
import asyncio
Expand Down Expand Up @@ -120,12 +123,18 @@ def get_parser() -> argparse.ArgumentParser:
)
parser.add_argument(
"--controller-url",
help="Controller API base url, e.g. http://host1:8080",
help="Controller API base url, e.g. https://host1:8080",
)
parser.add_argument(
"--controller-token",
help="Controller API authentication token",
)
parser.add_argument(
"--controller-ssl-verify",
help="How to verify SSL when connecting to the "
"controller, yes|no|<path to a CA bundle>, "
"default to yes for https connection",
)
parser.add_argument(
"--print-events",
action="store_true",
Expand Down Expand Up @@ -186,6 +195,8 @@ def main(args: List[str] = None) -> int:
if args.controller_token:
job_template_runner.host = args.controller_url
job_template_runner.token = args.controller_token
if args.controller_ssl_verify:
job_template_runner.verify_ssl = args.controller_ssl_verify
else:
print("Error: controller_token is required")
return 1
Expand Down
26 changes: 22 additions & 4 deletions ansible_rulebook/job_template_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
import json
import logging
import os
from typing import Any, Callable
import ssl
from functools import cached_property
from typing import Any, Callable, Union
from urllib.parse import parse_qsl, quote, urljoin, urlparse

import aiohttp
Expand Down Expand Up @@ -32,9 +34,12 @@ class JobTemplateRunner:
VALID_POST_CODES = [200, 201, 202]
JOB_COMPLETION_STATUSES = ["successful", "failed", "error", "canceled"]

def __init__(self, host: str = "", token: str = ""):
def __init__(
self, host: str = "", token: str = "", verify_ssl: str = "yes"
):
self.token = token
self.host = host
self.verify_ssl = verify_ssl
self.refresh_delay = int(
os.environ.get("EDA_JOB_TEMPLATE_REFRESH_DELAY", 10)
)
Expand All @@ -43,7 +48,9 @@ async def _get_page(
self, session: aiohttp.ClientSession, href_slug: str, params: dict
) -> dict:
url = urljoin(self.host, href_slug)
async with session.get(url, params=params) as response:
async with session.get(
url, params=params, ssl=self._sslcontext
) as response:
response_text = dict(
status=response.status, body=await response.text()
)
Expand All @@ -61,6 +68,15 @@ async def _get_page(
def _auth_headers(self) -> dict:
return dict(Authorization=f"Bearer {self.token}")

@cached_property
def _sslcontext(self) -> Union[bool, ssl.SSLContext]:
if self.host.startswith("https"):
if self.verify_ssl.lower() == "yes":
return True
elif not self.verify_ssl.lower() == "no":
return ssl.create_default_context(cafile=self.verify_ssl)
return False

async def run_job_template(
self,
name: str,
Expand Down Expand Up @@ -118,7 +134,9 @@ async def launch(
async with aiohttp.ClientSession(
headers=self._auth_headers()
) as session:
async with session.post(url, json=job_params) as post_response:
async with session.post(
url, json=job_params, ssl=self._sslcontext
) as post_response:
response = dict(
status=post_response.status,
body=await post_response.text(),
Expand Down
2 changes: 2 additions & 0 deletions ansible_rulebook/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ async def request_workload(activation_id, websocket_address):
job_template_runner.host = data.get("data")
if data.get("type") == "ControllerToken":
job_template_runner.token = data.get("data")
if data.get("type") == "ControllerSslVerify":
job_template_runner.verify_ssl = data.get("data")
return inventory, extra_vars, rulebook, project_data_file
except CancelledError:
logger.info("closing websocket due to task cancelled")
Expand Down
2 changes: 1 addition & 1 deletion docs/actions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ run_job_template
Run a job template.

.. note::
``--controller_url`` and ``--controller_token`` cmd options must be provided to use this action
``--controller-url`` and ``--controller-token`` cmd options must be provided to use this action

.. list-table::
:widths: 25 150 10
Expand Down
6 changes: 5 additions & 1 deletion docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,13 @@ The `ansible-rulebook` CLI supports the following options::
--project-tarball PROJECT_TARBALL
A tarball of the project
--controller-url CONTROLLER_URL
Controller API base url, e.g. http://host1:8080
Controller API base url, e.g. https://host1:8080
--controller-token CONTROLLER_TOKEN
Controller API authentication token
--controller-ssl-verify
How to verify SSL when connecting to the
controller, yes|no|<path to a CA bundle>,
default to yes for https connection
--print-events Print events to stdout, disabled if used with --debug

To get help from `ansible-rulebook` run the following:
Expand Down

0 comments on commit e3b9c7b

Please sign in to comment.