Search code examples
amazon-web-servicescommand-line-interfaceaws-cliamazon-sns

Publish SNS message with AWS CLI including attributes


What is the correct syntax to include message attributes when publishing a message to an SNS topic? I know it's --message-attributes, but how to properly pass the values?

For example, to send a message I use this command line:

aws sns publish --topic-arn "arn:aws:sns:us-east-1:09706xxxxxxx:UpdatesTopic" --message "Update 1"

I want to include these message attributes:

MessageAttributes={
            'type': {
                'DataType': 'String',
                'StringValue': 'event_type_a'
            },
            'srcArn': {
                'DataType': 'String',
                'StringValue': f'arn:aws:ec2:us-east-1:09706xxxxxxx:instance/instance_a'
            },
            'session_id': {
                'DataType': 'String',
                'StringValue': 'abc123'
            },
            'owner': {
                'DataType': 'String',
                'StringValue': 'me'
            }
        }

Solution

  • You could use:

    aws sns publish --topic-arn "arn:aws:sns:us-east-1:09706xxxxxxx:UpdatesTopic" --message "hello" --message-attributes '{"type":{"DataType":"String","StringValue":"event_type_a"},"srcArn":{"DataType":"String","StringValue":"arnxxx"}}'
    

    or even:

    aws sns publish --topic-arn "arn:aws:sns:us-east-1:09706xxxxxxx:UpdatesTopic" --message "hello" --message-attributes '
    {
        "type": {
            "DataType": "String",
            "StringValue": "event_type_a"
        },
        "srcArn": {
            "DataType": "String",
            "StringValue": "arnxxx"
        }
    }
    

    This worked on a Mac. If you use Windows, then you might need to change your handling of quotation marks.