Skip to content
28 changes: 13 additions & 15 deletions src/azure-cli/azure/cli/command_modules/mysql/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from azure.core.paging import ItemPaged
from azure.core.rest import HttpRequest
from azure.cli.core.commands import LongRunningOperation, AzArgumentContext, _is_poller
from azure.cli.core.azclierror import RequiredArgumentMissingError, InvalidArgumentValueError, AuthenticationError
from azure.cli.core.azclierror import RequiredArgumentMissingError, InvalidArgumentValueError, AuthenticationError, ClientRequestError
from azure.cli.command_modules.role.custom import create_service_principal_for_rbac
from azure.mgmt.mysqlflexibleservers import models
from azure.mgmt.resource.resources.models import ResourceGroup
Expand Down Expand Up @@ -433,9 +433,15 @@ def run_cmd(args, **kwargs):
return core_run_cmd(args, **kwargs)


def run_subprocess(command, stdout_show=None):
def run_subprocess(command, stdout_show=None, input_data=None):
commands = list(command)
commands[0] = resolve_executable(commands[0])
if input_data is not None:
# Keep caller-provided input out of subprocess diagnostics.
process = subprocess.run(commands, input=input_data, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if process.returncode:
raise ClientRequestError("Command '{}' failed with exit code {}.".format(commands[0], process.returncode))
return
if stdout_show:
process = subprocess.Popen(commands)
else:
Expand All @@ -460,25 +466,17 @@ def register_credential_secrets(cmd, database_engine, server, repository):
app.pop('displayName')
app.pop('name')

app_key_val = []
for key, val in app.items():
app_key_val.append('"{}": "{}"'.format(key, val))

app_json = ',\n '.join(app_key_val)
app_json = '{\n ' + app_json + '\n}'
credential_file = "./temp_app_credential.txt"
with open(credential_file, "w") as f:
f.write(app_json)
run_subprocess(["gh", "secret", "set", AZURE_CREDENTIALS, "--repo", repository, "<", credential_file])
os.remove(credential_file)
run_subprocess(['gh', 'secret', 'set', AZURE_CREDENTIALS, '--repo', repository],
input_data=json.dumps(app).encode('utf-8'))


def register_connection_secrets(server, database_name, administrator_login,
administrator_login_password, repository, connection_string_name):
logger.warning("Added secret %s to github repository", connection_string_name)
connection_string = "Server={}; Port=3306; Database={}; Uid={}; Pwd={}; SslMode=Preferred;".format(
server.fully_qualified_domain_name, database_name, administrator_login, administrator_login_password)
run_subprocess(['gh', 'secret', 'set', connection_string_name, '--repo', repository, '-b', connection_string])
run_subprocess(['gh', 'secret', 'set', connection_string_name, '--repo', repository],
input_data=connection_string.encode('utf-8'))
logger.warning("Added secret %s to github repository", connection_string_name)


def fill_action_template(cmd, database_engine, server, database_name, administrator_login,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def test_setup_uploads_missing_credentials_through_stdin(self):

self.upload.assert_called_once_with(
[self.executable, 'secret', 'set', util.AZURE_CREDENTIALS, '--repo', 'owner/repository'],
input=mock.ANY, capture_output=True, check=False)
input=mock.ANY, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.assertEqual(json.loads(self.upload.call_args.kwargs['input']), self.credentials)
self.files.assert_any_call(self.workflow, 'w', encoding='utf8')
self.assertEqual(self.git.call_args_list, [
Expand All @@ -143,19 +143,29 @@ def test_setup_uploads_missing_credentials_through_stdin(self):

def test_setup_stops_after_credential_upload_failure(self):
self.upload.return_value.returncode = 1
self.upload.return_value.stderr = self.credentials['clientSecret'].encode('UTF-8')
self.upload.return_value.stdout = b'unexpected upload stdout'
self.upload.return_value.stderr = (
self.credentials['clientSecret'].encode('UTF-8') + b' unexpected upload stderr')
with self.assertLogs(util.logger.name, level='WARNING') as logs:
with self.assertRaisesRegex(ClientRequestError, 'Failed to set the AZURE_CREDENTIALS secret') as error:
deploy.github_actions_setup(
mock.Mock(), self.client, 'test-rg', 'server', 'database', 'admin', 'unused',
'schema file.sql', 'owner/repository', action_name='deploy database',
branch='feature/database', allow_push=True)

self.upload.assert_called_once()
self.upload.assert_called_once_with(
[self.executable, 'secret', 'set', util.AZURE_CREDENTIALS, '--repo', 'owner/repository'],
input=mock.ANY, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.git.assert_not_called()
self.files.assert_not_called()
self.assertNotIn(self.credentials['clientSecret'], str(error.exception))
self.assertNotIn(self.credentials['clientSecret'], '\n'.join(logs.output))
self.assertEqual(
str(error.exception),
'Failed to set the AZURE_CREDENTIALS secret in the GitHub repository (exit code 1).')
self.assertEqual(error.exception.recommendations, [
'Check your GitHub CLI authentication and repository permissions, then retry.'])
diagnostics = '\n'.join([str(error.exception), *error.exception.recommendations, *logs.output])
for value in (self.credentials['clientSecret'], 'unexpected upload stdout', 'unexpected upload stderr'):
self.assertNotIn(value, diagnostics)


@unittest.skipUnless(sys.platform == 'win32', 'Windows executable search semantics')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,16 +76,15 @@ def test_setup_pins_all_probe_login_secret_and_git_launches(self):
[self.git, 'rev-parse', '--show-toplevel'],
[self.gh, 'secret', 'list', '--repo', 'owner/repo'],
[self.gh, 'secret', 'set', 'AZURE_CREDENTIALS', '--repo', 'owner/repo'],
[self.gh, 'secret', 'set', 'SERVER_DATABASE_POSTGRESQL_CONNECTION_STRING', '--repo', 'owner/repo'],
[self.git, 'rev-parse', '--show-toplevel']])
credentials = self.run.call_args_list[-2].kwargs
credentials = self.run.call_args_list[-3].kwargs
self.assertEqual(json.loads(credentials['input']), {
'clientId': 'app', 'clientSecret': 'unused', 'tenantId': 'tenant', 'subscriptionId': 'sub'})
self.assertIn(b'host=server.example', self.run.call_args_list[-2].kwargs['input'])
launches = [c.args[0] for c in self.popen.call_args_list]
self.assertEqual(launches[0], [self.gh, 'auth', 'login'])
self.assertEqual(launches[1][:7], [
self.gh, 'secret', 'set', 'SERVER_DATABASE_POSTGRESQL_CONNECTION_STRING', '--repo', 'owner/repo', '-b'])
self.assertEqual(len(launches[1]), 8)
self.assertEqual(launches[2:], [
self.assertEqual(launches[1:], [
[self.git, 'add', 'C:/work with spaces/.github/workflows/deploy action.yml'],
[self.git, 'commit', '-m', 'Add github action file'],
[self.git, 'push', 'origin', 'topic branch']])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,12 +284,19 @@ def run_cmd(args, **kwargs):
return core_run_cmd(args, **kwargs)


def run_subprocess(command, stdout_show=None):
command = [resolve_executable(command[0])] + command[1:]
def run_subprocess(command, stdout_show=None, input_data=None):
commands = list(command)
commands[0] = resolve_executable(commands[0])
if input_data is not None:
# Keep caller-provided input out of subprocess diagnostics.
process = subprocess.run(commands, input=input_data, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if process.returncode:
raise ClientRequestError("Command '{}' failed with exit code {}.".format(commands[0], process.returncode))
return
if stdout_show:
process = subprocess.Popen(command, shell=False)
process = subprocess.Popen(commands, shell=False)
else:
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
process = subprocess.Popen(commands, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
process.wait()
if process.returncode:
logger.warning(process.stderr.read().strip().decode('UTF-8'))
Expand All @@ -310,7 +317,7 @@ def register_credential_secrets(cmd, database_engine, server, repository, gh_pat

process = subprocess.run(
[gh_path, 'secret', 'set', AZURE_CREDENTIALS, '--repo', repository],
input=json.dumps(app).encode('UTF-8'), capture_output=True, check=False)
input=json.dumps(app).encode('utf-8'), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if process.returncode:
raise ClientRequestError(
'Failed to set the AZURE_CREDENTIALS secret in the GitHub repository (exit code {}).'.format(
Expand All @@ -320,9 +327,10 @@ def register_credential_secrets(cmd, database_engine, server, repository, gh_pat

def register_connection_secrets(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, repository, connection_string_name, gh_path=None):
gh_path = resolve_executable(gh_path or "gh")
logger.warning("Added secret %s to github repository", connection_string_name)
connection_string = "host={} port=5432 dbname={} user={} password={} sslmode=require".format(server.fully_qualified_domain_name, database_name, administrator_login, administrator_login_password)
run_subprocess([gh_path, 'secret', 'set', connection_string_name, '--repo', repository, '-b', connection_string])
run_subprocess([gh_path, 'secret', 'set', connection_string_name, '--repo', repository],
input_data=connection_string.encode('utf-8'))
logger.warning("Added secret %s to github repository", connection_string_name)


def fill_action_template(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, file_name, action_name, repository, gh_path=None, git_path=None):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,20 @@
# pylint: disable=unused-argument, line-too-long, import-outside-toplevel, raise-missing-from
import datetime as dt
from datetime import datetime
import errno
import json
import os
import random
import subprocess
import secrets
import shlex
import string
import sys
import yaml
from knack.log import get_logger
from knack.prompting import prompt_y_n, NoTTYException
from azure.mgmt.core.tools import parse_resource_id
from azure.cli.core.util import CLIError, run_cmd
from azure.cli.core.azclierror import AuthenticationError
from azure.cli.core.util import CLIError, get_safe_executable_path, run_cmd as core_run_cmd
from azure.cli.core.azclierror import AuthenticationError, ClientRequestError
from azure.core.exceptions import HttpResponseError
from azure.core.paging import ItemPaged
from azure.cli.core.commands.client_factory import get_subscription_id
Expand Down Expand Up @@ -298,8 +300,32 @@ def _resolve_api_version(client, provider_namespace, resource_type, parent_path)
.format(resource_type))


def run_subprocess(command, stdout_show=None):
commands = shlex.split(command)
def resolve_executable(executable):
"""Bind Windows tool launches to installed executables without changing Unix lookup."""
if sys.platform != 'win32' or os.path.dirname(executable):
return executable
name = executable if os.path.splitext(executable)[1] else executable + '.exe'
resolved = get_safe_executable_path(name)
if resolved is None:
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), executable)
return resolved


def run_cmd(args, **kwargs):
if isinstance(args, list) and args:
args = [resolve_executable(args[0]), *args[1:]]
return core_run_cmd(args, **kwargs)


def run_subprocess(command, stdout_show=None, input_data=None):
commands = list(command)
commands[0] = resolve_executable(commands[0])
if input_data is not None:
# Keep caller-provided input out of subprocess diagnostics.
process = subprocess.run(commands, input=input_data, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if process.returncode:
raise ClientRequestError("Command '{}' failed with exit code {}.".format(commands[0], process.returncode))
return
if stdout_show:
process = subprocess.Popen(commands)
else:
Expand All @@ -321,23 +347,15 @@ def register_credential_secrets(cmd, database_engine, server, repository):
app.pop('displayName')
app.pop('name')

app_key_val = []
for key, val in app.items():
app_key_val.append('"{}": "{}"'.format(key, val))

app_json = ',\n '.join(app_key_val)
app_json = '{\n ' + app_json + '\n}'
credential_file = "./temp_app_credential.txt"
with open(credential_file, "w") as f:
f.write(app_json)
run_subprocess('gh secret set {} --repo {} < {}'.format(AZURE_CREDENTIALS, repository, credential_file))
os.remove(credential_file)
run_subprocess(['gh', 'secret', 'set', AZURE_CREDENTIALS, '--repo', repository],
input_data=json.dumps(app).encode('utf-8'))


def register_connection_secrets(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, repository, connection_string_name):
logger.warning("Added secret %s to github repository", connection_string_name)
connection_string = "Server={}; Port=3306; Database={}; Uid={}; Pwd={}; SslMode=Preferred;".format(server.fully_qualified_domain_name, database_name, administrator_login, administrator_login_password)
run_subprocess('gh secret set {} --repo {} -b"{}"'.format(connection_string_name, repository, connection_string))
run_subprocess(['gh', 'secret', 'set', connection_string_name, '--repo', repository],
input_data=connection_string.encode('utf-8'))
logger.warning("Added secret %s to github repository", connection_string_name)


def fill_action_template(cmd, database_engine, server, database_name, administrator_login, administrator_login_password, file_name, action_name, repository):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
from knack.log import get_logger
from knack.util import CLIError
from urllib.request import urlretrieve
from azure.cli.core.util import sdk_no_wait, user_confirmation, run_cmd
from azure.cli.core.util import sdk_no_wait, user_confirmation
from azure.cli.core.azclierror import ClientRequestError
from ._flexible_server_util import run_subprocess
from ._flexible_server_util import run_cmd, run_subprocess
from .validators import validate_public_access_server, validate_resource_group, check_resource_group

logger = get_logger(__name__)
Expand Down Expand Up @@ -195,17 +195,20 @@ def github_actions_run(action_name, branch):

gitcli_check_and_login()
logger.warning("Created an event for %s.yml in branch %s", action_name, branch)
run_subprocess("gh workflow run {}.yml --ref {}".format(action_name, branch))
run_subprocess(["gh", "workflow", "run", action_name + ".yml", "--ref", branch])


def gitcli_check_and_login():
output = run_cmd(["gh"], capture_output=True)
try:
output = run_cmd(["gh"], capture_output=True)
except FileNotFoundError as ex:
raise ClientRequestError('Please install "Github CLI" to run this command.') from ex
if output.returncode:
raise ClientRequestError('Please install "Github CLI" to run this command.')

output = run_cmd(["gh", "auth", "status"], capture_output=True)
if output.returncode:
run_subprocess("gh auth login", stdout_show=True)
run_subprocess(["gh", "auth", "login"], stdout_show=True)


# Custom functions for server logs
Expand Down
Loading
Loading