in src/Amazon.Common.DotNetCli.Tools/RoleHelper.cs [140:227]
public static string CreateRole(IAmazonIdentityManagementService iamClient, string roleName, string assumeRolePolicy, params string[] managedPolicies)
{
if (managedPolicies != null && managedPolicies.Length > 0)
{
for(int i = 0; i < managedPolicies.Length; i++)
{
if (managedPolicies[i] != null)
{
managedPolicies[i] = ExpandManagedPolicyName(iamClient, managedPolicies[i]);
}
}
}
string roleArn;
try
{
CreateRoleRequest request = new CreateRoleRequest
{
RoleName = roleName,
AssumeRolePolicyDocument = assumeRolePolicy
};
var response = iamClient.CreateRoleAsync(request).Result;
roleArn = response.Role.Arn;
}
catch (Exception e)
{
throw new ToolsException($"Error creating IAM Role: {e.Message}", ToolsException.CommonErrorCode.IAMCreateRole, e);
}
if (managedPolicies != null && managedPolicies.Length > 0)
{
try
{
foreach (var managedPolicy in managedPolicies)
{
if (managedPolicy != null)
{
var request = new AttachRolePolicyRequest
{
RoleName = roleName,
PolicyArn = managedPolicy
};
iamClient.AttachRolePolicyAsync(request).Wait();
}
}
}
catch (Exception e)
{
throw new ToolsException($"Error assigning managed IAM Policy: {e.Message}", ToolsException.CommonErrorCode.IAMAttachRole, e);
}
}
bool found = false;
do
{
// There is no way check if the role has propagated yet so to
// avoid error during deployment creation do a generous sleep.
Console.WriteLine("Waiting for new IAM Role to propagate to AWS regions");
long start = DateTime.Now.Ticks;
while (TimeSpan.FromTicks(DateTime.Now.Ticks - start).TotalSeconds < SLEEP_TIME_FOR_ROLE_PROPOGATION.TotalSeconds)
{
Thread.Sleep(TimeSpan.FromSeconds(1));
Console.Write(".");
Console.Out.Flush();
}
Console.WriteLine("\t Done");
try
{
var getResponse = iamClient.GetRoleAsync(new GetRoleRequest { RoleName = roleName }).Result;
if (getResponse.Role != null)
found = true;
}
catch (NoSuchEntityException)
{
}
catch (Exception e)
{
throw new ToolsException("Error confirming new role was created: " + e.Message, ToolsException.CommonErrorCode.IAMGetRole, e);
}
} while (!found);
return roleArn;
}