Skip to content

Commit

Permalink
export import configs
Browse files Browse the repository at this point in the history
  • Loading branch information
isra-fel committed Jun 14, 2022
1 parent 23ffff9 commit 65885b6
Show file tree
Hide file tree
Showing 22 changed files with 763 additions and 98 deletions.
2 changes: 1 addition & 1 deletion src/Accounts/Accounts/Az.Accounts.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ CmdletsToExport = 'Disable-AzDataCollection', 'Disable-AzContextAutosave',
'Register-AzModule', 'Enable-AzureRmAlias', 'Disable-AzureRmAlias',
'Uninstall-AzureRm', 'Invoke-AzRestMethod', 'Get-AzAccessToken',
'Open-AzSurveyLink', 'Get-AzConfig', 'Update-AzConfig',
'Clear-AzConfig'
'Clear-AzConfig', 'Export-AzConfig', 'Import-AzConfig'

# Variables to export from this module
# VariablesToExport = @()
Expand Down
1 change: 1 addition & 0 deletions src/Accounts/Accounts/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
-->

## Upcoming Release
* Supported exporting and importing configurations by `Export-AzConfig` and `Import-AzConfig`.
* Fixed an issue that Az.Accounts failed to be imported if multiple environment variables, which only differ by case, are set. [#18304]

## Version 2.8.0
Expand Down
3 changes: 2 additions & 1 deletion src/Accounts/Accounts/Config/ClearConfigCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.Common.Exceptions;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.PowerShell.Common.Config;
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
Expand All @@ -24,7 +25,7 @@

namespace Microsoft.Azure.Commands.Common.Authentication.Config
{
[Cmdlet("Clear", "AzConfig", SupportsShouldProcess = true, DefaultParameterSetName = ClearAll)]
[Cmdlet("Clear", AzureRMConstants.AzureRMPrefix + "Config", SupportsShouldProcess = true, DefaultParameterSetName = ClearAll)]
[OutputType(typeof(bool))]
[CmdletPreview(PreviewMessage)]
public class ClearConfigCommand : ConfigCommandBase, IDynamicParameters
Expand Down
2 changes: 1 addition & 1 deletion src/Accounts/Accounts/Config/ConfigCommandBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ namespace Microsoft.Azure.Commands.Common.Authentication.Config
{
public abstract class ConfigCommandBase : AzureRMCmdlet
{
protected const string PreviewMessage = "The cmdlet group \"AzConfig\" is in preview. Feedback is welcome: https://aka.ms/azpsissue";
public const string PreviewMessage = "The cmdlet group \"AzConfig\" is in preview. Feedback is welcome: https://aka.ms/azpsissue";

private readonly RuntimeDefinedParameterDictionary _dynamicParameters = new RuntimeDefinedParameterDictionary();

Expand Down
67 changes: 67 additions & 0 deletions src/Accounts/Accounts/Config/ExportConfigCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.Common.Exceptions;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.PowerShell.Common.Config;
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.Common.Authentication.Config
{
[Cmdlet("Export", AzureRMConstants.AzureRMPrefix + "Config", SupportsShouldProcess = true)]
[CmdletPreview(ConfigCommandBase.PreviewMessage)]
[OutputType(typeof(bool))]
public class ExportConfigCommand : AzureRMCmdlet
{
[Parameter(Position = 1, Mandatory = true, HelpMessage = "Specifies the path of the file to which to save the configs.")]
[ValidateNotNullOrEmpty]
public string Path { get; set; }

[Parameter(HelpMessage = "Overwrites the given file if it exists.")]
public SwitchParameter Force { get; set; }

[Parameter(HelpMessage = "Returns a boolean value indicating success or failure.")]
public SwitchParameter PassThru { get; set; }

public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
var dataStore = AzureSession.Instance.DataStore;
AzureSession.Instance.TryGetComponent<IConfigManager>(nameof(IConfigManager), out var configManager);
if (!dataStore.FileExists(configManager.ConfigFilePath))
{
throw new AzPSApplicationException("No configs to export. Make sure at least one config is set by `Update-AzConfig` with the `CurrentUser` scope.", ErrorKind.UserError);
}

Path = ResolveUserPath(Path);
WriteDebugWithTimestamp($"[{nameof(ExportConfigCommand)}] Exporting configs to {Path}.");
ConfirmAction(
Force,
$"Overwrite existing file at {Path}",
$"Export configs to file at {Path}",
$"all the configs at {ConfigScope.CurrentUser} scope",
() =>
{
new JsonConfigHelper(configManager.ConfigFilePath, dataStore).ExportConfigFile(Path);
WriteDebugWithTimestamp($"[{nameof(ExportConfigCommand)}] Configs are exported to {Path} successfully.");
if (PassThru)
{
WriteObject(true);
}
},
() => dataStore.FileExists(Path)); // only ask for confirmation if file exists
}
}
}
54 changes: 54 additions & 0 deletions src/Accounts/Accounts/Config/ImportConfigCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.PowerShell.Common.Config;
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.Common.Authentication.Config
{
[Cmdlet("Import", AzureRMConstants.AzureRMPrefix + "Config", SupportsShouldProcess = true)]
[CmdletPreview(ConfigCommandBase.PreviewMessage)]
[OutputType(typeof(bool))]
public class ImportConfigCommand : AzureRMCmdlet
{
[Parameter(Position = 1, Mandatory = true, HelpMessage = "Specifies the path to configuration saved by using Export-AzConfig.")]
[ValidateNotNullOrEmpty]
public string Path { get; set; }

[Parameter(HelpMessage = "Returns a boolean value indicating success or failure.")]
public SwitchParameter PassThru { get; set; }

public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();

Path = ResolveUserPath(Path);
WriteDebugWithTimestamp($"[{nameof(ImportConfigCommand)}] Importing configs from {Path}.");
base.ConfirmAction($"Import configs from config file", Path, () =>
{
AzureSession.Instance.TryGetComponent<IConfigManager>(nameof(IConfigManager), out var configManager);
new JsonConfigHelper(configManager.ConfigFilePath, AzureSession.Instance.DataStore).ImportConfigFile(Path);
WriteDebugWithTimestamp($"[{nameof(ImportConfigCommand)}] Configs are imported from {Path} successfully. Rebuilding config manager.");
configManager.BuildConfig();
WriteDebugWithTimestamp($"[{nameof(ImportConfigCommand)}] Rebuilt config manager.");
if (PassThru)
{
WriteObject(true);
}
});
}
}
}
3 changes: 2 additions & 1 deletion src/Accounts/Accounts/Config/UpdateConfigCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

using Microsoft.Azure.Commands.Common.Exceptions;
using Microsoft.Azure.Commands.Profile.Models;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.PowerShell.Common.Config;
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
using System;
Expand All @@ -24,7 +25,7 @@

namespace Microsoft.Azure.Commands.Common.Authentication.Config
{
[Cmdlet("Update", "AzConfig", SupportsShouldProcess = true)]
[Cmdlet("Update", AzureRMConstants.AzureRMPrefix + "Config", SupportsShouldProcess = true)]
[OutputType(typeof(PSConfig))]
[CmdletPreview(PreviewMessage)]
public class UpdateConfigCommand : ConfigCommandBase, IDynamicParameters
Expand Down
6 changes: 6 additions & 0 deletions src/Accounts/Accounts/help/Az.Accounts.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ machine. Data is collected by default unless you explicitly opt out.
### [Enable-AzureRmAlias](Enable-AzureRmAlias.md)
Enables AzureRm prefix aliases for Az modules.

### [Export-AzConfig](Export-AzConfig.md)
Exports all the configs into a file so that it can be imported on another machine.

### [Get-AzAccessToken](Get-AzAccessToken.md)
Get raw access token. When using -ResourceUrl, please make sure the value does match current Azure environment. You may refer to the value of `(Get-AzContext).Environment`.

Expand All @@ -81,6 +84,9 @@ Get subscriptions that the current account can access.
### [Get-AzTenant](Get-AzTenant.md)
Gets tenants that are authorized for the current user.

### [Import-AzConfig](Import-AzConfig.md)
Imports configs from a file that was previously exported by `Export-AzConfig`.

### [Import-AzContext](Import-AzContext.md)
Loads Azure authentication information from a file.

Expand Down
2 changes: 1 addition & 1 deletion src/Accounts/Accounts/help/Clear-AzConfig.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ By default it is CurrentUser.
Type: Microsoft.Azure.PowerShell.Common.Config.ConfigScope
Parameter Sets: (All)
Aliases:
Accepted values: CurrentUser, Process, Default
Accepted values: CurrentUser, Process

Required: False
Position: Named
Expand Down
140 changes: 140 additions & 0 deletions src/Accounts/Accounts/help/Export-AzConfig.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
---
external help file: Microsoft.Azure.PowerShell.Cmdlets.Accounts.dll-Help.xml
Module Name: Az.Accounts
online version: https://docs.microsoft.com/powershell/module/az.accounts/export-azconfig
schema: 2.0.0
---

# Export-AzConfig

## SYNOPSIS
Exports all the configs into a file so that it can be imported on another machine.

## SYNTAX

```
Export-AzConfig [-Path] <String> [-Force] [-PassThru] [-DefaultProfile <IAzureContextContainer>] [-WhatIf]
[-Confirm] [<CommonParameters>]
```

## DESCRIPTION
The `Export-AzConfig` cmdlet exports all the configs that are set at the "CurrentUser" scope into a file at given path in JSON format. The file can then be imported by `Import-AzConfig` for example on another machine.

## EXAMPLES

### Example 1
```powershell
Export-AzConfig -Path ./config.json
```

This example exports the configs to `./config.json` file which can later be imported via `Import-AzConfig`.

## PARAMETERS

### -DefaultProfile
The credentials, account, tenant, and subscription used for communication with Azure.

```yaml
Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core.IAzureContextContainer
Parameter Sets: (All)
Aliases: AzContext, AzureRmContext, AzureCredential

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Force
Overwrites the given file if it exists.
```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -PassThru
Returns a boolean value indicating success or failure.
```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Path
Specifies the path of the file to which to save the configs.
```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -Confirm
Prompts you for confirmation before running the cmdlet.
```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: cf

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.
```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: wi

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```
### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).
## INPUTS
### None
## OUTPUTS
### System.Boolean
## NOTES
## RELATED LINKS
[Import-AzConfig](./Import-AzConfig.md)
2 changes: 1 addition & 1 deletion src/Accounts/Accounts/help/Get-AzConfig.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ By default it is CurrentUser.
Type: Microsoft.Azure.PowerShell.Common.Config.ConfigScope
Parameter Sets: (All)
Aliases:
Accepted values: CurrentUser, Process, Default
Accepted values: CurrentUser, Process, Default, Environment

Required: False
Position: Named
Expand Down
Loading

0 comments on commit 65885b6

Please sign in to comment.