Skip to content

Commit 6acd4bf

Browse files
authored
export import configs (#18371)
1 parent f3123d7 commit 6acd4bf

22 files changed

+763
-98
lines changed

src/Accounts/Accounts/Az.Accounts.psd1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ CmdletsToExport = 'Disable-AzDataCollection', 'Disable-AzContextAutosave',
109109
'Register-AzModule', 'Enable-AzureRmAlias', 'Disable-AzureRmAlias',
110110
'Uninstall-AzureRm', 'Invoke-AzRestMethod', 'Get-AzAccessToken',
111111
'Open-AzSurveyLink', 'Get-AzConfig', 'Update-AzConfig',
112-
'Clear-AzConfig'
112+
'Clear-AzConfig', 'Export-AzConfig', 'Import-AzConfig'
113113

114114
# Variables to export from this module
115115
# VariablesToExport = @()

src/Accounts/Accounts/ChangeLog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
-->
2020

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

2425
## Version 2.8.0

src/Accounts/Accounts/Config/ClearConfigCommand.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
// ----------------------------------------------------------------------------------
1414

1515
using Microsoft.Azure.Commands.Common.Exceptions;
16+
using Microsoft.Azure.Commands.ResourceManager.Common;
1617
using Microsoft.Azure.PowerShell.Common.Config;
1718
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
1819
using Microsoft.WindowsAzure.Commands.Utilities.Common;
@@ -24,7 +25,7 @@
2425

2526
namespace Microsoft.Azure.Commands.Common.Authentication.Config
2627
{
27-
[Cmdlet("Clear", "AzConfig", SupportsShouldProcess = true, DefaultParameterSetName = ClearAll)]
28+
[Cmdlet("Clear", AzureRMConstants.AzureRMPrefix + "Config", SupportsShouldProcess = true, DefaultParameterSetName = ClearAll)]
2829
[OutputType(typeof(bool))]
2930
[CmdletPreview(PreviewMessage)]
3031
public class ClearConfigCommand : ConfigCommandBase, IDynamicParameters

src/Accounts/Accounts/Config/ConfigCommandBase.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ namespace Microsoft.Azure.Commands.Common.Authentication.Config
2424
{
2525
public abstract class ConfigCommandBase : AzureRMCmdlet
2626
{
27-
protected const string PreviewMessage = "The cmdlet group \"AzConfig\" is in preview. Feedback is welcome: https://aka.ms/azpsissue";
27+
public const string PreviewMessage = "The cmdlet group \"AzConfig\" is in preview. Feedback is welcome: https://aka.ms/azpsissue";
2828

2929
private readonly RuntimeDefinedParameterDictionary _dynamicParameters = new RuntimeDefinedParameterDictionary();
3030

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// ----------------------------------------------------------------------------------
2+
//
3+
// Copyright Microsoft Corporation
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
// You may obtain a copy of the License at
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
// ----------------------------------------------------------------------------------
14+
15+
using Microsoft.Azure.Commands.Common.Exceptions;
16+
using Microsoft.Azure.Commands.ResourceManager.Common;
17+
using Microsoft.Azure.PowerShell.Common.Config;
18+
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
19+
using System.Management.Automation;
20+
21+
namespace Microsoft.Azure.Commands.Common.Authentication.Config
22+
{
23+
[Cmdlet("Export", AzureRMConstants.AzureRMPrefix + "Config", SupportsShouldProcess = true)]
24+
[CmdletPreview(ConfigCommandBase.PreviewMessage)]
25+
[OutputType(typeof(bool))]
26+
public class ExportConfigCommand : AzureRMCmdlet
27+
{
28+
[Parameter(Position = 1, Mandatory = true, HelpMessage = "Specifies the path of the file to which to save the configs.")]
29+
[ValidateNotNullOrEmpty]
30+
public string Path { get; set; }
31+
32+
[Parameter(HelpMessage = "Overwrites the given file if it exists.")]
33+
public SwitchParameter Force { get; set; }
34+
35+
[Parameter(HelpMessage = "Returns a boolean value indicating success or failure.")]
36+
public SwitchParameter PassThru { get; set; }
37+
38+
public override void ExecuteCmdlet()
39+
{
40+
base.ExecuteCmdlet();
41+
var dataStore = AzureSession.Instance.DataStore;
42+
AzureSession.Instance.TryGetComponent<IConfigManager>(nameof(IConfigManager), out var configManager);
43+
if (!dataStore.FileExists(configManager.ConfigFilePath))
44+
{
45+
throw new AzPSApplicationException("No configs to export. Make sure at least one config is set by `Update-AzConfig` with the `CurrentUser` scope.", ErrorKind.UserError);
46+
}
47+
48+
Path = ResolveUserPath(Path);
49+
WriteDebugWithTimestamp($"[{nameof(ExportConfigCommand)}] Exporting configs to {Path}.");
50+
ConfirmAction(
51+
Force,
52+
$"Overwrite existing file at {Path}",
53+
$"Export configs to file at {Path}",
54+
$"all the configs at {ConfigScope.CurrentUser} scope",
55+
() =>
56+
{
57+
new JsonConfigHelper(configManager.ConfigFilePath, dataStore).ExportConfigFile(Path);
58+
WriteDebugWithTimestamp($"[{nameof(ExportConfigCommand)}] Configs are exported to {Path} successfully.");
59+
if (PassThru)
60+
{
61+
WriteObject(true);
62+
}
63+
},
64+
() => dataStore.FileExists(Path)); // only ask for confirmation if file exists
65+
}
66+
}
67+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// ----------------------------------------------------------------------------------
2+
//
3+
// Copyright Microsoft Corporation
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
// You may obtain a copy of the License at
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
// ----------------------------------------------------------------------------------
14+
15+
using Microsoft.Azure.Commands.ResourceManager.Common;
16+
using Microsoft.Azure.PowerShell.Common.Config;
17+
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
18+
using System.Management.Automation;
19+
20+
namespace Microsoft.Azure.Commands.Common.Authentication.Config
21+
{
22+
[Cmdlet("Import", AzureRMConstants.AzureRMPrefix + "Config", SupportsShouldProcess = true)]
23+
[CmdletPreview(ConfigCommandBase.PreviewMessage)]
24+
[OutputType(typeof(bool))]
25+
public class ImportConfigCommand : AzureRMCmdlet
26+
{
27+
[Parameter(Position = 1, Mandatory = true, HelpMessage = "Specifies the path to configuration saved by using Export-AzConfig.")]
28+
[ValidateNotNullOrEmpty]
29+
public string Path { get; set; }
30+
31+
[Parameter(HelpMessage = "Returns a boolean value indicating success or failure.")]
32+
public SwitchParameter PassThru { get; set; }
33+
34+
public override void ExecuteCmdlet()
35+
{
36+
base.ExecuteCmdlet();
37+
38+
Path = ResolveUserPath(Path);
39+
WriteDebugWithTimestamp($"[{nameof(ImportConfigCommand)}] Importing configs from {Path}.");
40+
base.ConfirmAction($"Import configs from config file", Path, () =>
41+
{
42+
AzureSession.Instance.TryGetComponent<IConfigManager>(nameof(IConfigManager), out var configManager);
43+
new JsonConfigHelper(configManager.ConfigFilePath, AzureSession.Instance.DataStore).ImportConfigFile(Path);
44+
WriteDebugWithTimestamp($"[{nameof(ImportConfigCommand)}] Configs are imported from {Path} successfully. Rebuilding config manager.");
45+
configManager.BuildConfig();
46+
WriteDebugWithTimestamp($"[{nameof(ImportConfigCommand)}] Rebuilt config manager.");
47+
if (PassThru)
48+
{
49+
WriteObject(true);
50+
}
51+
});
52+
}
53+
}
54+
}

src/Accounts/Accounts/Config/UpdateConfigCommand.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
using Microsoft.Azure.Commands.Common.Exceptions;
1616
using Microsoft.Azure.Commands.Profile.Models;
17+
using Microsoft.Azure.Commands.ResourceManager.Common;
1718
using Microsoft.Azure.PowerShell.Common.Config;
1819
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
1920
using System;
@@ -24,7 +25,7 @@
2425

2526
namespace Microsoft.Azure.Commands.Common.Authentication.Config
2627
{
27-
[Cmdlet("Update", "AzConfig", SupportsShouldProcess = true)]
28+
[Cmdlet("Update", AzureRMConstants.AzureRMPrefix + "Config", SupportsShouldProcess = true)]
2829
[OutputType(typeof(PSConfig))]
2930
[CmdletPreview(PreviewMessage)]
3031
public class UpdateConfigCommand : ConfigCommandBase, IDynamicParameters

src/Accounts/Accounts/help/Az.Accounts.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@ machine. Data is collected by default unless you explicitly opt out.
5656
### [Enable-AzureRmAlias](Enable-AzureRmAlias.md)
5757
Enables AzureRm prefix aliases for Az modules.
5858

59+
### [Export-AzConfig](Export-AzConfig.md)
60+
Exports all the configs into a file so that it can be imported on another machine.
61+
5962
### [Get-AzAccessToken](Get-AzAccessToken.md)
6063
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`.
6164

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

87+
### [Import-AzConfig](Import-AzConfig.md)
88+
Imports configs from a file that was previously exported by `Export-AzConfig`.
89+
8490
### [Import-AzContext](Import-AzContext.md)
8591
Loads Azure authentication information from a file.
8692

src/Accounts/Accounts/help/Clear-AzConfig.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ By default it is CurrentUser.
168168
Type: Microsoft.Azure.PowerShell.Common.Config.ConfigScope
169169
Parameter Sets: (All)
170170
Aliases:
171-
Accepted values: CurrentUser, Process, Default
171+
Accepted values: CurrentUser, Process
172172

173173
Required: False
174174
Position: Named
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
---
2+
external help file: Microsoft.Azure.PowerShell.Cmdlets.Accounts.dll-Help.xml
3+
Module Name: Az.Accounts
4+
online version: https://docs.microsoft.com/powershell/module/az.accounts/export-azconfig
5+
schema: 2.0.0
6+
---
7+
8+
# Export-AzConfig
9+
10+
## SYNOPSIS
11+
Exports all the configs into a file so that it can be imported on another machine.
12+
13+
## SYNTAX
14+
15+
```
16+
Export-AzConfig [-Path] <String> [-Force] [-PassThru] [-DefaultProfile <IAzureContextContainer>] [-WhatIf]
17+
[-Confirm] [<CommonParameters>]
18+
```
19+
20+
## DESCRIPTION
21+
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.
22+
23+
## EXAMPLES
24+
25+
### Example 1
26+
```powershell
27+
Export-AzConfig -Path ./config.json
28+
```
29+
30+
This example exports the configs to `./config.json` file which can later be imported via `Import-AzConfig`.
31+
32+
## PARAMETERS
33+
34+
### -DefaultProfile
35+
The credentials, account, tenant, and subscription used for communication with Azure.
36+
37+
```yaml
38+
Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core.IAzureContextContainer
39+
Parameter Sets: (All)
40+
Aliases: AzContext, AzureRmContext, AzureCredential
41+
42+
Required: False
43+
Position: Named
44+
Default value: None
45+
Accept pipeline input: False
46+
Accept wildcard characters: False
47+
```
48+
49+
### -Force
50+
Overwrites the given file if it exists.
51+
52+
```yaml
53+
Type: System.Management.Automation.SwitchParameter
54+
Parameter Sets: (All)
55+
Aliases:
56+
57+
Required: False
58+
Position: Named
59+
Default value: None
60+
Accept pipeline input: False
61+
Accept wildcard characters: False
62+
```
63+
64+
### -PassThru
65+
Returns a boolean value indicating success or failure.
66+
67+
```yaml
68+
Type: System.Management.Automation.SwitchParameter
69+
Parameter Sets: (All)
70+
Aliases:
71+
72+
Required: False
73+
Position: Named
74+
Default value: None
75+
Accept pipeline input: False
76+
Accept wildcard characters: False
77+
```
78+
79+
### -Path
80+
Specifies the path of the file to which to save the configs.
81+
82+
```yaml
83+
Type: System.String
84+
Parameter Sets: (All)
85+
Aliases:
86+
87+
Required: True
88+
Position: 1
89+
Default value: None
90+
Accept pipeline input: False
91+
Accept wildcard characters: False
92+
```
93+
94+
### -Confirm
95+
Prompts you for confirmation before running the cmdlet.
96+
97+
```yaml
98+
Type: System.Management.Automation.SwitchParameter
99+
Parameter Sets: (All)
100+
Aliases: cf
101+
102+
Required: False
103+
Position: Named
104+
Default value: None
105+
Accept pipeline input: False
106+
Accept wildcard characters: False
107+
```
108+
109+
### -WhatIf
110+
Shows what would happen if the cmdlet runs.
111+
The cmdlet is not run.
112+
113+
```yaml
114+
Type: System.Management.Automation.SwitchParameter
115+
Parameter Sets: (All)
116+
Aliases: wi
117+
118+
Required: False
119+
Position: Named
120+
Default value: None
121+
Accept pipeline input: False
122+
Accept wildcard characters: False
123+
```
124+
125+
### CommonParameters
126+
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).
127+
128+
## INPUTS
129+
130+
### None
131+
132+
## OUTPUTS
133+
134+
### System.Boolean
135+
136+
## NOTES
137+
138+
## RELATED LINKS
139+
140+
[Import-AzConfig](./Import-AzConfig.md)

0 commit comments

Comments
 (0)