Skip to content

Commit d512e5c

Browse files
authored
Merge pull request #6003 from cormacpayne/context-default
Enable context autosave by default
2 parents e590c75 + 9ddec26 commit d512e5c

File tree

7 files changed

+57
-33
lines changed

7 files changed

+57
-33
lines changed

src/Common/Commands.Common.Authentication/AzureSessionInitializer.cs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,17 @@ static ContextAutosaveSettings InitializeSessionSettings(IDataStore store, strin
9797
result.Mode = settings.Mode;
9898
result.ContextFile = settings.ContextFile ?? result.ContextFile;
9999
}
100+
else
101+
{
102+
string directoryPath = Path.GetDirectoryName(profileDirectory);
103+
if (!store.DirectoryExists(directoryPath))
104+
{
105+
store.CreateDirectory(directoryPath);
106+
}
107+
string autoSavePath = Path.Combine(profileDirectory, settingsFile);
108+
store.WriteFile(autoSavePath, JsonConvert.SerializeObject(result));
109+
result.Mode = ContextSaveMode.CurrentUser;
110+
}
100111
}
101112
catch
102113
{
@@ -191,7 +202,7 @@ public override System.Diagnostics.TraceLevel AuthenticationLegacyTraceLevel
191202
}
192203
set
193204
{
194-
205+
195206
}
196207
}
197208

src/ResourceManager/Common/Commands.Common.Authentication.ResourceManager/AzureRmProfile.cs

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public class AzureRmProfile : IAzureContextContainer, IProfileOperations
4040
public IDictionary<string, IAzureContext> Contexts { get; set; } = new ConcurrentDictionary<string, IAzureContext>(StringComparer.CurrentCultureIgnoreCase);
4141

4242
/// <summary>
43-
/// Gets the path of the profile file.
43+
/// Gets the path of the profile file.
4444
/// </summary>
4545
[JsonIgnore]
4646
[XmlIgnore]
@@ -271,7 +271,7 @@ public void Save(IFileProvider provider, bool serializeCache = true)
271271
writer.Write(contents);
272272
writer.Flush();
273273

274-
// When writing to a stream, ensure that the file is truncated
274+
// When writing to a stream, ensure that the file is truncated
275275
// so that previous data is overwritten
276276
provider.Stream.SetLength(provider.Stream.Position);
277277
}
@@ -386,20 +386,9 @@ public bool TryGetContextName(IAzureContext context, out string name)
386386
if (context != null)
387387
{
388388

389-
if ((context.Account != null && !string.IsNullOrWhiteSpace(context.Account.Id)) || context.Subscription != null)
389+
if (context.Subscription != null)
390390
{
391-
List<string> components = new List<string>();
392-
if (context.Account != null && !string.IsNullOrWhiteSpace(context.Account.Id))
393-
{
394-
components.Add(context.Account.Id);
395-
}
396-
397-
if (context.Subscription != null)
398-
{
399-
components.Add(context.Subscription.GetId().ToString());
400-
}
401-
402-
name = string.Format("[{0}]", string.Join(", ", components));
391+
name = string.Format("{0} - {1}", context.Subscription.Name, context.Subscription.Id);
403392
result = true;
404393
}
405394
else

src/ResourceManager/Profile/ChangeLog.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
-->
2020
## Current Release
2121
* Set minimum dependency of module to PowerShell 5.0
22+
* Enable context autosave by default
23+
* Create a context for each subscription when running `Connect-AzureRmAccount` with no previous context
2224
* Add USGovernmentOperationalInsightsEndpoint and USGovernmentOperationalInsightsEndpointResourceId properties to Azure environment for US Gov.
2325

2426
## Version 4.6.0

src/ResourceManager/Profile/Commands.Profile.Test/ContextCmdletTests.cs

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -96,12 +96,7 @@ public void GetAzureContextNoLogin()
9696
}
9797

9898
// Verify
99-
Assert.True(commandRuntimeMock.OutputPipeline.Count == 1);
100-
var context = (PSAzureContext)commandRuntimeMock.OutputPipeline[0];
101-
Assert.True(context == null || context.Account == null || context.Account.Id == null);
102-
Assert.True(commandRuntimeMock.ErrorStream.Count == 1);
103-
var error = commandRuntimeMock.ErrorStream[0];
104-
Assert.Equal("Run Connect-AzureRmAccount to login.", error.Exception.Message);
99+
Assert.True(commandRuntimeMock.OutputPipeline.Count == 0);
105100
}
106101

107102
[Fact]
@@ -131,9 +126,7 @@ public void ListAzureContextNoLogin()
131126

132127
// Verify
133128
Assert.Equal(0, commandRuntimeMock.OutputPipeline.Count);
134-
Assert.True(commandRuntimeMock.ErrorStream.Count == 1);
135-
var error = commandRuntimeMock.ErrorStream[0];
136-
Assert.Equal("Run Connect-AzureRmAccount to login.", error.Exception.Message);
129+
Assert.True(commandRuntimeMock.ErrorStream.Count == 0);
137130
}
138131

139132

src/ResourceManager/Profile/Commands.Profile.Test/SessionInitializationTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ public void DataCollectionSettingPreventsFileWrite()
8383
Assert.Equal(typeof(AuthenticationStoreTokenCache), session.TokenCache.GetType());
8484
Assert.NotNull(AzureRmProfileProvider.Instance);
8585
Assert.Equal(typeof(ResourceManagerProfileProvider), AzureRmProfileProvider.Instance.GetType());
86-
store.Verify(f => f.WriteFile(It.IsAny<string>(), It.IsAny<string>()), Times.Never);
86+
store.Verify(f => f.WriteFile(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
8787
}
8888
finally
8989
{

src/ResourceManager/Profile/Commands.Profile/Context/GetAzureRMContext.cs

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
namespace Microsoft.Azure.Commands.Profile
2626
{
2727
/// <summary>
28-
/// Cmdlet to get current context.
28+
/// Cmdlet to get current context.
2929
/// </summary>
3030
[Cmdlet(VerbsCommon.Get, "AzureRmContext", DefaultParameterSetName = GetSingleParameterSet)]
3131
[OutputType(typeof(PSAzureContext))]
@@ -53,13 +53,10 @@ protected override IAzureContext DefaultContext
5353

5454
public override void ExecuteCmdlet()
5555
{
56+
// If no context is found, return
5657
if (DefaultContext == null)
5758
{
58-
WriteError(new ErrorRecord(
59-
new PSInvalidOperationException(Resources.RunLoginCmdlet),
60-
string.Empty,
61-
ErrorCategory.AuthenticationError,
62-
null));
59+
return;
6360
}
6461

6562
if (ListAvailable.IsPresent)
@@ -102,6 +99,15 @@ void WriteContext(IAzureContext azureContext, string name)
10299
context.Name = name;
103100
}
104101

102+
// Don't write the default (empty) context to the output stream
103+
if (context.Account == null &&
104+
context.Environment == null &&
105+
context.Subscription == null &&
106+
context.Tenant == null)
107+
{
108+
return;
109+
}
110+
105111
WriteObject(context);
106112
}
107113

src/ResourceManager/Profile/Commands.Profile/Models/RMProfileClient.cs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,6 @@ public AzureRmProfile Login(
140140
Id = tenantId
141141
};
142142
}
143-
144143
else
145144
{
146145
// (tenant and subscription are present) OR
@@ -227,6 +226,7 @@ public AzureRmProfile Login(
227226
}
228227
}
229228

229+
bool shouldPopulateContextList = _profile.DefaultContext?.Account == null;
230230
if (newSubscription == null)
231231
{
232232
if (subscriptionId != null)
@@ -261,6 +261,29 @@ public AzureRmProfile Login(
261261
}
262262

263263
_profile.DefaultContext.TokenCache = _cache;
264+
var defaultContext = _profile.DefaultContext;
265+
if (shouldPopulateContextList)
266+
{
267+
var subscriptions = ListSubscriptions(tenantId);
268+
foreach (var subscription in subscriptions)
269+
{
270+
var tempContext = new AzureContext(subscription, account, environment, newTenant);
271+
string tempName = null;
272+
if (!_profile.TryGetContextName(tempContext, out tempName))
273+
{
274+
WriteWarningMessage(string.Format("Unable to get context name for subscription with id '{0}'.", subscription.Id));
275+
continue;
276+
}
277+
278+
if (!_profile.TrySetContext(tempName, tempContext))
279+
{
280+
WriteWarningMessage(string.Format("Cannot create a context for subscription with id '{0}'.", subscription.Id));
281+
}
282+
}
283+
284+
_profile.TrySetDefaultContext(defaultContext);
285+
_profile.TryRemoveContext("Default");
286+
}
264287

265288
return _profile.ToProfile();
266289
}

0 commit comments

Comments
 (0)