com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement Java Examples

The following examples show how to use com.amazonaws.services.simplesystemsmanagement.AWSSimpleSystemsManagement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EC2InventoryUtilTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch SSM info test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchSSMInfoTest() throws Exception {
    
    mockStatic(AWSSimpleSystemsManagementClientBuilder.class);
    AWSSimpleSystemsManagement ssmClient = PowerMockito.mock(AWSSimpleSystemsManagement.class);
    AWSSimpleSystemsManagementClientBuilder simpleSystemsManagementClientBuilder = PowerMockito.mock(AWSSimpleSystemsManagementClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(simpleSystemsManagementClientBuilder.standard()).thenReturn(simpleSystemsManagementClientBuilder);
    when(simpleSystemsManagementClientBuilder.withCredentials(anyObject())).thenReturn(simpleSystemsManagementClientBuilder);
    when(simpleSystemsManagementClientBuilder.withRegion(anyString())).thenReturn(simpleSystemsManagementClientBuilder);
    when(simpleSystemsManagementClientBuilder.build()).thenReturn(ssmClient);
    
    DescribeInstanceInformationResult describeInstanceInfoRslt = new DescribeInstanceInformationResult();
    List<InstanceInformation> ssmInstanceListTemp = new ArrayList<>();
    ssmInstanceListTemp.add(new InstanceInformation());
    describeInstanceInfoRslt.setInstanceInformationList(ssmInstanceListTemp);
    when(ssmClient.describeInstanceInformation(anyObject())).thenReturn(describeInstanceInfoRslt);
    assertThat(ec2InventoryUtil.fetchSSMInfo(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
}
 
Example #2
Source File: SsmService.java    From Gatekeeper with Apache License 2.0 6 votes vote down vote up
private Map<String, String> cancelPendingExecution(AWSSimpleSystemsManagement ssmClient, Set<String> instanceIds, String commandId, Map<String, String> results){
    CancelCommandRequest cancelCommandRequest = new CancelCommandRequest()
            .withInstanceIds(instanceIds)
            .withCommandId(commandId);
    ssmClient.cancelCommand(cancelCommandRequest);
    for(String instance : results.keySet()){
        String status = results.get(instance);
        if(status.equals(CommandStatus.InProgress.toString())
                || status.equals(CommandStatus.Pending.toString())
                || status.equals(CommandStatus.Cancelling.toString())){
            results.put(instance, CommandStatus.Cancelled.toString());
        }
        
    }
    return results;
}
 
Example #3
Source File: SsmUtil.java    From herd-mdl with Apache License 2.0 6 votes vote down vote up
private static Parameter getParameter(String parameterKey, boolean isEncrypted) {
    LOGGER.info("get ssm parameter key:" + parameterKey);
    AWSCredentialsProvider credentials = InstanceProfileCredentialsProvider.getInstance();
    AWSSimpleSystemsManagement simpleSystemsManagementClient =
        AWSSimpleSystemsManagementClientBuilder.standard().withCredentials(credentials)
            .withRegion(Regions.getCurrentRegion().getName()).build();
    GetParameterRequest parameterRequest = new GetParameterRequest();
    parameterRequest.withName(parameterKey).setWithDecryption(isEncrypted);
    GetParameterResult parameterResult = simpleSystemsManagementClient.getParameter(parameterRequest);
    return parameterResult.getParameter();
}
 
Example #4
Source File: SsmService.java    From Gatekeeper with Apache License 2.0 6 votes vote down vote up
private  Map<String, String> executeSsm(AWSEnvironment environment, List<String> instanceIds, String platform, Map<String, ArrayList<String>> parameters, GatekeeperSsmProperties.SsmDocument documentProperties){
    AWSSimpleSystemsManagement ssmClient = awsSessionService.getSsmSession(environment);

    SendCommandRequest scr = new SendCommandRequest()
            .withInstanceIds(instanceIds)
            .withDocumentName(documentProperties.getDocumentName());


    for(String key : parameters.keySet()){
        scr.addParametersEntry(key, parameters.get(key));
    }

    return waitForSsmCommand(ssmClient,
            ssmClient.sendCommand(scr).getCommand().getCommandId(),
            instanceIds.size(),
            documentProperties.getTimeout(), documentProperties.getWaitInterval());
}
 
Example #5
Source File: AmazonAsyncDockerClientsHolder.java    From spring-localstack with Apache License 2.0 5 votes vote down vote up
@Override
public AWSSimpleSystemsManagement awsSimpleSystemsManagement() {
    return decorateWithConfigsAndBuild(
      AWSSimpleSystemsManagementClientBuilder.standard(),
      LocalstackDocker::getEndpointSSM
    );
}
 
Example #6
Source File: AwsParamStoreBootstrapConfiguration.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
AWSSimpleSystemsManagement ssmClient(
		AwsParamStoreProperties awsParamStoreProperties) {
	return StringUtils.isNullOrEmpty(awsParamStoreProperties.getRegion())
			? AWSSimpleSystemsManagementClientBuilder.defaultClient()
			: AWSSimpleSystemsManagementClientBuilder.standard()
					.withRegion(awsParamStoreProperties.getRegion()).build();
}
 
Example #7
Source File: GetSimpleSystemsManagementParas.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        // snippet-start:[ssm.Java1.get_params.main]
        AWSSimpleSystemsManagement ssm = AWSSimpleSystemsManagementClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build();

        try {
            DescribeParametersRequest desRequest = new DescribeParametersRequest();
            desRequest.setMaxResults(10);

            DescribeParametersResult results = ssm.describeParameters(desRequest);

            List<ParameterMetadata> params = results.getParameters();

            //Iterate through the list
            Iterator<ParameterMetadata> tagIterator = params.iterator();

            while(tagIterator.hasNext()) {

                ParameterMetadata paraMeta = (ParameterMetadata)tagIterator.next();

                System.out.println(paraMeta.getName());
                System.out.println(paraMeta.getDescription());
            }

        } catch (AmazonServiceException e) {
            e.getStackTrace();
        }
        // snippet-end:[ssm.Java1.get_params.main]
    }
 
Example #8
Source File: GetSimpleSystemsManagementOps.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        if (args.length < 1) {
            System.out.println("Please specify a SSM OpsItem ID value. You can obtain this value using the AWS Console.");
            System.exit(1);
        }

        // snippet-start:[ssm.Java1.get_ops.main]

        // Get the OpsItem ID value
        String opsID = args[0];

        // Create the AWSSimpleSystemsManagement client object
        AWSSimpleSystemsManagement ssm = AWSSimpleSystemsManagementClientBuilder.standard().withRegion(Regions.DEFAULT_REGION).build();

        try {
            GetOpsItemRequest opsRequest = new GetOpsItemRequest();
            opsRequest.setOpsItemId(opsID);

            GetOpsItemResult opsResults = ssm.getOpsItem(opsRequest);

            OpsItem item = opsResults.getOpsItem();

            System.out.println(item.getTitle());
            System.out.println(item.getDescription());
            System.out.println(item.getSource());

        } catch (AmazonServiceException e) {
            e.getStackTrace();
        }
        // snippet-end:[ssm.Java1.get_ops.main]
    }
 
Example #9
Source File: AwsSessionFactory.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
public AWSSimpleSystemsManagement createSsmSession(BasicSessionCredentials basicSessionCredentials, String region){
    return AWSSimpleSystemsManagementClientBuilder
            .standard()
            .withRegion(Regions.fromName(region))
            .withCredentials(setCredentials(basicSessionCredentials))
            .build();
}
 
Example #10
Source File: SsmService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
private Map<String, String> waitForSsmCommand(AWSSimpleSystemsManagement ssmClient, String commandId, int instanceCount, int timeout, int interval) {
    ListCommandInvocationsRequest lcir = new ListCommandInvocationsRequest().withCommandId(commandId);
    lcir.setMaxResults(50);
    ListCommandInvocationsResult result = ssmClient.listCommandInvocations(lcir);
    Map<String, String> results = checkEveryInstance(result);
    int waited=0;
    logger.info("Waiting for SSM command with id " + commandId + " to complete.");
    while (waited < instanceCount*timeout
            && !finished(result,instanceCount)) {
        try {
            Thread.sleep(interval);
        } catch (InterruptedException e) {
            continue;
        }
        waited += interval;
        result = ssmClient.listCommandInvocations(lcir);
        results = checkEveryInstance(result);
        logger.info("time waited: " + waited + " timeout: " + instanceCount*timeout);
    }
    /**
     * This cancels any pending commands so that when timeout happens, users won't get added
     * This is mainly important when all instances timeout. there would be no attempt to remove.
     * Need to get result again
     */
    results = cancelPendingExecution(ssmClient, results.keySet(), commandId, results);
    return results;
}
 
Example #11
Source File: SsmService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
public Map<String, String> checkInstancesWithSsm(AWSEnvironment environment, List<String> instanceIds){
    Map<String,String> instanceStatuses = new HashMap<>();

    AWSSimpleSystemsManagement ssmClient = awsSessionService.getSsmSession(environment);
    for(int i = 0; i < instanceIds.size(); i+=50){
        //since we're partitioning 50 at a time we need to make sure that we don't go over the index of the actual size of the set itself
        //if we do then we will use the upper value of the set.
        Integer upperBound = i+50 < instanceIds.size() ? i+50 : instanceIds.size();

        List<String> partitionedList = instanceIds.subList(i, upperBound);


        DescribeInstanceInformationRequest describeInstanceInformationRequest = new DescribeInstanceInformationRequest();
        InstanceInformationFilter filter = new InstanceInformationFilter();
        filter.setKey("InstanceIds");
        filter.setValueSet(partitionedList);
        List<InstanceInformationFilter> informationFilters = new ArrayList<>();
        informationFilters.add(filter);
        describeInstanceInformationRequest.setInstanceInformationFilterList(informationFilters);
        describeInstanceInformationRequest.setMaxResults(50);

        //make the initial call, SSM Chunks it up so we need to call it with tokens til the string returns empty.
        DescribeInstanceInformationResult describeInstanceInformationResult = ssmClient.describeInstanceInformation(describeInstanceInformationRequest);

        describeInstanceInformationResult.getInstanceInformationList().forEach(instance ->
                instanceStatuses.put(instance.getInstanceId(), instance.getPingStatus()));

        while(describeInstanceInformationResult.getNextToken() != null) {
            //get the next chunk of results
            describeInstanceInformationResult = ssmClient.describeInstanceInformation(describeInstanceInformationRequest.withNextToken(describeInstanceInformationResult.getNextToken()));
            describeInstanceInformationResult.getInstanceInformationList().forEach(instance ->
                    instanceStatuses.put(instance.getInstanceId(), instance.getPingStatus()));
        }
    }

    return instanceStatuses;
}
 
Example #12
Source File: DefaultParameterStorePropertySourceConfigurationStrategy.java    From spring-boot-parameter-store-integration with MIT License 5 votes vote down vote up
private AWSSimpleSystemsManagement buildSSMClient(ConfigurableEnvironment environment)
{
    if (hasCustomEndpoint(environment)) {
        return AWSSimpleSystemsManagementClientBuilder.standard()
                                                      .withEndpointConfiguration(new EndpointConfiguration(getCustomEndpoint(environment),
                                                                                                           getSigningRegion(environment)))
                                                      .build();
    }
    return AWSSimpleSystemsManagementClientBuilder.defaultClient();
}
 
Example #13
Source File: SsmUtil.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
/**
 * Delete parameter from aws ssm
 * @param parameterKey ssm parameter key
 */
public static void deleteParameter(String parameterKey) {
    LOGGER.info(String.format("delete ssm parameter key %s", parameterKey));
    AWSCredentialsProvider credentials = InstanceProfileCredentialsProvider.getInstance();
    AWSSimpleSystemsManagement simpleSystemsManagementClient =
        AWSSimpleSystemsManagementClientBuilder.standard().withCredentials(credentials)
            .withRegion(Regions.getCurrentRegion().getName()).build();
    DeleteParameterRequest parameterRequest = new DeleteParameterRequest().withName(parameterKey);

    simpleSystemsManagementClient.deleteParameter(parameterRequest);
}
 
Example #14
Source File: SsmUtil.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
/**
 * Put string parameter to aws ssm
 * @param parameterKey ssm parameter key
 * @param parameterValue ssm parameter value
 */
public static void putParameter(String parameterKey, String parameterValue) {
    LOGGER.info(String.format("put ssm parameter key %s; with value: %s ", parameterKey, parameterValue));
    AWSCredentialsProvider credentials = InstanceProfileCredentialsProvider.getInstance();
    AWSSimpleSystemsManagement simpleSystemsManagementClient =
        AWSSimpleSystemsManagementClientBuilder.standard().withCredentials(credentials)
            .withRegion(Regions.getCurrentRegion().getName()).build();
    PutParameterRequest parameterRequest = new PutParameterRequest().withName(parameterKey).withValue(parameterValue).withOverwrite(true).withType("String");

    simpleSystemsManagementClient.putParameter(parameterRequest);
}
 
Example #15
Source File: SsmUtil.java    From herd-mdl with Apache License 2.0 5 votes vote down vote up
/**
 * Get list of parameters with prefix
 * @param prefix parameter prefix
 * @return list of  parameters
 */
public static List<Parameter> getParametersWithPrefix(String prefix){
    AWSCredentialsProvider credentials = InstanceProfileCredentialsProvider.getInstance();
    AWSSimpleSystemsManagement simpleSystemsManagementClient =
        AWSSimpleSystemsManagementClientBuilder.standard().withCredentials(credentials)
            .withRegion(Regions.getCurrentRegion().getName()).build();

    GetParametersByPathRequest getParametersByPathRequest = new GetParametersByPathRequest()
        .withPath(prefix)
        .withRecursive(true);

    GetParametersByPathResult parameterResult = simpleSystemsManagementClient.getParametersByPath(getParametersByPathRequest);
    return parameterResult.getParameters();
}
 
Example #16
Source File: EC2InventoryUtil.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch SSM info.
 *
 * @param temporaryCredentials the temporary credentials
 * @param skipRegions the skip regions
 * @param accountId the accountId
 * @return the map
 */
public static Map<String,List<InstanceInformation>> fetchSSMInfo(BasicSessionCredentials temporaryCredentials, String skipRegions, String accountId,String accountName) {

	Map<String,List<InstanceInformation>> ssmInstanceList = new LinkedHashMap<>();

	AWSSimpleSystemsManagement ssmClient;
	String expPrefix = InventoryConstants.ERROR_PREFIX_CODE + accountId
			+ "\",\"Message\": \"Exception in fetching info for resource in specific region\" ,\"type\": \"SSM\" , \"region\":\"";

	List<InstanceInformation> ssmInstanceListTemp ;
	
	for (Region region : RegionUtils.getRegions()) {
		try {
			if (!skipRegions.contains(region.getName())) {
				ssmInstanceListTemp = new ArrayList<>();
				ssmClient = AWSSimpleSystemsManagementClientBuilder.standard()
						.withCredentials(new AWSStaticCredentialsProvider(temporaryCredentials))
						.withRegion(region.getName()).build();
				String nextToken = null;
				DescribeInstanceInformationResult describeInstanceInfoRslt;
				do {
					describeInstanceInfoRslt = ssmClient.describeInstanceInformation(
							new DescribeInstanceInformationRequest().withNextToken(nextToken));
					nextToken = describeInstanceInfoRslt.getNextToken();
					ssmInstanceListTemp.addAll(describeInstanceInfoRslt
							.getInstanceInformationList());
				} while (nextToken != null);
				if(! ssmInstanceListTemp.isEmpty() ) {
					log.debug(InventoryConstants.ACCOUNT + accountId + " Type : SSM "+region.getName() + " >> "+ssmInstanceListTemp.size());
					ssmInstanceList.put(accountId+delimiter+accountName+delimiter+region.getName(), ssmInstanceListTemp);
				}
			}

		} catch (Exception e) {
			log.warn(expPrefix + region.getName() + InventoryConstants.ERROR_CAUSE + e.getMessage() + "\"}");
			ErrorManageUtil.uploadError(accountId, region.getName(), "SSM", e.getMessage());
		}
	}
	return ssmInstanceList;
}
 
Example #17
Source File: AmazonDockerClientsHolder.java    From spring-localstack with Apache License 2.0 5 votes vote down vote up
@Override
public AWSSimpleSystemsManagement awsSimpleSystemsManagement() {
    return decorateWithConfigsAndBuild(
      AWSSimpleSystemsManagementClientBuilder.standard(),
      LocalstackDocker::getEndpointSSM
    );
}
 
Example #18
Source File: DefaultParameterStorePropertySourceConfigurationStrategy.java    From spring-boot-parameter-store-integration with MIT License 4 votes vote down vote up
private ParameterStorePropertySource buildParameterStorePropertySource(AWSSimpleSystemsManagement ssmClient,
                                                                       boolean haltBoot)
{
    return new ParameterStorePropertySource(PARAMETER_STORE_PROPERTY_SOURCE_NAME,
                                            new ParameterStoreSource(ssmClient, haltBoot));
}
 
Example #19
Source File: MultiRegionParameterStorePropertySourceConfigurationStrategy.java    From spring-boot-parameter-store-integration with MIT License 4 votes vote down vote up
private AWSSimpleSystemsManagement buildSSMClient(String region)
{
    return AWSSimpleSystemsManagementClientBuilder.standard().withRegion(region).build();
}
 
Example #20
Source File: ParameterStoreSource.java    From spring-boot-parameter-store-integration with MIT License 4 votes vote down vote up
public ParameterStoreSource(AWSSimpleSystemsManagement ssmClient, boolean haltBoot)
{
    this.ssmClient = ssmClient;
    this.haltBoot = haltBoot;
}
 
Example #21
Source File: AwsSessionService.java    From Gatekeeper with Apache License 2.0 4 votes vote down vote up
public AWSSimpleSystemsManagement getSsmSession(AWSEnvironment environment) {
    return awsSessionFactory.createSsmSession(credentialCache.getUnchecked(environment), environment.getRegion());
}
 
Example #22
Source File: AwsSessionServiceTest.java    From Gatekeeper with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetSsmSession(){
    AWSSimpleSystemsManagement client = awsSessionService.getSsmSession(awsEnvironment);
    Assert.assertNotNull("Verify Ssm Session is fetched", client);
    Mockito.verify(awsSessionFactory, times(1)).createSsmSession(anyObject(), eq(awsEnvironment.getRegion()));
}
 
Example #23
Source File: EveryAwsClientAutoConfiguration.java    From spring-localstack with Apache License 2.0 4 votes vote down vote up
@Bean
public AWSSimpleSystemsManagement awsSimpleSystemsManagement() { return  amazonClientsHolder.awsSimpleSystemsManagement(); }
 
Example #24
Source File: AwsParamStorePropertySource.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
public AwsParamStorePropertySource(String context,
		AWSSimpleSystemsManagement ssmClient) {
	super(context, ssmClient);
	this.context = context;
}
 
Example #25
Source File: AwsParamStorePropertySourceLocator.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
public AwsParamStorePropertySourceLocator(AWSSimpleSystemsManagement ssmClient,
		AwsParamStoreProperties properties) {
	this.ssmClient = ssmClient;
	this.properties = properties;
}
 
Example #26
Source File: AwsParamStoreBootstrapConfiguration.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Bean
AwsParamStorePropertySourceLocator awsParamStorePropertySourceLocator(
		AWSSimpleSystemsManagement ssmClient, AwsParamStoreProperties properties) {
	return new AwsParamStorePropertySourceLocator(ssmClient, properties);
}
 
Example #27
Source File: AmazonClientsHolder.java    From spring-localstack with Apache License 2.0 votes vote down vote up
AWSSimpleSystemsManagement awsSimpleSystemsManagement();