in src/Amazon.Common.DotNetCli.Tools/Commands/BaseCommand.cs [586:654]
public string GetInstanceProfileOrDefault(string propertyValue, CommandOption option, bool required, string newRoleName)
{
var value = GetStringValueOrDefault(propertyValue, option, false);
if (!string.IsNullOrEmpty(value))
{
value = RoleHelper.ExpandInstanceProfile(this.IAMClient, value);
return value;
}
else if (required && !this.DisableInteractive)
{
var existingProfiles = RoleHelper.FindExistingInstanceProfilesAsync(this.IAMClient, 20).Result;
var selections = new List<string>();
foreach (var profile in existingProfiles)
selections.Add(profile.InstanceProfileName);
selections.Add("*** Create new Instance Profile ***");
var chosenIndex = PromptForValue(option, selections);
if(chosenIndex < selections.Count - 1)
{
var arn = existingProfiles[chosenIndex].Arn;
_cachedRequestedValues[option] = arn;
return arn;
}
else
{
var promptInfo = new RoleHelper.PromptRoleInfo
{
KnownManagedPolicyDescription = Constants.COMMON_KNOWN_MANAGED_POLICY_DESCRIPTIONS
};
var managedPolices = RoleHelper.FindManagedPoliciesAsync(this.IAMClient, promptInfo, 20).Result;
var profileSelection = new List<string>();
foreach (var profile in managedPolices)
profileSelection.Add(profile.PolicyName);
chosenIndex = PromptForValue("Select managed policy to assign to new instance profile: ", profileSelection);
var uniqueRoleName = RoleHelper.GenerateUniqueIAMRoleName(this.IAMClient, newRoleName);
this.Logger?.WriteLine("Creating role {0}", uniqueRoleName);
RoleHelper.CreateRole(this.IAMClient, uniqueRoleName, Constants.EC2_ASSUME_ROLE_POLICY, managedPolices[chosenIndex].Arn);
this.Logger?.WriteLine("Creating instance profile {0}", uniqueRoleName);
var response = this.IAMClient.CreateInstanceProfileAsync(new IdentityManagement.Model.CreateInstanceProfileRequest
{
InstanceProfileName = uniqueRoleName
}).Result;
this.Logger?.WriteLine("Assigning role to instance profile");
this.IAMClient.AddRoleToInstanceProfileAsync(new IdentityManagement.Model.AddRoleToInstanceProfileRequest
{
InstanceProfileName = uniqueRoleName,
RoleName = uniqueRoleName
}).Wait();
var arn = response.InstanceProfile.Arn;
_cachedRequestedValues[option] = arn;
return arn;
}
}
if (required)
{
throw new ToolsException($"Missing required parameter: {option.Switch}", ToolsException.CommonErrorCode.MissingRequiredParameter);
}
return null;
}