aws-sdk#SSM TypeScript Examples

The following examples show how to use aws-sdk#SSM. 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: util.ts    From ServerlessPlugin-SSMPublish with MIT License 7 votes vote down vote up
compareParams = (localParams: SSMParamWithValue[], remoteParams: SSM.GetParametersResult['Parameters']) => localParams.reduce< { nonExistingParams: SSMParamWithValue[]; existingChangedParams: SSMParamWithValue[]; existingUnchangedParams: SSMParamWithValue[] }>((acc, curr) => {

  const existingParam = remoteParams?.find((param) => param.Name === curr.path);
  if (!existingParam) {
    acc.nonExistingParams.push(curr);
    return acc;
  }

  // Compare unchanged
  if (typeof curr.value === 'string') {
    // Simple string comparison
    if (existingParam.Value === curr.value) {
      acc.existingUnchangedParams.push(curr);
      return acc;
    }
  } else {
    // Can't rely on serialized YAML string to be the same as the original definition.
    // We therefore parse it & do quick-n-dirty deep object comparison via JSON.stringify
    const parsedExisting = yaml.safeLoad(existingParam.Value ? existingParam.Value : '');
    if (JSON.stringify(parsedExisting) === JSON.stringify(curr.value)) {
      acc.existingUnchangedParams.push(curr);
      return acc;
    }
  }

  // Compare changed
  acc.existingChangedParams.push(curr);
  return acc;
}
, { nonExistingParams: [], existingChangedParams: [], existingUnchangedParams: [] })
Example #2
Source File: handlers.ts    From aws-resource-providers with MIT License 6 votes vote down vote up
private async upsertSSMPublicSharingBlock(action: Action, service: SSM, logger: Logger, model: ResourceModel): Promise<ResourceModel> {
        const request: SSM.UpdateServiceSettingRequest = {
            SettingId: '/ssm/documents/console/public-sharing-permission',
            SettingValue: model.blockPublicSharing ? 'Disable' : 'Enable',
        };

        logger.log({
            action,
            message: 'before invoke updateServiceSetting',
            request,
        });
        const response = await service.updateServiceSetting(request).promise();
        logger.log({
            action,
            message: 'after invoke updateServiceSetting',
            response,
        });

        logger.log({ action, message: 'done', model });
        return model;
    }
Example #3
Source File: handlers.ts    From aws-resource-providers with MIT License 6 votes vote down vote up
@handlerEvent(Action.Delete)
    @commonAws({ serviceName: 'SSM', debug: true })
    public async delete(action: Action, args: HandlerArgs<ResourceModel>, service: SSM): Promise<null> {
        const model = new ResourceModel();
        model.blockPublicSharing = false;
        this.upsertSSMPublicSharingBlock(action, service, args.logger, model);

        return Promise.resolve(null);
    }
Example #4
Source File: handlers.ts    From aws-resource-providers with MIT License 6 votes vote down vote up
@handlerEvent(Action.Read)
    @commonAws({ serviceName: 'SSM', debug: true })
    public async read(action: Action, args: HandlerArgs<ResourceModel>, service: SSM): Promise<ResourceModel> {
        const accountId = args.request.awsAccountId;

        const request: SSM.GetServiceSettingRequest = {
            SettingId: '/ssm/documents/console/public-sharing-permission',
        };

        args.logger.log({
            action,
            message: 'before invoke getServiceSetting',
            request,
        });
        try {
            const response = await service.getServiceSetting(request).promise();
            args.logger.log({
                action,
                message: 'after invoke getServiceSetting',
                response,
            });

            const blockPublicSharing = response.ServiceSetting.SettingValue === 'Disabled' ? true : false;

            const result: ResourceModel = new ResourceModel();
            result.blockPublicSharing = blockPublicSharing;
            result.resourceId = accountId;

            args.logger.log({ action, message: 'done', result });

            return Promise.resolve(result);
        } catch (err) {
            // Raise the original exception
            throw err;
        }
    }
Example #5
Source File: index.ts    From ServerlessPlugin-SSMPublish with MIT License 5 votes vote down vote up
/**
   * Goes through custom ssm publish properties and initializes local variables.
   */
  private async initializeVariables(): Promise<void> {
    if (!this.initialized) {
      this.enabled = evaluateEnabled(this.serverless.service.custom, this.throwError.bind(this)); // tslint:disable-line:no-unsafe-any

      if (this.enabled) {
        const credentials = this.provider.getCredentials(); // tslint:disable-line:no-unsafe-any

        // Extract plugin variables
        this.region = this.serverless.service.provider.region;

        this.stackName = util.format('%s-%s',
          this.serverless.service.getServiceName(),
          this.serverless.getProvider('aws').getStage(),
        );

        // Initialize AWS SDK clients
        const credentialsWithRegion = { ...credentials, region: this.region };

        this.ssm = new this.provider.sdk.SSM(credentialsWithRegion); // tslint:disable-line:no-unsafe-any

        // Validate plugin variables

        const yamlDefinedParams = validateParams(this.serverless.service.custom.ssmPublish.params, this.throwError.bind(this), this.log.bind(this)) || []; // tslint:disable-line:no-unsafe-any

        // Retrieve Cloud Formation output if necessary
        if (yamlDefinedParams.some((param: SSMParamCloudFormation) => param.source)) {
          this.logIfDebug('Retrieving Cloud Formation Outputs');
          this.cloudFormationOutput = await this.retrieveAndFormatCloudFormationOutput();
        }

        // Merge cloud formation output with yaml defined values
        const checkIfParamHasValue = (param: SSMParam): param is SSMParamWithValue => param.hasOwnProperty('value');

        const mergedParams = yamlDefinedParams.map((slsParam): SSMParamWithValue => {
          if (checkIfParamHasValue(slsParam)) return slsParam;

          const foundCloudFormationParam = this.cloudFormationOutput?.find((cloudFormationParam) => cloudFormationParam.path === slsParam.source);

          if (!foundCloudFormationParam) {
            this.throwError(`No Cloud Formation Output found for source ${slsParam.source}`);
            throw new Error(`No Cloud Formation Output found for source ${slsParam.source}`); // Throwing again as typescript won't recognise throwError as throwing
          }
          return { ...slsParam, value: foundCloudFormationParam.value, description: foundCloudFormationParam.description || slsParam.description };
        });

        // Put params on this for following logic

        this.params = [...mergedParams]; // tslint:disable-line:no-unsafe-any

        unsupportedRegionPrefixes.forEach((unsupportedRegionPrefix) => {
          if (this.region.startsWith(unsupportedRegionPrefix)) {
            this.log(chalk.bold.yellow(`The configured region ${this.region} does not support SSM. Plugin disabled`));
            this.enabled = false;
          }
        });
      }

      this.initialized = true;
    }
  }
Example #6
Source File: index.ts    From ServerlessPlugin-SSMPublish with MIT License 5 votes vote down vote up
// tslint:disable-line:no-any

  // AWS SDK resources
  private ssm: SSM;
Example #7
Source File: index.ts    From office-booker with MIT License 5 votes vote down vote up
ssm = new SSM()
Example #8
Source File: handlers.ts    From aws-resource-providers with MIT License 5 votes vote down vote up
@handlerEvent(Action.Create)
    @commonAws({ serviceName: 'SSM', debug: true })
    public async create(action: Action, args: HandlerArgs<ResourceModel>, service: SSM, model: ResourceModel): Promise<ResourceModel> {
        const accountId = args.request.awsAccountId;
        model.resourceId = `${accountId}/${args.request.region}`;
        return this.upsertSSMPublicSharingBlock(action, service, args.logger, model);
    }
Example #9
Source File: handlers.ts    From aws-resource-providers with MIT License 5 votes vote down vote up
@handlerEvent(Action.Update)
    @commonAws({ serviceName: 'SSM', debug: true })
    public async update(action: Action, args: HandlerArgs<ResourceModel>, service: SSM, model: ResourceModel): Promise<ResourceModel> {
        return this.upsertSSMPublicSharingBlock(action, service, args.logger, model);
    }