Skip to content
4 changes: 4 additions & 0 deletions samcli/commands/_utils/table_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ def pprint_wrap(func):

@wraps(func)
def wrap(*args, **kwargs):
output_mode = kwargs.pop("output_mode", "text")
if output_mode == "json":
kwargs["output_mode"] = output_mode
return func(*args, **kwargs)
# The table is setup with the column names, format_string contains the column names.
if table_header:
click.secho(
Expand Down
24 changes: 21 additions & 3 deletions samcli/commands/deploy/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
CLI command for "deploy" command
"""

import contextlib
import logging
import os

Expand Down Expand Up @@ -170,6 +171,12 @@
@no_progressbar_option
@capabilities_option
@language_extensions_option
@click.option(
"--output",
default="text",
help="Output the results from the command in a given output format. Supported formats: text (default), json.",
type=click.Choice(["text", "json"], case_sensitive=False),
)
@aws_creds_options
@common_options
@save_params_option
Expand Down Expand Up @@ -206,6 +213,7 @@ def cli(
resolve_s3,
resolve_image_repos,
language_extensions,
output,
save_params,
config_file,
config_env,
Expand Down Expand Up @@ -251,6 +259,7 @@ def cli(
on_failure,
max_wait_duration,
express,
output,
) # pragma: no cover


Expand Down Expand Up @@ -287,6 +296,7 @@ def do_cli(
on_failure,
max_wait_duration,
express,
output="text",
):
"""
Implementation of the ``cli`` method
Expand All @@ -298,6 +308,9 @@ def do_cli(

language_extensions_enabled = resolve_language_extensions_enabled(language_extensions)

if guided and output == "json":
raise click.UsageError("--guided is not compatible with --output json")

if guided:
# Allow for a guided deploy to prompt and save those details.
guided_context = GuidedContext(
Expand Down Expand Up @@ -326,8 +339,12 @@ def do_cli(
if resolve_s3:
if bool(s3_bucket):
raise DeployResolveS3AndS3SetError()
s3_bucket = manage_stack(profile=profile, region=region)
print_managed_s3_bucket_info(s3_bucket)
if output == "json":

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[BUG] The --output flag is only handled in the non-guided branch. When a user runs sam deploy --guided --output json, the if guided: branch (which precedes this block) invokes guided_context.run(), which unconditionally writes decorative text via click.echo/click.secho and blocks on interactive prompts (click.prompt, click.confirm) in samcli/commands/deploy/guided_context.py (e.g., lines 128, 149, 153, 165, 186, 191) and guided_config.py. As a result:

  • The NDJSON stream on stdout is corrupted by yellow-tinted prose ("Setting default arguments for 'sam deploy'", "Looking for resources needed for deployment:", managed-bucket info, etc.).
  • Interactive prompts hang indefinitely because a JSON-consuming caller cannot supply keyboard input.

Please either thread output into the guided flow and suppress its output there too, or reject the combination early in cli():

if guided and output == "json":
   raise click.UsageError("--guided is not compatible with --output json")

with open(os.devnull, "w") as devnull, contextlib.redirect_stdout(devnull):
s3_bucket = manage_stack(profile=profile, region=region)
else:
s3_bucket = manage_stack(profile=profile, region=region)
print_managed_s3_bucket_info(s3_bucket)

# TODO Refactor resolve-s3 and resolve-image-repos into one place
# after we figure out how to enable resolve-images-repos in package
Expand All @@ -351,7 +368,7 @@ def do_cli(
kms_key_id=kms_key_id,
use_json=use_json,
force_upload=force_upload,
no_progressbar=no_progressbar,
no_progressbar=no_progressbar if output != "json" else True,
metadata=metadata,
on_deploy=True,
region=guided_context.guided_region if guided else region,
Expand Down Expand Up @@ -399,5 +416,6 @@ def do_cli(
max_wait_duration=max_wait_duration,
language_extensions=language_extensions,
express=express,
output=output,
) as deploy_context:
deploy_context.run()
1 change: 1 addition & 0 deletions samcli/commands/deploy/core/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
ADDITIONAL_OPTIONS: List[str] = [
"language_extensions",
"no_progressbar",
"output",
"signing_profiles",
"template_file",
"use_json",
Expand Down
102 changes: 77 additions & 25 deletions samcli/commands/deploy/deploy_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

import json
import logging
import os
import sys
from typing import Dict, List, Optional

import boto3
Expand Down Expand Up @@ -78,6 +80,7 @@ def __init__(
max_wait_duration,
language_extensions: Optional[bool] = None,
express: bool = False,
output: str = "text",
):
self.template_file = template_file
self.stack_name = stack_name
Expand Down Expand Up @@ -113,6 +116,7 @@ def __init__(
self.max_wait_duration = max_wait_duration
self._language_extensions_enabled = resolve_language_extensions_enabled(language_extensions)
self.express = express
self.output = output

def __enter__(self):
return self
Expand All @@ -128,6 +132,8 @@ def run(self):
"""
Execute deployment based on the argument provided by customers and samconfig.toml.
"""
if self.output == "json":
logging.getLogger("samcli").setLevel(logging.WARNING)

# Parse parameters
with open(self.template_file, "r") as handle:
Expand Down Expand Up @@ -155,25 +161,31 @@ def run(self):
s3_client = boto3.client("s3", region_name=self.region if self.region else None, config=boto_config)

self.s3_uploader = S3Uploader(
s3_client, self.s3_bucket, self.s3_prefix, self.kms_key_id, self.force_upload, self.no_progressbar
s3_client,
self.s3_bucket,
self.s3_prefix,
self.kms_key_id,
self.force_upload,
True if self.output == "json" else self.no_progressbar,
)

self.deployer = Deployer(cloudformation_client, client_sleep=self.poll_delay)
self.deployer = Deployer(cloudformation_client, client_sleep=self.poll_delay, output_mode=self.output)

region = s3_client._client_config.region_name if s3_client else self.region # pylint: disable=W0212
display_parameter_overrides = hide_noecho_parameter_overrides(template_dict, self.parameter_overrides)
print_deploy_args(
self.stack_name,
self.s3_bucket,
self.image_repositories if isinstance(self.image_repositories, dict) else self.image_repository,
region,
self.capabilities,
display_parameter_overrides,
self.confirm_changeset,
self.signing_profiles,
self.use_changeset,
self.disable_rollback,
)
if self.output != "json":
display_parameter_overrides = hide_noecho_parameter_overrides(template_dict, self.parameter_overrides)
print_deploy_args(
self.stack_name,
self.s3_bucket,
self.image_repositories if isinstance(self.image_repositories, dict) else self.image_repository,
region,
self.capabilities,
display_parameter_overrides,
self.confirm_changeset,
self.signing_profiles,
self.use_changeset,
self.disable_rollback,
)
return self.deploy(
self.stack_name,
template_str,
Expand Down Expand Up @@ -254,7 +266,13 @@ def deploy(

for resource, authorization_required in auth_required_per_resource:
if not authorization_required:
click.secho(f"{resource} has no authentication.", fg="yellow")
if self.output == "json":
sys.stdout.write(
json.dumps({"type": "warning", "message": "no authentication", "resource": resource}) + "\n"
)
sys.stdout.flush()
else:
click.secho(f"{resource} has no authentication.", fg="yellow")

assert self.deployer is not None
if self.express:
Expand All @@ -275,12 +293,32 @@ def deploy(
tags=tags,
deployment_config=deployment_config,
)
click.echo(self.MSG_SHOWCASE_CHANGESET.format(changeset_id=result["Id"]))
if self.output != "json":
click.echo(self.MSG_SHOWCASE_CHANGESET.format(changeset_id=result["Id"]))

if no_execute_changeset:
if self.output == "json":
sys.stdout.write(
json.dumps({"type": "result", "status": "CHANGESET_CREATED", "changeset_id": result["Id"]})
+ "\n"
)
sys.stdout.flush()
return

if confirm_changeset:
if self.output == "json":
sys.stdout.write(
json.dumps(
{
"type": "result",
"status": "CONFIRMATION_REQUIRED",
"changeset_id": result["Id"],
}
)
+ "\n"
)
sys.stdout.flush()
return
click.secho(self.MSG_CONFIRM_CHANGESET_HEADER, fg="yellow")
click.secho("=" * len(self.MSG_CONFIRM_CHANGESET_HEADER), fg="yellow")
if not click.confirm(f"{self.MSG_CONFIRM_CHANGESET}", default=False):
Expand All @@ -291,22 +329,36 @@ def deploy(
self.deployer.wait_for_execute(
stack_name, changeset_type, disable_rollback, self.on_failure, marker_time, self.max_wait_duration
)
click.echo(self.MSG_EXECUTE_SUCCESS.format(stack_name=stack_name, region=region))
if self.express:
click.secho(
"\nDeployed with CloudFormation Express mode. "
"Resources may still be stabilizing in the background.",
fg="yellow",
if self.output == "json":
sys.stdout.write(
json.dumps({"type": "result", "status": "SUCCESS", "stack_name": stack_name, "region": region})
+ "\n"
)
sys.stdout.flush()
else:
click.echo(self.MSG_EXECUTE_SUCCESS.format(stack_name=stack_name, region=region))
if self.express:
click.secho(
"\nDeployed with CloudFormation Express mode. "
"Resources may still be stabilizing in the background.",
fg="yellow",
)

except deploy_exceptions.ChangeEmptyError as ex:
if fail_on_empty_changeset:
raise
click.echo(str(ex))
except deploy_exceptions.DeployFailedError:
if self.output == "json":
sys.stdout.write(json.dumps({"type": "result", "status": "NO_CHANGES", "message": str(ex)}) + "\n")
sys.stdout.flush()
else:
click.echo(str(ex))
except deploy_exceptions.DeployFailedError as ex:
# Failed to deploy, check for DELETE action otherwise skip
if self.on_failure == FailureMode.DELETE:
self.deployer.rollback_delete_stack(stack_name)
if self.output == "json":
sys.stdout.write(json.dumps({"type": "result", "status": "FAILED", "error": str(ex)}) + "\n")
sys.stdout.flush()
raise

else:
Expand Down
Loading
Loading