コード例 #1
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonSimpleSystemsManagementConfig config = new AmazonSimpleSystemsManagementConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonSimpleSystemsManagementClient client = new AmazonSimpleSystemsManagementClient(creds, config);

            DescribeParametersResponse resp = new DescribeParametersResponse();

            do
            {
                DescribeParametersRequest req = new DescribeParametersRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems
                };

                resp = client.DescribeParameters(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.Parameters)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
コード例 #2
0
 public SettingsController(IHostEnvironment hostingEnvironment)
 {
     if (hostingEnvironment.IsDevelopment())
     {
         var systemsManagementConfig = new AmazonSimpleSystemsManagementConfig
         {
             ServiceURL = Consts.SSMServiceUrl,
             UseHttp    = true
         };
         _amazonSettingsClient = new AmazonSimpleSystemsManagementClient(new BasicAWSCredentials("abc", "def"), systemsManagementConfig);
     }
 }
        protected IAmazonSimpleSystemsManagement CreateClient(AWSCredentials credentials, RegionEndpoint region)
        {
            var config = new AmazonSimpleSystemsManagementConfig {
                RegionEndpoint = region
            };

            Amazon.PowerShell.Utils.Common.PopulateConfig(this, config);
            this.CustomizeClientConfig(config);
            var client = new AmazonSimpleSystemsManagementClient(credentials, config);

            client.BeforeRequestEvent += RequestEventHandler;
            client.AfterResponseEvent += ResponseEventHandler;
            return(client);
        }
コード例 #4
0
        public IEncryptedParameterClient GetClient(string id)
        {
            if (Clients.ContainsKey(id))
            {
                return(Clients[id]);
            }
            var config = new AmazonSimpleSystemsManagementConfig {
                RegionEndpoint = RegionEndpoint.USWest2
            };
            var ssmClient            = new AmazonSimpleSystemsManagementClient(config);
            var parameterStoreClient = new EncryptedParameterStoreClient(ssmClient);

            Clients.TryAdd(id, parameterStoreClient);
            return(Clients[id]);
        }
コード例 #5
0
 public ElectionConfigurationSource(IOptions <AppConfig> config, IHostingEnvironment hostingEnvironment)
 {
     _config             = config.Value;
     _parameterStoreName = Consts.ParameterStoreName;
     if (hostingEnvironment.IsDevelopment())
     {
         var systemsManagementConfig = new AmazonSimpleSystemsManagementConfig
         {
             ServiceURL = Consts.SSMServiceUrl,
             UseHttp    = true
         };
         _amazonSettingsClient = new AmazonSimpleSystemsManagementClient(new BasicAWSCredentials("abc", "def"), systemsManagementConfig);
         _parameterStoreName  += "-dev";
     }
     if (hostingEnvironment.IsStaging())
     {
         _parameterStoreName += "-stag";
     }
 }
コード例 #6
0
    public async Task <SsmCommandResponse> RunSsmCommand(UserRequest request, HandlerConfig config)
    {
        if (request == null || config == null)
        {
            return(null);
        }
        string             errorMessage = string.Empty;
        SsmCommandResponse output       = new SsmCommandResponse()
        {
            Status = "Failed" // If no processing is done.
        };

        AmazonSimpleSystemsManagementConfig clientConfig = new AmazonSimpleSystemsManagementConfig()
        {
            MaxErrorRetry    = config.ClientMaxErrorRetry,
            Timeout          = TimeSpan.FromSeconds(config.ClientTimeoutSeconds),
            ReadWriteTimeout = TimeSpan.FromSeconds(config.ClientReadWriteTimeoutSeconds),
            RegionEndpoint   = RegionEndpoint.GetBySystemName(request.AwsRegion) // Or RegionEndpoint.EUWest1
        };

        try
        {
            // https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-creds.html
            // Accessing Credentials and Profiles in an Application
            CredentialProfileStoreChain chain = new CredentialProfileStoreChain(config.AwsProfilesLocation);

            AWSCredentials awsCredentials;
            if (chain.TryGetAWSCredentials(request.AwsRole, out awsCredentials))
            {
                // Use awsCredentials
                AmazonSimpleSystemsManagementClient ssmClient =
                    new AmazonSimpleSystemsManagementClient(awsCredentials, clientConfig);
                if (request.CommandType == "send-command")
                {
                    List <string> instanceIds = new List <string> {
                        request.InstanceId
                    };
                    SendCommandRequest commandRequest = new SendCommandRequest(request.CommandDocument, instanceIds);
                    commandRequest.MaxConcurrency = config.CommandMaxConcurrency; // 50%
                    commandRequest.MaxErrors      = config.CommandMaxErrors;
                    commandRequest.TimeoutSeconds = config.CommandTimeoutSeconds;
                    commandRequest.Comment        = request.CommandComment;
                    commandRequest.Parameters     = request.CommandParameters;
                    SendCommandResponse sendCommandResponse = await ssmClient.SendCommandAsync(commandRequest);

                    output.Status         = "Complete";
                    output.CommandId      = sendCommandResponse.Command.CommandId;
                    output.CommandStatus  = sendCommandResponse.Command.StatusDetails;
                    output.ErrorMessage   = errorMessage;
                    output.CommandComment = sendCommandResponse.Command.Comment;
                }
                else if (request.CommandType == "get-command-invocation")
                {
                    //GetCommandInvocationRequest commandRequest = new GetCommandInvocationRequest()
                    //{
                    //    CommandId = request.CommandId,
                    //    InstanceId = request.InstanceId,
                    //    PluginName = request.CommandPluginName // If there are more than one plugins, this cannot be null.
                    //};
                    //GetCommandInvocationResponse getCommandResponse =
                    //    await ssmClient.GetCommandInvocationAsync(commandRequest);

                    ListCommandInvocationsRequest commandRequest = new ListCommandInvocationsRequest()
                    {
                        CommandId = request.CommandId,
                        Details   = true
                    };
                    ListCommandInvocationsResponse commandResponse = await ssmClient.ListCommandInvocationsAsync(commandRequest);

                    if (commandResponse.CommandInvocations.Count > 0)
                    {
                        output.Status         = "Complete";
                        output.CommandId      = commandResponse.CommandInvocations[0].CommandId;
                        output.CommandStatus  = commandResponse.CommandInvocations[0].StatusDetails;
                        output.CommandComment = commandResponse.CommandInvocations[0].Comment;
                        if (commandResponse.CommandInvocations[0].StatusDetails == "Success" &&
                            commandResponse.CommandInvocations[0].CommandPlugins.Count > 0)
                        {
                            output.StandardOutput = commandResponse.CommandInvocations[0].CommandPlugins[0].Output;
                        }
                        else if (commandResponse.CommandInvocations[0].StatusDetails == "Failed" &&
                                 commandResponse.CommandInvocations[0].CommandPlugins.Count > 0)
                        {
                            GetCommandInvocationRequest invocationRequest = new GetCommandInvocationRequest()
                            {
                                CommandId  = request.CommandId,
                                InstanceId = request.InstanceId,
                                PluginName = request.CommandPluginName // If there are more than one plugins, this cannot be null.
                            };
                            GetCommandInvocationResponse getCommandResponse =
                                await ssmClient.GetCommandInvocationAsync(invocationRequest);

                            output.StandardOutput = getCommandResponse.StandardOutputContent;
                            output.StandardError  = getCommandResponse.StandardErrorContent;
                        }
                    }
                    else
                    {
                        errorMessage = "The command id and instance id specified did not match any invocation.";
                    }
                }
            }
            else
            {
                errorMessage = "AWS credentials cannot be found for the execution.";
            }
        }
        catch (AmazonSimpleSystemsManagementException ex)
        {
            switch (ex.ErrorCode)
            {
            // https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_SendCommand.html
            // Error codes for "SendCommandRequest"
            case "DuplicateInstanceId":
                errorMessage = "You cannot specify an instance ID in more than one association.";
                break;

            case "InternalServerError":
                errorMessage = "Internal server error.";
                break;

            case "InvalidDocument":
                errorMessage = "The specified document does not exist.";
                break;

            case "InvalidDocumentVersion":
                errorMessage = "The document version is not valid or does not exist.";
                break;

            case "ExpiredTokenException":
                errorMessage = "The security token included in the request is expired.";
                break;

            case "InvalidInstanceId":
                errorMessage = "Possible causes are the 1) server instance may not be running 2) Server instance may not exist. 3) SSM agent may not be running. 4) Account used does not have permssion to access the instance.";
                break;

            case "InvalidNotificationConfig":
                errorMessage = "One or more configuration items is not valid.";
                break;

            case "InvalidOutputFolder":
                errorMessage = "The S3 bucket does not exist.";
                break;

            case "InvalidParameters":
                errorMessage =
                    "You must specify values for all required parameters in the Systems Manager document.";
                break;

            case "InvalidRole":
                errorMessage = "The role name can't contain invalid characters.";
                break;

            case "MaxDocumentSizeExceeded":
                errorMessage = "The size limit of a document is 64 KB.";
                break;

            case "UnsupportedPlatformType":
                errorMessage = "The document does not support the platform type of the given instance ID(s).";
                break;

            // Error codes for "GetcommandInvocation"
            case "InvalidCommandId":
                errorMessage = "The command ID is invalid.";
                break;

            case "InvocationDoesNotExist":
                errorMessage =
                    "The command id and instance id specified did not match any invocation.";
                break;

            case "ValidationException":
                errorMessage = ex.Message;
                break;

            default:
                errorMessage = ex.Message;
                break;
            }
        }
        catch (Exception ex)
        {
            errorMessage = ex.Message;
        }

        if (!string.IsNullOrWhiteSpace(errorMessage))
        {
            throw new Exception(errorMessage);
        }
        return(output);
    }