Path: blob/develop/awscli/customizations/configservice/subscribe.py
1567 views
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.1#2# Licensed under the Apache License, Version 2.0 (the "License"). You3# may not use this file except in compliance with the License. A copy of4# the License is located at5#6# http://aws.amazon.com/apache2.0/7#8# or in the "license" file accompanying this file. This file is9# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF10# ANY KIND, either express or implied. See the License for the specific11# language governing permissions and limitations under the License.12import json13import sys1415from awscli.customizations.commands import BasicCommand16from awscli.customizations.utils import s3_bucket_exists17from awscli.customizations.s3.utils import find_bucket_key181920S3_BUCKET = {'name': 's3-bucket', 'required': True,21'help_text': ('The S3 bucket that the AWS Config delivery channel'22' will use. If the bucket does not exist, it will '23'be automatically created. The value for this '24'argument should follow the form '25'bucket/prefix. Note that the prefix is optional.')}2627SNS_TOPIC = {'name': 'sns-topic', 'required': True,28'help_text': ('The SNS topic that the AWS Config delivery channel'29' will use. If the SNS topic does not exist, it '30'will be automatically created. Value for this '31'should be a valid SNS topic name or the ARN of an '32'existing SNS topic.')}3334IAM_ROLE = {'name': 'iam-role', 'required': True,35'help_text': ('The IAM role that the AWS Config configuration '36'recorder will use to record current resource '37'configurations. Value for this should be the '38'ARN of the desired IAM role.')}394041def register_subscribe(cli):42cli.register('building-command-table.configservice', add_subscribe)434445def add_subscribe(command_table, session, **kwargs):46command_table['subscribe'] = SubscribeCommand(session)474849class SubscribeCommand(BasicCommand):50NAME = 'subscribe'51DESCRIPTION = ('Subscribes user to AWS Config by creating an AWS Config '52'delivery channel and configuration recorder to track '53'AWS resource configurations. The names of the default '54'channel and configuration recorder will be default.')55ARG_TABLE = [S3_BUCKET, SNS_TOPIC, IAM_ROLE]5657def __init__(self, session):58self._s3_client = None59self._sns_client = None60self._config_client = None61super(SubscribeCommand, self).__init__(session)6263def _run_main(self, parsed_args, parsed_globals):64# Setup the necessary all of the necessary clients.65self._setup_clients(parsed_globals)6667# Prepare a s3 bucket for use.68s3_bucket_helper = S3BucketHelper(self._s3_client)69bucket, prefix = s3_bucket_helper.prepare_bucket(parsed_args.s3_bucket)7071# Prepare a sns topic for use.72sns_topic_helper = SNSTopicHelper(self._sns_client)73sns_topic_arn = sns_topic_helper.prepare_topic(parsed_args.sns_topic)7475name = 'default'7677# Create a configuration recorder.78self._config_client.put_configuration_recorder(79ConfigurationRecorder={80'name': name,81'roleARN': parsed_args.iam_role82}83)8485# Create a delivery channel.86delivery_channel = {87'name': name,88's3BucketName': bucket,89'snsTopicARN': sns_topic_arn90}9192if prefix:93delivery_channel['s3KeyPrefix'] = prefix9495self._config_client.put_delivery_channel(96DeliveryChannel=delivery_channel)9798# Start the configuration recorder.99self._config_client.start_configuration_recorder(100ConfigurationRecorderName=name101)102103# Describe the configuration recorders104sys.stdout.write('Subscribe succeeded:\n\n')105sys.stdout.write('Configuration Recorders: ')106response = self._config_client.describe_configuration_recorders()107sys.stdout.write(108json.dumps(response['ConfigurationRecorders'], indent=4))109sys.stdout.write('\n\n')110111# Describe the delivery channels112sys.stdout.write('Delivery Channels: ')113response = self._config_client.describe_delivery_channels()114sys.stdout.write(json.dumps(response['DeliveryChannels'], indent=4))115sys.stdout.write('\n')116117return 0118119def _setup_clients(self, parsed_globals):120client_args = {121'verify': parsed_globals.verify_ssl,122'region_name': parsed_globals.region123}124self._s3_client = self._session.create_client('s3', **client_args)125self._sns_client = self._session.create_client('sns', **client_args)126# Use the specified endpoint only for config related commands.127client_args['endpoint_url'] = parsed_globals.endpoint_url128self._config_client = self._session.create_client('config',129**client_args)130131132class S3BucketHelper(object):133def __init__(self, s3_client):134self._s3_client = s3_client135136def prepare_bucket(self, s3_path):137bucket, key = find_bucket_key(s3_path)138bucket_exists = self._check_bucket_exists(bucket)139if not bucket_exists:140self._create_bucket(bucket)141sys.stdout.write('Using new S3 bucket: %s\n' % bucket)142else:143sys.stdout.write('Using existing S3 bucket: %s\n' % bucket)144return bucket, key145146def _check_bucket_exists(self, bucket):147return s3_bucket_exists(self._s3_client, bucket)148149def _create_bucket(self, bucket):150region_name = self._s3_client.meta.region_name151params = {152'Bucket': bucket153}154bucket_config = {'LocationConstraint': region_name}155if region_name != 'us-east-1':156params['CreateBucketConfiguration'] = bucket_config157self._s3_client.create_bucket(**params)158159160class SNSTopicHelper(object):161def __init__(self, sns_client):162self._sns_client = sns_client163164def prepare_topic(self, sns_topic):165sns_topic_arn = sns_topic166# Create the topic if a name is given.167if not self._check_is_arn(sns_topic):168response = self._sns_client.create_topic(Name=sns_topic)169sns_topic_arn = response['TopicArn']170sys.stdout.write('Using new SNS topic: %s\n' % sns_topic_arn)171else:172sys.stdout.write('Using existing SNS topic: %s\n' % sns_topic_arn)173return sns_topic_arn174175def _check_is_arn(self, sns_topic):176# The name of topic cannot contain a colon only arns have colons.177return ':' in sns_topic178179180