Beispiel #1
0
func ExampleSNS_ConfirmSubscription() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := sns.New(sess)

	params := &sns.ConfirmSubscriptionInput{
		Token:                     aws.String("token"),    // Required
		TopicArn:                  aws.String("topicARN"), // Required
		AuthenticateOnUnsubscribe: aws.String("authenticateOnUnsubscribe"),
	}
	resp, err := svc.ConfirmSubscription(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Beispiel #2
0
func ExampleSNS_SetSMSAttributes() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := sns.New(sess)

	params := &sns.SetSMSAttributesInput{
		Attributes: map[string]*string{ // Required
			"Key": aws.String("String"), // Required
			// More values...
		},
	}
	resp, err := svc.SetSMSAttributes(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Beispiel #3
0
func ExampleSNS_SetTopicAttributes() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := sns.New(sess)

	params := &sns.SetTopicAttributesInput{
		AttributeName:  aws.String("attributeName"), // Required
		TopicArn:       aws.String("topicARN"),      // Required
		AttributeValue: aws.String("attributeValue"),
	}
	resp, err := svc.SetTopicAttributes(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Beispiel #4
0
func ExampleSNS_RemovePermission() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := sns.New(sess)

	params := &sns.RemovePermissionInput{
		Label:    aws.String("label"),    // Required
		TopicArn: aws.String("topicARN"), // Required
	}
	resp, err := svc.RemovePermission(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Beispiel #5
0
func ExampleSNS_ListSubscriptionsByTopic() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := sns.New(sess)

	params := &sns.ListSubscriptionsByTopicInput{
		TopicArn:  aws.String("topicARN"), // Required
		NextToken: aws.String("nextToken"),
	}
	resp, err := svc.ListSubscriptionsByTopic(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Beispiel #6
0
func ExampleSNS_ListEndpointsByPlatformApplication() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := sns.New(sess)

	params := &sns.ListEndpointsByPlatformApplicationInput{
		PlatformApplicationArn: aws.String("String"), // Required
		NextToken:              aws.String("String"),
	}
	resp, err := svc.ListEndpointsByPlatformApplication(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Beispiel #7
0
func ExampleSNS_Subscribe() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := sns.New(sess)

	params := &sns.SubscribeInput{
		Protocol: aws.String("protocol"), // Required
		TopicArn: aws.String("topicARN"), // Required
		Endpoint: aws.String("endpoint"),
	}
	resp, err := svc.Subscribe(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Beispiel #8
0
// NewSNSPublisher will initiate the SNS client.
// If no credentials are passed in with the config,
// the publisher is instantiated with the AWS_ACCESS_KEY
// and the AWS_SECRET_KEY environment variables.
func NewSNSPublisher(cfg *config.SNS) (*SNSPublisher, error) {
	p := &SNSPublisher{}

	if cfg.Topic == "" {
		return p, errors.New("SNS topic name is required")
	}
	p.topic = cfg.Topic

	if cfg.Region == "" {
		return p, errors.New("SNS region is required")
	}

	var creds *credentials.Credentials
	if cfg.AccessKey != "" {
		creds = credentials.NewStaticCredentials(cfg.AccessKey, cfg.SecretKey, "")
	} else {
		creds = credentials.NewEnvCredentials()
	}

	p.sns = sns.New(session.New(&aws.Config{
		Credentials: creds,
		Region:      &cfg.Region,
	}))
	return p, nil
}
Beispiel #9
0
func ExampleSNS_CreatePlatformApplication() {
	svc := sns.New(nil)

	params := &sns.CreatePlatformApplicationInput{
		Attributes: map[string]*string{ // Required
			"Key": aws.String("String"), // Required
			// More values...
		},
		Name:     aws.String("String"), // Required
		Platform: aws.String("String"), // Required
	}
	resp, err := svc.CreatePlatformApplication(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
Beispiel #10
0
func ExampleSNS_AddPermission() {
	svc := sns.New(session.New())

	params := &sns.AddPermissionInput{
		AWSAccountId: []*string{ // Required
			aws.String("delegate"), // Required
			// More values...
		},
		ActionName: []*string{ // Required
			aws.String("action"), // Required
			// More values...
		},
		Label:    aws.String("label"),    // Required
		TopicArn: aws.String("topicARN"), // Required
	}
	resp, err := svc.AddPermission(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Beispiel #11
0
func ExampleSNS_ListPlatformApplications() {
	svc := sns.New(nil)

	params := &sns.ListPlatformApplicationsInput{
		NextToken: aws.String("String"),
	}
	resp, err := svc.ListPlatformApplications(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.Prettify(resp))
}
Beispiel #12
0
func findSubscription(config *aws.Config, topicARN, queueARN string) (string, error) {
	svc := sns.New(config)

	params := &sns.ListSubscriptionsByTopicInput{
		TopicArn: aws.String(topicARN),
	}

	for {
		resp, err := svc.ListSubscriptionsByTopic(params)
		if awserr, ok := err.(awserr.Error); ok {
			return "", fmt.Errorf("aws error while listing subscriptions to SNS topic: %v %v", awserr.Code(), awserr.Message())
		} else if err != nil {
			return "", fmt.Errorf("error while listing subscriptions to SNS topic: %v", err)
		} else if resp == nil || resp.Subscriptions == nil {
			break
		}

		for _, sub := range resp.Subscriptions {
			if sub.Endpoint != nil && *sub.Endpoint == queueARN && sub.Protocol != nil && *sub.Protocol == "sqs" && sub.SubscriptionArn != nil {
				return *sub.SubscriptionArn, nil
			}
		}

		if resp.NextToken != nil {
			params.NextToken = resp.NextToken
		} else {
			break
		}
	}

	return "", nil
}
// SendMessage sends an SNS message to an SNS region.
// See http://docs.aws.amazon.com/sdk-for-go/api/service/sns.html#type-PublishInput
func SendMessage(region string, topic string, subject string, message string) {
	if region == "" {
		log.Fatal("SNS region is required")
	}

	if topic == "" {
		log.Fatal("SNS topic is required")
	}

	if subject == "" {
		log.Fatal("SNS subject is required")
	}

	if message == "" {
		log.Fatal("SNS message is required")
	}

	params := &sns.PublishInput{
		Subject:   aws.String(subject),
		Message:   aws.String(message),
		TargetArn: aws.String(topic),
	}

	sns := sns.New(session.New(), aws.NewConfig().WithRegion(region))

	_, err := sns.Publish(params)
	awserror.HandleError(err)
}
Beispiel #14
0
func ExampleSNS_Publish() {
	svc := sns.New(session.New())

	params := &sns.PublishInput{
		Message: aws.String("message"), // Required
		MessageAttributes: map[string]*sns.MessageAttributeValue{
			"Key": { // Required
				DataType:    aws.String("String"), // Required
				BinaryValue: []byte("PAYLOAD"),
				StringValue: aws.String("String"),
			},
			// More values...
		},
		MessageStructure: aws.String("messageStructure"),
		Subject:          aws.String("subject"),
		TargetArn:        aws.String("String"),
		TopicArn:         aws.String("topicARN"),
	}
	resp, err := svc.Publish(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Beispiel #15
0
func (awssns *AwsSnsNotifier) Send(subject string, message string) bool {
	svc := sns.New(session.New(&aws.Config{
		Region: aws.String(awssns.Region),
	}))

	params := &sns.PublishInput{
		Message: aws.String(message),
		MessageAttributes: map[string]*sns.MessageAttributeValue{
			"Key": {
				DataType:    aws.String("String"),
				StringValue: aws.String("String"),
			},
		},
		MessageStructure: aws.String("messageStructure"),
		Subject:          aws.String(subject),
		TopicArn:         aws.String(awssns.TopicArn),
	}

	resp, err := svc.Publish(params)
	if err != nil {
		log.Println(err.Error())
		return false
	}
	log.Println(resp)

	return true
}
Beispiel #16
0
func main() {
	abc := 123
	fmt.Println(abc)
	config := aws.Config{Region: aws.String("us-west-2")}
	svc := sns.New(&config)
	fmt.Println(svc.APIVersion)
}
Beispiel #17
0
/*
PublishSNS publishes message to a SNS topic (EC2SPOT_SNS_TOPIC) and returns Error
Refer to SNS struct for required properties
*/
func PublishSNS(c Config) (err error) {

	// AWS initialization
	client := sns.New(session.New(), &aws.Config{Region: aws.String(c.Region)})

	/*
		    SNS params prior to publish message to topic
			ref: http://docs.aws.amazon.com/sdk-for-go/api/service/sns/SNS.html#Publish-instance_method
	*/
	params := &sns.PublishInput{
		Message: aws.String(string(c.SNS.Message)),
		MessageAttributes: map[string]*sns.MessageAttributeValue{
			"Key": {
				DataType:    aws.String("String"),
				StringValue: aws.String("String"),
			},
		},
		Subject:  aws.String(c.SNS.Subject),
		TopicArn: aws.String(c.SNS.Topic),
	}

	_, errs := client.Publish(params)
	if errs != nil {
		err = fmt.Errorf("[!] Error found while trying to publish instance details via SNS: %s", errs)
	}

	return
}
Beispiel #18
0
func ExampleSNS_CreatePlatformEndpoint() {
	sess, err := session.NewSession()
	if err != nil {
		fmt.Println("failed to create session,", err)
		return
	}

	svc := sns.New(sess)

	params := &sns.CreatePlatformEndpointInput{
		PlatformApplicationArn: aws.String("String"), // Required
		Token: aws.String("String"), // Required
		Attributes: map[string]*string{
			"Key": aws.String("String"), // Required
			// More values...
		},
		CustomUserData: aws.String("String"),
	}
	resp, err := svc.CreatePlatformEndpoint(params)

	if err != nil {
		// Print the error, cast err to awserr.Error to get the Code and
		// Message from an error.
		fmt.Println(err.Error())
		return
	}

	// Pretty-print the response data.
	fmt.Println(resp)
}
Beispiel #19
0
func ExampleSNS_AddPermission() {
	svc := sns.New(nil)

	params := &sns.AddPermissionInput{
		AWSAccountID: []*string{ // Required
			aws.String("delegate"), // Required
			// More values...
		},
		ActionName: []*string{ // Required
			aws.String("action"), // Required
			// More values...
		},
		Label:    aws.String("label"),    // Required
		TopicARN: aws.String("topicARN"), // Required
	}
	resp, err := svc.AddPermission(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
Beispiel #20
0
func ExampleSNS_Unsubscribe() {
	svc := sns.New(nil)

	params := &sns.UnsubscribeInput{
		SubscriptionARN: aws.String("subscriptionARN"), // Required
	}
	resp, err := svc.Unsubscribe(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.StringValue(resp))
}
Beispiel #21
0
func ExampleSNS_SetTopicAttributes() {
	svc := sns.New(nil)

	params := &sns.SetTopicAttributesInput{
		AttributeName:  aws.String("attributeName"), // Required
		TopicArn:       aws.String("topicARN"),      // Required
		AttributeValue: aws.String("attributeValue"),
	}
	resp, err := svc.SetTopicAttributes(params)

	if err != nil {
		if awsErr, ok := err.(awserr.Error); ok {
			// Generic AWS error with Code, Message, and original error (if any)
			fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr())
			if reqErr, ok := err.(awserr.RequestFailure); ok {
				// A service error occurred
				fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID())
			}
		} else {
			// This case should never be hit, the SDK should always return an
			// error which satisfies the awserr.Error interface.
			fmt.Println(err.Error())
		}
	}

	// Pretty-print the response data.
	fmt.Println(awsutil.Prettify(resp))
}
Beispiel #22
0
func findExistingTopicARN(config *aws.Config, topic string) (string, error) {
	svc := sns.New(nil)

	params := &sns.ListTopicsInput{
		NextToken: nil,
	}

	for {
		resp, err := svc.ListTopics(params)
		if awserr, ok := err.(awserr.Error); ok {
			return "", fmt.Errorf("aws error while listing SNS topics: %v %v", awserr.Code(), awserr.Message())
		} else if err != nil {
			return "", fmt.Errorf("error while listing SNS topics: %v", err)
		} else if resp == nil || resp.Topics == nil {
			break
		}

		for _, topicPtr := range resp.Topics {
			if topicPtr != nil && topicPtr.TopicArn != nil && strings.HasSuffix(*topicPtr.TopicArn, topic) {
				return *topicPtr.TopicArn, nil
			}
		}

		if resp.NextToken != nil {
			params.NextToken = resp.NextToken
		} else {
			break
		}
	}

	return "", nil
}
// Create a push notification manager
func NewPushNotification(awsAccessKey string, awsSecretKey string, region string) *PushNotification {
	entity := new(PushNotification)
	cred := credentials.NewStaticCredentials(awsAccessKey, awsSecretKey, "")
	config := aws.NewConfig().WithRegion(region).WithCredentials(cred)
	sess := session.New(config)
	entity.sns = sns.New(sess)
	return entity
}
Beispiel #24
0
func forwardToSNS(data []byte) error {
	svc := sns.New(&aws.Config{Region: region})

	params := &sns.PublishInput{
		Message:  aws.String(string(data)),
		TopicARN: aws.String(*topicARN),
	}
	_, err := svc.Publish(params)
	return err
}
Beispiel #25
0
func (r *Resource) GetSNS() *sns.SNS {
	r.mutex.Lock()
	defer r.mutex.Unlock()

	if _, ok := r.services["sns"]; !ok {
		r.services["sns"] = sns.New(session.New(r.awsConfig))
	}

	return r.services["sns"].(*sns.SNS)
}
Beispiel #26
0
// NewLifeCycle creates a new lifecycle management system, everything begins
// with an autoscaling resource, we are listening to any change on that
// resource, to be able to listen them we are attaching a notification
// configuration to given autoscaling resource, notification configuration works
// with a TopicARN, which is basically a SNS Topic, to be able to listen from a
// Topic ARN we need a SQS, SQS is attached to Notification Topic and configured
// to pass events as soon as they occur, it also has re- try mechanism. One
// event only be handled by one manager, there wont be any race condition on
// processing that particular message. Manager is idempotent, if any given
// resource doesnt exist in the given AWS system, it will create or re-use the
// previous ones
func NewLifeCycle(session *session.Session, log logging.Logger, asgName string) *LifeCycle {
	return &LifeCycle{
		closed:      false,
		closeChan:   make(chan chan struct{}),
		ec2:         ec2.New(session),
		sqs:         sqs.New(session),
		sns:         sns.New(session),
		autoscaling: autoscaling.New(session),
		asgName:     &asgName,
		log:         log.New("lifecycle"),
	}
}
func (command SNSLambdaEventSourceResource) updateRegistration(isTargetActive bool,
	session *session.Session,
	logger *logrus.Logger) (map[string]interface{}, error) {

	// Get the current subscriptions...
	snsSvc := sns.New(session)
	snsInput := &sns.ListSubscriptionsByTopicInput{
		TopicArn: aws.String(command.SNSTopicArn.Literal),
	}
	listSubscriptions, listSubscriptionsErr := snsSvc.ListSubscriptionsByTopic(snsInput)
	if nil != listSubscriptionsErr {
		return nil, listSubscriptionsErr
	}
	var lambdaSubscriptionArn string
	for _, eachSubscription := range listSubscriptions.Subscriptions {
		if *eachSubscription.Protocol == "lambda" && *eachSubscription.Endpoint == command.LambdaTargetArn.Literal {
			if "" != lambdaSubscriptionArn {
				return nil, fmt.Errorf("Multiple SNS %s registrations found for lambda: %s",
					*snsInput.TopicArn,
					command.LambdaTargetArn.Literal)
			}
			lambdaSubscriptionArn = *eachSubscription.SubscriptionArn
		}
	}
	// Just log it...
	logger.WithFields(logrus.Fields{
		"SNSTopicArn":             command.SNSTopicArn,
		"LambdaArn":               command.LambdaTargetArn,
		"ExistingSubscriptionArn": lambdaSubscriptionArn,
	}).Info("Current SNS subscription status")

	var opErr error
	if isTargetActive && "" == lambdaSubscriptionArn {
		subscribeInput := &sns.SubscribeInput{
			Protocol: aws.String("lambda"),
			TopicArn: aws.String(command.SNSTopicArn.Literal),
			Endpoint: aws.String(command.LambdaTargetArn.Literal),
		}
		_, opErr = snsSvc.Subscribe(subscribeInput)
	} else if !isTargetActive && "" != lambdaSubscriptionArn {
		unsubscribeInput := &sns.UnsubscribeInput{
			SubscriptionArn: aws.String(lambdaSubscriptionArn),
		}
		_, opErr = snsSvc.Unsubscribe(unsubscribeInput)
	} else {
		// Just log it...
		logger.WithFields(logrus.Fields{
			"Command": command,
		}).Info("No SNS operation required")
	}

	return nil, opErr
}
Beispiel #28
0
// Create a new StorageClient object based on a configuration file.
func (c *Config) NewClient() (dialects.StorageClient, error) {
	creds := credentials.NewStaticCredentials(c.AccessKeyID, c.SecretAccessKey, "")
	_, err := creds.Get()
	if err != nil {
		return nil, err
	}
	return &SNSStorage{
		AccessKeyID:     c.AccessKeyID,
		SecretAccessKey: c.SecretAccessKey,
		TopicArn:        c.TopicArn,
		Client:          sns.New(session.New(), &aws.Config{Region: &c.Region, Credentials: creds})}, nil
}
Beispiel #29
0
func NewAwsProvider(key string, secret string, region string, debug bool) *Aws {
	config := aws.NewConfig().
		WithCredentials(credentials.NewStaticCredentials(key, secret, "")).
		WithRegion(region)

	if debug {
		config.WithLogLevel(aws.LogDebug)
	}

	return &Aws{
		client: sns.New(config),
	}
}
Beispiel #30
0
// NewWithEndpoint works like New but allows you to override the AWS HTTP
// endpoint to send requests to.
func NewWithEndpoint(endpoint, region, topic string) beacon.Backend {
	cfg := &aws.Config{}
	if endpoint != "" {
		cfg.Endpoint = aws.String(endpoint)
	}
	if region != "" {
		cfg.Region = aws.String(region)
	}
	return &sns{
		client: awssns.New(session.New(), cfg),
		topic:  topic,
	}
}