Giter Site home page Giter Site logo

saltstack-formulas / ec2-autoscale-reactor Goto Github PK

View Code? Open in Web Editor NEW
76.0 47.0 28.0 154 KB

Autonomous Minion Management via EC2 Autoscaler

Home Page: http://docs.saltstack.com/en/latest/topics/development/conventions/formulas.html

License: Other

SaltStack 100.00%

ec2-autoscale-reactor's Introduction

ec2-autoscale-reactor

This is a reactor formula, which allows the autoscaling feature in EC2 to notify Salt when an instance is created, so that it may be automatically bootstrapped and accepted by the Salt Master, or when an instance is deleted, so that its key can be automatically removed from the Salt Master.

Dependencies

The following packages must be installed:

- Salt (develop branch)

Master Configuration

The following files need to be configured on the Salt Master:

- /etc/salt/master
- /etc/salt/cloud.providers.d/ec2.conf
- /srv/reactor/ec2-autoscale.sls (from this package)

/etc/salt/master

This reactor makes use of the web hooks system introduced in Salt API 0.8.4. The configuration for Salt API is stored in the master configuration file:

external_auth:
  pam:
    myuser:
      - .*
      - '@runner'
      - '@wheel'

rest_cherrypy:
  port: 8080
  host: 0.0.0.0
  webhook_url: /hook
  webhook_disable_auth: True

When a web request is received, Salt API will fire an event for the reactor system to pick up:

reactor:
  - 'salt/netapi/hook/ec2/autoscale':
    - '/srv/reactor/ec2-autoscale.sls'

This reactor will examine the web hook received from EC2 and check its authenticity. If issues are encountered, such as an invalid signature, or the certificates being located outside of Amazon, a notification will be sent to the user via email. The following settings are an example of SMTP settings that might be used to connect to the mail server:

smtp.from: '[email protected]'
smtp.to: [email protected]; [email protected]
smtp.host: smtp.gmail.com
smtp.username: '[email protected]'
smtp.password: 'verybadpass'
smtp.tls: True
smtp.subject: 'Salt'

Finally, some extra settings must be set up to point the reactor to the necessary Salt Cloud provider setting. Any additional settings to be used on the target minion, that are not configured in the provider configuration, can also be set here.

ec2.autoscale:
  provider: my-ec2-config
  ssh_username: ec2-user

/etc/salt/cloud.providers.d/ec2.conf

Existing Salt Cloud provider configuration can be used with this reactor. Profile configuration is not necessary on the master; minions will be configured as per the EC2 Autoscaling Group.

my-ec2-config:
  id: <aws id>
  key: <aws key>
  keyname: <my key name>
  securitygroup: <my security group>
  private_key: </path/to/my/priv_key.pem>
  location: us-east-1
  provider: ec2
  minion:
    master: saltmaster.example.com

/srv/reactor/ec2-autoscale.sls

This package includes a file in its reactor/ directory called ec2-autoscale.sls. Create the /src/reactor/ directory on the Salt Master if it doesn't already exist, and copy this file into it.

EC2 Configuration

The following must be configured in the EC2 account to be used:

- SNS HTTP Notification
- Launch Configuration
- Autoscaling Group

SNS HTTP(S) Notification

In order to notify the reactor that an instance is being autoscaled up or down, AWS SNS must be configured with the URL to send the notification webhook to. Both HTTP and HTTPS are available, but it is highly recommended that HTTPS is used.

From the AWS Console, select SNS (Push Notification Service). This will take you to the SNS dashboard.

Click the button to Create New Topic. Enter a Topic Name, and a human-readable Display Name, and select the Create Topic button. This will take you to the Topic Details area.

Inside the Topic Details, click the button to Create Subscription. Select HTTP or HTTPS as appropriate, and enter the URL to your Salt API server as the endpoint. Assuming it is set up at https://saltmaster.example.com/, the endpoint will look like:

https://saltmaster.example.com/hook/ec2/autoscale

In this URL, /hook notifies Salt API that a webhook is being used, and /ec2/autoscale will be used to tag the event that the reactor uses to process it. The tag that will be created by this URL will be

salt/netapi/hook/ec2/autoscale

Clicking the Subscribe button will cause a subscription notification to be sent immediately to the endpoint. If the Master configuration is correct, the reactor will forward the subscription notication to the configured email address(es). This message will contain a subscribe URL which, when visited, will activate the Subscription.

If the Salt Master is not properly configured, the endpoint can be re-entered, and another subscription notifcation will be sent. It should be noted that once configured, a subscription may not be deleted via the web interface until the subscribe URL has been visited and confirmed.

Launch Configuration

In order to start autoscaling instances, EC2 requires a launch configuration to be set. This defines the EC2-specific variables (AMI, disks, etc.) that will be used to spin up new instances.

From the AWS Console, select EC2 (Virtual Servers in the Cloud), which will lead to the EC2 Management Console. From there, select Launch Configurations from the left-hand menu.

Click the Create Launch Configuration button. Follow the wizard to select the appropriate AMI and configuration to use. At the Review screen, click the Create Launch Configuration button to save.

Autoscaling Group

Once a launch configuration is defined, an autoscaling group may be configured which defines variables such as the minimum and maximum number of instances, and under what circumstances to add and remove instances.

From the AWS Console, select Auto Scaling Groups from the left-hand menu. Click the Create Auto Scaling Group button. Select the option to "Create an Auto Scaling group from an existing launch configuration". Select the Launch Configuration, and click Next Step.

Follow the wizard to the "Configure Notifications" screen. Click the "Add Notification" button and select the notification that was configured on SNS. Complete the wizard as normal.

Basic Usage

Once the Salt Master and AWS have been configured, the reactor will manage itself. When the autoscaler adds a new instance, Salt Cloud will be notified to wait for it to become available, and bootstrap it with Salt. Its key will be automatically accepted, and if the minion configuration includes the appropriate startup state, then the minion will configure itself, and go to work.

When the autoscaler spins down a machine, the Wheel system inside of Salt will be notified to delete its key from the master. This causes instances to be completely autonomous, both in setup and tear-down.

Caveats

As instances will be launched and destroyed automatically by EC2, they will not have the opportunity to be configured with user-definable names, and will therefore be identified to the master by their instance-id. In the event that more detailed identifying information needs to be available, the instances should be configured to include EC2 tags, which can later be read and displayed to the user via Salt Cloud.

ec2-autoscale-reactor's People

Contributors

nmadhok avatar techhat avatar whiteinge avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ec2-autoscale-reactor's Issues

Setup Issues

Hello, I have a number of salt ec2 auto scale groups that I am trying to saltify. However, I'm having a few issues attempting to set this up. This formula is the most recent I can find but i'm unsure if this is still the most current or recommended method for having salt bootstrap new instances deployed within an ec2 vpc autoscale group?

is the develop branch still required? i'm just running the latest stable given it seems quite old..

here are my salt version details:

$ salt --versions-report
           Salt: 2015.5.0
         Python: 2.6.9 (unknown, Apr  1 2015, 18:16:00)
         Jinja2: 2.7.2
       M2Crypto: 0.21.1
 msgpack-python: 0.4.6
   msgpack-pure: Not Installed
       pycrypto: 2.6.1
        libnacl: Not Installed
         PyYAML: 3.10
          ioflo: Not Installed
          PyZMQ: 14.3.1
           RAET: Not Installed
            ZMQ: 3.2.5
           Mako: Not Installed

the main problem I am having is setting up SNS over SSL. your documentation makes no mention of configuring salt-api for SSL but salt-api appears to needs a crt & key or for ssl to be explicitly disabled.

ive got the system working fine running salt-api with disable_ssl true and an SNS endpoint over HTTP, i receive the notifications and reactor goes to work, but that highlights my main concern with this method going over public internet.. even with SSL i'm not sure i'd want this, as it poses the issue of locking my salt instance port 8080 down to the SNS IP range, something which is notoriously difficult. Ideally i'd want SNS hitting my salt instance privately or utilizing IAM roles but i am unsure that is possible at this stage.

but first things first, trying to enable salt-api running with SSL, i've tried about 7 differently generated selfsigned SSL certs and also one proper wildcard ssl in use for my primary domain. All have resulted in salt-api throwing the following errors when receiving messages from SNS:

[ERROR   ] [14/Jul/2015:05:33:53] ENGINE Error in HTTPServer.tick
Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 1837, in start
    self.tick()
  File "/usr/lib/python2.6/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 1902, in tick
    s, ssl_env = self.ssl_adapter.wrap(s)
  File "/usr/lib/python2.6/site-packages/cherrypy/wsgiserver/ssl_builtin.py", line 52, in wrap
    keyfile=self.private_key, ssl_version=ssl.PROTOCOL_SSLv23)
  File "/usr/lib64/python2.6/ssl.py", line 338, in wrap_socket
    suppress_ragged_eofs=suppress_ragged_eofs)
  File "/usr/lib64/python2.6/ssl.py", line 120, in __init__
    self.do_handshake()
  File "/usr/lib64/python2.6/ssl.py", line 279, in do_handshake
    self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:493: error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown

this includes using the salt module 'salt-call tls.create_self_signed_cert' to generate one, no dice.

  1. what is the requirement here for a secure connection between SNS and my salt instance?
  2. is it possible to have SNS communicate privately ore more securely with my salt instance because this doesn't seem ideal?
  3. whats the most up to date method of having salt/salt-cloud etc. take charge of autoscaling?

Docs don't specify where to put SMTP settings

I'm new to saltstack, so docs with simultaneously vague and specific instructions, such as "The following settings are an example of SMTP settings that might be used to connect to the mail server" are extremely frustrating, and seemingly everywhere in the salt docs. Where do I put those settings? What file? In the reactor settings or the master settings?

Error in Log

2016-02-17 09:48:16,756 [salt.utils.reactor][ERROR   ][14898] Failed to render "/srv/reactor/ec2-autoscale.sls":
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/salt/utils/reactor.py", line 53, in render_reaction
    data=data)
  File "/usr/lib/python2.7/dist-packages/salt/state.py", line 280, in render_template
    template, self.rend, self.opts['renderer'], **kwargs)
  File "/usr/lib/python2.7/dist-packages/salt/template.py", line 95, in compile_template
    ret = render(input_data, saltenv, sls, **render_kwargs)
  File "/usr/lib/python2.7/dist-packages/salt/renderers/py.py", line 112, in render
    'Unknown render error in py renderer'))
SaltRenderError: Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/salt/utils/templates.py", line 522, in py
    data = mod.run()
  File "/srv/reactor/ec2-autoscale.sls", line 83, in run
    instance_id = str(message['EC2InstanceId'])
KeyError: 'EC2InstanceId'

Is there anyway to debug the message being sent to ec2-autoscale.sls?

Clarification needed for ec2.conf

Need some clarification on the ec2.conf settings.

my-ec2-config:
  id: <aws id>
  key: <aws key>
  keyname: <my key name>
  securitygroup: <my security group>
  private_key: </path/to/my/priv_key.pem>
  location: us-east-1
  provider: ec2
  minion:
    master: saltmaster.example.com

Is id the aws account id? the aws_access_key_id?
Is key is this the aws_access_key_id? the aws_secret_access_key?
What about keyname? securitygroup? and private_key?

exception occurred in runner cloud.create

I have tested it with latest version of saltstack (2016.3.4), but it was returned an exception after reacting a new event from auto scaling group.It seems that "cloud.create runner" needed one more argument to work with event as well. Probably something is changed in latest version of salt which contain core framework.

Exception

salt/run/20161124075253378593/ret { "_stamp": "2016-11-24T07:52:53.444115", "fun": "runner.cloud.create", "jid": "20161124075253378593", "return": "Exception occurred in runner cloud.create: Traceback (most recent call last):\n File \"/usr/lib/python2.7/site-packages/salt/client/mixins.py\", line 326, in low\n expected_extra_kws=CLIENT_INTERNAL_KEYWORDS\n File \"/usr/lib/python2.7/site-packages/salt/utils/__init__.py\", line 1021, in format_call\n used_args_count\nSaltInvocationError: create takes at least 2 arguments (1 given)\n", "success": false, "user": "Reactor" }

Tracing log:

2016-11-24 12:10:47,865 [salt.template ][PROFILE ][13984] Time (in seconds) to render '/srv/reactor/ec2-autoscale.sls' using 'py' renderer: 0.0761120319366 2016-11-24 12:10:47,879 [salt.utils.process][DEBUG ][13984] ThreadPool executing func: <bound method RunnerClient.low of <salt.runner.RunnerClient object at 0x32ad7d0>> with args:('cloud.create', {'name': u'ec2_autoscale_launch', 'instance_id': 'i-5c6c50cg', 'instances': 'i-5c6c50cg', 'state': 'runner', '__user__': 'Reactor', '__sls__': '/srv/reactor/ec2-autoscale.sls', 'reactor': True, 'order': 1, '__id__': 'ec2_autoscale_launch'}) kwargs{}

Failed to Render

I've been trying to configure this to work with my auto-scaling groups, but I can't seem to see past the following error:

2014-08-11 19:48:17,101 [salt.utils.event ][ERROR ] Failed to render "/srv/reactor/ec2-autoscale.sls"

Getting Ec2 Autoscale Signature Errors after sending subscription request to Salt from SNS

Hi,

Here's the body of the e-mail I receive from init.sls:

There was an error with the EC2 Signature. Content received was:

{'Message': '{"notificationType":"Delivery","mail":{"timestamp":"2016-01-05T21:53:41.711Z","source":"[email protected]","sourceArn":"arn:aws:ses:us-east-1:119183261856:identity/[email protected]","sendingAccountId":"119183261856","messageId":"0000015213c8054f-5ea63928-47a9-4094-a787-dd8d004fe1a7-000000","destination":["[email protected]"]},"delivery":{"timestamp":"2016-01-05T21:53:42.365Z","processingTimeMillis":654,"recipients":["[email protected]"],"smtpResponse":"250 2.0.0 OK 1452030822 b6si8242311qhb.113 - gsmtp","reportingMTA":"a9-40.smtp-out.amazonses.com"}}',
 'MessageId': '73756525-2fee-5876-8163-2a231248adaf',
 'Signature': 'Tf+hoY9dfVesumthZ3chSXOBXd81ivsYWqiqdfIblapgiyNRdd4qavzWWhURF6r0sXO8kTfh4UzERIk2NpMVzi0P2UE4UFlyZWLLMyLmMgYGDQ4EGNvx60D/IU4rbNaBmZf/TXrOzj0VxtNl3T0QWwBZo7W/f7Fzgmv+lzuASNaCUM8oBm7dO1FcR6WX8UJm4+uAsoWQ50Gr9tvqO7eeKFC18FKhr9iMtgi6zy6luJ30mUGOmWwTWmqBqDBh/qMpxgwQsUyqLGq4XBMc/8mLR2brb7phw5vvk5SXDOxttIeVxH2z5bqZFkZ08DomuOQG9hy3KKAezbMSKFiofC5WzA==',
 'SignatureVersion': '1',
 'SigningCertURL': 'https://sns.us-east-1.amazonaws.com/SimpleNotificationService-bb750dd426d95ee9390147a5624348ee.pem',
 'Subject': '',
 'Timestamp': '2016-01-05T21:53:42.442Z',
 'TopicArn': 'arn:aws:sns:us-east-1:119183261856:Delivery-Autoscaling-Events',
 'Type': 'Notification',
 'UnsubscribeURL': 'https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:119183261856:Delivery-Autoscaling-Events:72b708fc-d558-4284-8a59-5093798b4e91'}

It's this bit of code that's doing it, I'm pretty sure.

    cert = M2Crypto.X509.load_cert_string(str(pem))
    pubkey = cert.get_pubkey()
    pubkey.reset_context(md='sha1')
    pubkey.verify_init()
    pubkey.verify_update(str_to_sign.encode())

    decoded = binascii.a2b_base64(sns['Signature'])
    result = pubkey.verify_final(decoded)

    if result != 1:
        msg_kwargs = {
            'smtp.subject': 'EC2 Autoscale Signature Error (via Salt Reactor)',
            'smtp.content': (
                'There was an error with the EC2 Signature. '
                'Content received was:\r\n\r\n{0}\r\n').format(
                    pprint.pformat(sns)
                ),

Something derailing during the binascii.a2b_base64 function maybe?
Any ideas what could be wrong? OR things I could check?

Thanks for any hints!

-Presley

Adjustment for Salt 2017.7

Just in case someone needs this, to make this reactor compartible with salt 2017, code starting from line https://github.com/saltstack-formulas/ec2-autoscale-reactor/blob/master/ec2-autoscale/init.sls#L86 should look like this:

        vm_ = __opts__.get('ec2.autoscale', {})
        vm_['reactor'] = True
        vm_['instances'] = instance_id
        vm_['instance_id'] = instance_id
        # Fire off an event to wait for the machine
        return {
            'ec2_autoscale_launch': {
                'runner.cloud.create': [{'kwarg': vm_}]
            }
        }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.