Ejemplo n.º 1
0
def main():
    '''Function: Generates the Cloudformation template'''
    template = Template()

    keyname_param = template.add_parameter(
        Parameter(
            'KeyName',
            Description='Name of an existing EC2 KeyPair for SSH access',
            ConstraintDescription='Must be the name of an existing EC2 KeyPair.',
            Type='AWS::EC2::KeyPair::KeyName',
        )
    )

    password_param = template.add_parameter(
        Parameter(
            'PassWord',
            Type='String',
            NoEcho=True,
            MinLength=8,
            MaxLength=64,
            Description='Password for the admin account',
            ConstraintDescription='A complex password at least eight chars long with alphanumeric characters, dashes and underscores.',
            AllowedPattern="[-_a-zA-Z0-9]*",
        )
    )

    template.add_mapping('RegionMap', {'ap-south-1': {'ami': 'ami-ee8ea481'}, 'eu-west-3': {'ami': 'ami-daf040a7'}, 'eu-west-2': {'ami': 'ami-ddb950ba'}, 'eu-west-1': {'ami': 'ami-d2414e38'}, 'ap-northeast-2': {'ami': 'ami-65d86d0b'}, 'ap-northeast-1': {'ami': 'ami-e875a197'}, 'sa-east-1': {'ami': 'ami-ccd48ea0'}, 'ca-central-1': {'ami': 'ami-c3e567a7'}, 'ap-southeast-1': {'ami': 'ami-31e7e44d'}, 'ap-southeast-2': {'ami': 'ami-23c51c41'}, 'eu-central-1': {'ami': 'ami-3c635cd7'}, 'us-east-1': {'ami': 'ami-5cc39523'}, 'us-east-2': {'ami': 'ami-67142d02'}, 'us-west-1': {'ami': 'ami-d7b355b4'}, 'us-west-2': {'ami': 'ami-39c28c41'}})

    ec2_security_group = template.add_resource(
        ec2.SecurityGroup(
            'SecurityGroup',
            GroupDescription='SSH, HTTP/HTTPS open for 0.0.0.0/0',
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(
                    IpProtocol='tcp',
                    FromPort='22',
                    ToPort='22',
                    CidrIp='0.0.0.0/0'),
                ec2.SecurityGroupRule(
                    IpProtocol='tcp',
                    FromPort='80',
                    ToPort='80',
                    CidrIp='0.0.0.0/0'),
                ec2.SecurityGroupRule(
                    IpProtocol='tcp',
                    FromPort='443',
                    ToPort='443',
                    CidrIp='0.0.0.0/0'),
            ],
        )
    )
    ec2_role = template.add_resource(
        Role('EC2Role',
		AssumeRolePolicyDocument={ "Version" : "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "ec2.amazonaws.com" ] }, "Action": [ "sts:AssumeRole" ] } ] },
    	)
    )
    ec2_policy = template.add_resource(
        ManagedPolicy(
        'EC2Policy',
            PolicyDocument={ "Version": "2012-10-17", "Statement": [ { "Action": "ec2:*", "Resource": "*", "Effect": "Allow" } ] }, Roles=[Ref(ec2_role)]
        )
    )
    ec2_profile = template.add_resource(
        InstanceProfile("EC2InstanceProfile", Roles=[Ref(ec2_role)])
    )
    ec2_instance = template.add_resource(
        ec2.Instance(
            'Instance',
            Metadata=Metadata(
            Init({
                    "config": InitConfig(
                        files=InitFiles({
                            "/etc/nginx/conf.d/jenkins.conf": InitFile(
                                content='server { listen 80 default_server; listen [::]:80  default_server; location / { proxy_pass http://localhost:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }',
                                mode="000644",
                                owner="root",
                                group="root"
                            )
                        }),
                    )
                }),
            ),
            CreationPolicy=CreationPolicy(
                ResourceSignal=ResourceSignal(Timeout='PT15M')
            ),
            ImageId=FindInMap('RegionMap', Ref('AWS::Region'), 'ami'),
            InstanceType='t2.micro',
            IamInstanceProfile=Ref(ec2_profile),
            KeyName=Ref(keyname_param),
            SecurityGroups=[Ref(ec2_security_group)],
            UserData=Base64(
                Join(
                    '',
                    [
                        '#!/bin/bash -x\n',
                        'exec > /tmp/user-data.log 2>&1\n'
                        'unset UCF_FORCE_CONFFOLD\n',
                        'export UCF_FORCE_CONFFNEW=YES\n',
                        'ucf --purge /boot/grub/menu.lst\n',
                        'export DEBIAN_FRONTEND=noninteractive\n',
                        'echo "deb http://pkg.jenkins-ci.org/debian binary/" > /etc/apt/sources.list.d/jenkins.list\n',
                        'wget -q -O jenkins-ci.org.key http://pkg.jenkins-ci.org/debian-stable/jenkins-ci.org.key\n'
                        'apt-key add jenkins-ci.org.key\n',
                        'apt-get update\n',
                        'apt-get -o Dpkg::Options::="--force-confnew" --force-yes -fuy upgrade\n',
                        'apt-get install -y python-pip\n',
                        'pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz\n',
                        'apt-get install -y nginx\n',
                        'apt-get install -y openjdk-8-jdk\n',
                        'apt-get install -y jenkins\n',
                        '# Wait for Jenkins to Set Up\n'
                        "until [ $(curl -o /dev/null --silent --head --write-out '%{http_code}\n' http://localhost:8080) -eq 403 ]; do sleep 1; done\n",
                        'sleep 10\n',
                        '# Change the password for the admin account\n',
                        "echo 'jenkins.model.Jenkins.instance.securityRealm.createAccount(\"admin\", \"",Ref(password_param),"\")' | java -jar /var/cache/jenkins/war/WEB-INF/jenkins-cli.jar -s \"http://localhost:8080/\" -auth \"admin:$(cat /var/lib/jenkins/secrets/initialAdminPassword)\" groovy =\n",
                        '/usr/local/bin/cfn-init --resource=Instance --region=', Ref('AWS::Region'), ' --stack=', Ref('AWS::StackName'), '\n',
                        'unlink /etc/nginx/sites-enabled/default\n',
                        'systemctl reload nginx\n',
                        '/usr/local/bin/cfn-signal -e $? --resource=Instance --region=', Ref('AWS::Region'),
                        ' --stack=', Ref('AWS::StackName'), '\n',
                    ]
                )
            )
        )
    )

    template.add_output([
        Output(
            'PublicDnsName',
            Description='PublicDnsName',
            Value=Join('',['http://', GetAtt(ec2_instance, 'PublicDnsName'),])
        ),
    ])

    print(template.to_yaml())
Ejemplo n.º 2
0
def main():
    '''Function: Generates the Cloudformation template'''
    template = Template()
    template.add_description("A target server for CI/CD tests.")

    keyname_param = template.add_parameter(
        Parameter(
            'KeyName',
            Description='An existing EC2 KeyPair.',
            ConstraintDescription='An existing EC2 KeyPair.',
            Type='AWS::EC2::KeyPair::KeyName',
        ))

    template.add_mapping(
        'RegionMap', {
            'ap-south-1': {
                'ami': 'ami-0dba8796fe499ae48'
            },
            'eu-west-3': {
                'ami': 'ami-07b2287c6776361c8'
            },
            'eu-north-1': {
                'ami': 'ami-34c14f4a'
            },
            'eu-west-2': {
                'ami': 'ami-0573b1dbbd809d6c3'
            },
            'eu-west-1': {
                'ami': 'ami-001b0e20a92d8db1e'
            },
            'ap-northeast-2': {
                'ami': 'ami-0dc961dd0c2c83bdd'
            },
            'ap-northeast-1': {
                'ami': 'ami-0f2c38ac2e37197be'
            },
            'sa-east-1': {
                'ami': 'ami-04ab6be036f8635bd'
            },
            'ca-central-1': {
                'ami': 'ami-0de195e1958cc0d52'
            },
            'ap-southeast-1': {
                'ami': 'ami-08540b8d2f7fa85a5'
            },
            'ap-southeast-2': {
                'ami': 'ami-0bbcf853aaf6ca4a6'
            },
            'eu-central-1': {
                'ami': 'ami-0332a5c40cf835528'
            },
            'us-east-1': {
                'ami': 'ami-0edd3706ab2e952c4'
            },
            'us-east-2': {
                'ami': 'ami-050553a7784d00d21'
            },
            'us-west-1': {
                'ami': 'ami-065ebd3e6b63c75d5'
            },
            'us-west-2': {
                'ami': 'ami-00f13b45242aff065'
            }
        })

    ec2_security_group = template.add_resource(
        ec2.SecurityGroup(
            'EC2SecurityGroup',
            Tags=[
                {
                    'Key': 'Name',
                    'Value': Ref('AWS::StackName')
                },
            ],
            GroupDescription='EC2 Security Group',
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(IpProtocol='tcp',
                                      FromPort='22',
                                      ToPort='22',
                                      CidrIp='0.0.0.0/0',
                                      Description='SSH'),
                ec2.SecurityGroupRule(IpProtocol='tcp',
                                      FromPort='80',
                                      ToPort='80',
                                      CidrIp='0.0.0.0/0',
                                      Description='HTTP'),
                ec2.SecurityGroupRule(IpProtocol='tcp',
                                      FromPort='443',
                                      ToPort='443',
                                      CidrIp='0.0.0.0/0',
                                      Description='HTTPS'),
            ],
        ))

    ec2_instance = template.add_resource(
        ec2.Instance(
            'Instance',
            Metadata=Metadata(
                Init({
                    "config":
                    InitConfig(files=InitFiles({
                        "/tmp/instance.txt":
                        InitFile(content=Ref('AWS::StackName'),
                                 mode="000644",
                                 owner="root",
                                 group="root")
                    }), )
                }), ),
            CreationPolicy=CreationPolicy(ResourceSignal=ResourceSignal(
                Timeout='PT15M')),
            Tags=[
                {
                    'Key': 'Name',
                    'Value': Ref('AWS::StackName')
                },
            ],
            ImageId=FindInMap('RegionMap', Ref('AWS::Region'), 'ami'),
            InstanceType='t2.micro',
            KeyName=Ref(keyname_param),
            SecurityGroups=[Ref(ec2_security_group)],
            UserData=Base64(
                Join('', [
                    '#!/bin/bash -x\n',
                    'exec > /tmp/user-data.log 2>&1\n',
                    'unset UCF_FORCE_CONFFOLD\n',
                    'export UCF_FORCE_CONFFNEW=YES\n',
                    'ucf --purge /boot/grub/menu.lst\n',
                    'export DEBIAN_FRONTEND=noninteractive\n',
                    'apt-get update\n',
                    'apt-get -o Dpkg::Options::="--force-confnew" --force-yes -fuy upgrade\n',
                    'apt-get install -y nginx supervisor build-essential libssl-dev libffi-dev python-pip python3-pip python3-dev python3-setuptools python3-venv\n',
                    'pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz\n',
                    '# Signal Cloudformation when set up is complete\n',
                    '/usr/local/bin/cfn-signal -e $? --resource=Instance --region=',
                    Ref('AWS::Region'),
                    ' --stack=',
                    Ref('AWS::StackName'),
                    '\n',
                ]))))

    template.add_output([
        Output(
            'InstanceDnsName',
            Description='PublicDnsName',
            Value=GetAtt(ec2_instance, 'PublicDnsName'),
        ),
    ])

    print(template.to_yaml())
Ejemplo n.º 3
0
def build_template(keyPair, instanceType):
    ''' Builds the CloudFormation template which will create EC2 and supporting resources. '''
    print
    print '################ 2. Template Build Phase ################'
    print 'Starting CloudFormation template build.'

    ### Template Info ###
    mini_template = Template()

    # Define template version and description
    mini_template.add_version('2010-09-09')
    mini_template.add_description(
        'Provisions VPC, IGW, Route Table, Subnet, and EC2 instance in AWS to support a static website.'
    )

    ### Parameters ###
    instance_type = mini_template.add_parameter(
        Parameter(
            'InstanceType',
            Type='String',
            Description='EC2 instance type',
            Default=instanceType,
            AllowedValues=[
                't1.micro', 't2.micro', 't2.small', 't2.medium', 'm1.small',
                'm1.medium', 'm1.large', 'm1.xlarge', 'm2.xlarge',
                'm2.2xlarge', 'm2.4xlarge', 'm3.medium', 'm3.large',
                'm3.xlarge', 'm3.2xlarge', 'm4.large', 'm4.xlarge',
                'm4.2xlarge', 'm4.4xlarge', 'm4.10xlarge', 'c1.medium',
                'c1.xlarge', 'c3.large', 'c3.xlarge', 'c3.2xlarge',
                'c3.4xlarge', 'c3.8xlarge', 'c4.large', 'c4.xlarge',
                'c4.2xlarge', 'c4.4xlarge', 'c4.8xlarge', 'g2.2xlarge',
                'r3.large', 'r3.xlarge', 'r3.2xlarge', 'r3.4xlarge',
                'r3.8xlarge', 'i2.xlarge', 'i2.2xlarge', 'i2.4xlarge',
                'i2.8xlarge', 'd2.xlarge', 'd2.2xlarge', 'd2.4xlarge',
                'd2.8xlarge', 'hi1.4xlarge', 'hs1.8xlarge', 'cr1.8xlarge',
                'cc2.8xlarge', 'cg1.4xlarge'
            ],
            ConstraintDescription='must be a valid EC2 instance type.',
        ))

    ### Mappings ###

    # AMI Mapping for Amazon Linux AMI as of 03-Jan-2017
    mini_template.add_mapping(
        'AWSRegionArch2AMI', {
            'us-east-1': {
                'HVM64': 'ami-9be6f38c'
            },
            'us-east-2': {
                'HVM64': 'ami-38cd975d'
            },
            'us-west-1': {
                'HVM64': 'ami-b73d6cd7'
            },
            'us-west-2': {
                'HVM64': 'ami-1e299d7e'
            },
            'ca-central-1': {
                'HVM64': 'ami-eb20928f'
            },
            'eu-west-1': {
                'HVM64': 'ami-c51e3eb6'
            },
            'eu-west-2': {
                'HVM64': 'ami-bfe0eadb'
            },
            'eu-central-1': {
                'HVM64': 'ami-211ada4e'
            },
            'ap-southeast-1': {
                'HVM64': 'ami-4dd6782e'
            },
            'ap-southeast-2': {
                'HVM64': 'ami-28cff44b'
            },
            'ap-northeast-1': {
                'HVM64': 'ami-9f0c67f8'
            },
            'ap-northeast-2': {
                'HVM64': 'ami-94bb6dfa'
            },
            'ap-south-1': {
                'HVM64': 'ami-9fc7b0f0'
            },
            'sa-east-1': {
                'HVM64': 'ami-bb40d8d7'
            }
        })

    ### Resources ###

    # VPC
    vpc = mini_template.add_resource(
        VPC('VPC',
            CidrBlock='172.16.0.0/16',
            EnableDnsSupport='True',
            EnableDnsHostnames='True',
            Tags=Tags(Name=stack_name + '-vpc', Project=stack_name)))

    # Internet Gateway
    igw = mini_template.add_resource(
        InternetGateway('InternetGateway',
                        Tags=Tags(Name=stack_name + '-igw',
                                  Project=stack_name)))

    # Attach IGW to VPC
    attach_gateway = mini_template.add_resource(
        VPCGatewayAttachment('AttachGateway',
                             VpcId=Ref(vpc),
                             InternetGatewayId=Ref(igw)))

    # Route Table
    route_table = mini_template.add_resource(
        RouteTable('RouteTable',
                   VpcId=Ref(vpc),
                   Tags=Tags(Name=stack_name + '-routetable',
                             Project=stack_name)))

    # Route 0.0.0.0 -> IGW
    route01 = mini_template.add_resource(
        Route('Route',
              DependsOn='AttachGateway',
              GatewayId=Ref(igw),
              DestinationCidrBlock='0.0.0.0/0',
              RouteTableId=Ref(route_table)))

    # Subnet
    subnet = mini_template.add_resource(
        Subnet('Subnet',
               CidrBlock='172.16.10.0/24',
               VpcId=Ref(vpc),
               MapPublicIpOnLaunch='True',
               Tags=Tags(Name=stack_name + '-subnet', Project=stack_name)))

    # Subnet -> Route Table
    subnet_route_associate = mini_template.add_resource(
        SubnetRouteTableAssociation('SubnetRouteTableAssociation',
                                    SubnetId=Ref(subnet),
                                    RouteTableId=Ref(route_table)))

    # Security Group allowing access via SSH and HTTP
    web_security_group = mini_template.add_resource(
        SecurityGroup('WebSecurityGroup',
                      GroupDescription=
                      'Enable access to the web server on ports 80 and 22.',
                      VpcId=Ref(vpc),
                      Tags=Tags(Name=stack_name + '-securitygroup',
                                Project=stack_name),
                      SecurityGroupIngress=[
                          SecurityGroupRule(IpProtocol='tcp',
                                            FromPort='22',
                                            ToPort='22',
                                            CidrIp='0.0.0.0/0'),
                          SecurityGroupRule(IpProtocol='tcp',
                                            FromPort='80',
                                            ToPort='80',
                                            CidrIp='0.0.0.0/0')
                      ]))

    # Metadata to install Apache
    ec2_metadata = Metadata(
        Init({
            'config':
            InitConfig(
                packages={'yum': {
                    'httpd': []
                }},
                files=InitFiles({
                    '/var/www/html/index.html':
                    InitFile(
                        content=
                        '<html><body><h2>Automation for the People!</h2></body></html>',
                        mode='000644',
                        owner='root',
                        group='root')
                }),
                services={
                    'sysvinit':
                    InitServices({
                        'httpd':
                        InitService(enabled=True, ensureRunning=True)
                    })
                })
        }))

    # EC2 Instance
    ec2 = mini_template.add_resource(
        Instance('Ec2Instance',
                 ImageId=FindInMap('AWSRegionArch2AMI', Ref('AWS::Region'),
                                   'HVM64'),
                 Metadata=ec2_metadata,
                 InstanceType=Ref(instance_type),
                 KeyName=keyPair,
                 SecurityGroupIds=[
                     Ref(web_security_group),
                 ],
                 SubnetId=Ref(subnet),
                 Tags=Tags(Name=stack_name + '-ec2', Project=stack_name),
                 CreationPolicy=CreationPolicy(ResourceSignal=ResourceSignal(
                     Timeout='PT15M')),
                 UserData=Base64(
                     Join('', [
                         '#!/bin/bash -x\n',
                         'yum update -y\n',
                         'yum update -y aws-cfn-bootstrap\n',
                         '/opt/aws/bin/cfn-init -v ',
                         '         --stack ',
                         Ref('AWS::StackName'),
                         '         --resource Ec2Instance ',
                         '         --region ',
                         Ref('AWS::Region'),
                         '\n',
                         '/opt/aws/bin/cfn-signal -e $? ',
                         '         --stack ',
                         Ref('AWS::StackName'),
                         '         --resource Ec2Instance ',
                         '         --region ',
                         Ref('AWS::Region'),
                         '\n',
                     ]))))

    ### Outputs ###

    # Output the Public DNS address for the EC2 instance
    mini_template.add_output(
        Output('URL',
               Description='HTTP Server URL',
               Value=Join('',
                          ['http://',
                           GetAtt('Ec2Instance', 'PublicDnsName')])))

    print 'CloudFormation template build is completed.'
    return mini_template
Ejemplo n.º 4
0
def main():
    '''Function: Generates the Cloudformation template'''
    template = Template()

    keyname_param = template.add_parameter(
        Parameter(
            'KeyName',
            Description='Name of an existing EC2 KeyPair for SSH access',
            ConstraintDescription='must be the name of an existing EC2 KeyPair.',
            Type='AWS::EC2::KeyPair::KeyName',
        )
    )
    password_param = template.add_parameter(
        Parameter(
            'PassWord',
            Type='String',
            NoEcho=True,
            MinLength=8,
            MaxLength=64,
            Description='Password for the admin account',
            ConstraintDescription='A complex password at least eight chars long with alphanumeric characters, dashes and underscores.',
            AllowedPattern="[-_a-zA-Z0-9]*",
        )
    )

    ec2_security_group = template.add_resource(
        ec2.SecurityGroup(
            'SecurityGroup',
            GroupDescription='SSH, HTTP/HTTPS open for 0.0.0.0/0',
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(
                    IpProtocol='tcp',
                    FromPort='22',
                    ToPort='22',
                    CidrIp='0.0.0.0/0'),
                ec2.SecurityGroupRule(
                    IpProtocol='tcp',
                    FromPort='80',
                    ToPort='80',
                    CidrIp='0.0.0.0/0'),
            ],
        )
    )

    ec2_instance = template.add_resource(
        ec2.Instance(
            'Instance',
            Metadata=Metadata(
            Init({
                    "config": InitConfig(
                        files=InitFiles({
                            "/etc/nginx/conf.d/app.conf": InitFile(
                                content='server { listen 80 default_server; listen [::]:80  default_server; location / { proxy_pass http://localhost:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }',
                                mode="000644",
                                owner="root",
                                group="root"
                            )
                        }),
                    )
                }),
            ),
            CreationPolicy=CreationPolicy(
                ResourceSignal=ResourceSignal(
                Timeout='PT15M')),
            Tags=[{'Key':'Name', 'Value':'Simple Stack Instance {}'.format(time.strftime('%c'))},],
            ImageId='ami-39c28c41',
            InstanceType='t2.micro',
            KeyName=Ref(keyname_param),
            SecurityGroups=[Ref(ec2_security_group)],
            UserData=Base64(
                Join(
                    '',
                    [
                        '#!/bin/bash -x\n',
                        'exec > /tmp/user-data.log 2>&1\n'
                        'apt-get update\n',
			            'apt-get install -y python-pip\n',
			            'pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz\n',
                        'apt-get install -y nginx\n',
                        'apt-get install -y openjdk-8-jdk\n',
                        '/usr/local/bin/cfn-init --verbose --resource=Instance --region=', Ref('AWS::Region'), ' --stack=', Ref('AWS::StackName'), '\n',
                        'unlink /etc/nginx/sites-enabled/default\n'
                        'systemctl reload nginx\n',
                        '/usr/local/bin/cfn-signal -e 0 --resource Instance --region us-west-2 --stack simple\n',
                    ]
                )
            )
        )
    )

    template.add_output([
        Output(
            'PublicDnsName',
            Description='PublicDnsName',
            Value=GetAtt(ec2_instance, 'PublicDnsName'),
        ),
    ])

    print(template.to_yaml())
Ejemplo n.º 5
0
def main():
    '''Function: Generates the Cloudformation template'''
    template = Template()
    template.add_description("Dev Stack")

    keyname_param = template.add_parameter(
        Parameter(
            'KeyName',
            Description='An existing EC2 KeyPair.',
            ConstraintDescription='An existing EC2 KeyPair.',
            Type='AWS::EC2::KeyPair::KeyName',
        ))

    db_pass_param = template.add_parameter(
        Parameter(
            'DBPass',
            NoEcho=True,
            Type='String',
            Description='The database admin account password',
            ConstraintDescription='Must contain only alphanumeric characters',
            AllowedPattern="[-_a-zA-Z0-9]*",
        ))

    db_name_param = template.add_parameter(
        Parameter(
            'DBName',
            Default='miramax',
            Type='String',
            Description='The database name',
            ConstraintDescription=
            'Must begin with a letter and contain only alphanumeric characters',
            AllowedPattern="[-_a-zA-Z0-9]*",
        ))

    db_user_param = template.add_parameter(
        Parameter(
            'DBUser',
            Default='miramax',
            Type='String',
            Description='Username for MySQL database access',
            ConstraintDescription=
            'Must begin with a letter and contain only alphanumeric characters',
            AllowedPattern="[-_a-zA-Z0-9]*",
        ))

    template.add_mapping(
        'RegionMap', {
            'ap-south-1': {
                'ami': 'ami-ee8ea481'
            },
            'eu-west-3': {
                'ami': 'ami-daf040a7'
            },
            'eu-west-2': {
                'ami': 'ami-ddb950ba'
            },
            'eu-west-1': {
                'ami': 'ami-d2414e38'
            },
            'ap-northeast-2': {
                'ami': 'ami-65d86d0b'
            },
            'ap-northeast-1': {
                'ami': 'ami-e875a197'
            },
            'sa-east-1': {
                'ami': 'ami-ccd48ea0'
            },
            'ca-central-1': {
                'ami': 'ami-c3e567a7'
            },
            'ap-southeast-1': {
                'ami': 'ami-31e7e44d'
            },
            'ap-southeast-2': {
                'ami': 'ami-23c51c41'
            },
            'eu-central-1': {
                'ami': 'ami-3c635cd7'
            },
            'us-east-1': {
                'ami': 'ami-5cc39523'
            },
            'us-east-2': {
                'ami': 'ami-67142d02'
            },
            'us-west-1': {
                'ami': 'ami-d7b355b4'
            },
            'us-west-2': {
                'ami': 'ami-39c28c41'
            }
        })

    ec2_security_group = template.add_resource(
        ec2.SecurityGroup(
            'EC2SecurityGroup',
            Tags=[
                {
                    'Key': 'Name',
                    'Value': Ref('AWS::StackName')
                },
            ],
            GroupDescription='EC2 Security Group',
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(IpProtocol='tcp',
                                      FromPort='22',
                                      ToPort='22',
                                      CidrIp='0.0.0.0/0',
                                      Description='SSH'),
                ec2.SecurityGroupRule(IpProtocol='tcp',
                                      FromPort='80',
                                      ToPort='80',
                                      CidrIp='0.0.0.0/0',
                                      Description='HTTP'),
                ec2.SecurityGroupRule(IpProtocol='tcp',
                                      FromPort='443',
                                      ToPort='443',
                                      CidrIp='0.0.0.0/0',
                                      Description='HTTPS'),
            ],
        ))

    db_security_group = template.add_resource(
        ec2.SecurityGroup('DBSecurityGroup',
                          Tags=[
                              {
                                  'Key': 'Name',
                                  'Value': Ref('AWS::StackName')
                              },
                          ],
                          GroupDescription='DB Security Group',
                          SecurityGroupIngress=[
                              ec2.SecurityGroupRule(
                                  IpProtocol='tcp',
                                  FromPort='3306',
                                  ToPort='3306',
                                  SourceSecurityGroupId=GetAtt(
                                      ec2_security_group, "GroupId"),
                                  Description='MySQL'),
                          ]))
    ec2_instance = template.add_resource(
        ec2.Instance(
            'Instance',
            Metadata=Metadata(
                Init({
                    "config":
                    InitConfig(files=InitFiles({
                        "/tmp/instance.txt":
                        InitFile(content=Ref('AWS::StackName'),
                                 mode="000644",
                                 owner="root",
                                 group="root")
                    }), )
                }), ),
            CreationPolicy=CreationPolicy(ResourceSignal=ResourceSignal(
                Timeout='PT15M')),
            Tags=[
                {
                    'Key': 'Name',
                    'Value': Ref('AWS::StackName')
                },
            ],
            ImageId=FindInMap('RegionMap', Ref('AWS::Region'), 'ami'),
            InstanceType='t2.micro',
            KeyName=Ref(keyname_param),
            SecurityGroups=[Ref(ec2_security_group),
                            Ref(db_security_group)],
            DependsOn='Database',
            UserData=Base64(
                Join('', [
                    '#!/bin/bash -x\n',
                    'exec > /tmp/user-data.log 2>&1\n',
                    'unset UCF_FORCE_CONFFOLD\n',
                    'export UCF_FORCE_CONFFNEW=YES\n',
                    'ucf --purge /boot/grub/menu.lst\n',
                    'export DEBIAN_FRONTEND=noninteractive\n',
                    'apt-get update\n',
                    'apt-get -o Dpkg::Options::="--force-confnew" --force-yes -fuy upgrade\n',
                    'apt-get install -y python-pip apache2 libapache2-mod-wsgi\n',
                    'pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz\n',
                    '# Signal Cloudformation when set up is complete\n',
                    '/usr/local/bin/cfn-signal -e $? --resource=Instance --region=',
                    Ref('AWS::Region'),
                    ' --stack=',
                    Ref('AWS::StackName'),
                    '\n',
                ]))))

    ip_association = template.add_resource(
        ec2.EIPAssociation('IPAssociation',
                           InstanceId=Ref(ec2_instance),
                           AllocationId='eipalloc-aa755d96'))

    db_instance = template.add_resource(
        DBInstance(
            'Database',
            DBName=Ref(db_name_param),
            AllocatedStorage=20,
            DBInstanceClass='db.t2.micro',
            Engine='MySQL',
            EngineVersion='5.7.21',
            MasterUsername=Ref(db_user_param),
            MasterUserPassword=Ref(db_pass_param),
            VPCSecurityGroups=[GetAtt(db_security_group, "GroupId")],
        ))

    template.add_output([
        Output(
            'InstanceDnsName',
            Description='PublicDnsName',
            Value=GetAtt(ec2_instance, 'PublicDnsName'),
        ),
        Output(
            'DatabaseDnsName',
            Description='DBEndpoint',
            Value=GetAtt(db_instance, 'Endpoint.Address'),
        ),
    ])

    print(template.to_yaml())
Ejemplo n.º 6
0
def generate_template():

    template = Template()

    ref_stack_id = Ref('AWS::StackId')
    ref_region = Ref('AWS::Region')
    ref_stack_name = Ref('AWS::StackName')

    template.add_description(
        'Counter Strike Source Dedicated Server instances Stack implementing a linux '
        + 'server and installing the dedicated server on it')

    aws_access_key = template.add_parameter(
        Parameter('AWSAccessKey', Type='String', Description='AWS Access Key'))

    aws_secret_key = template.add_parameter(
        Parameter('AWSSecretKey', Type='String', Description='AWS Secret Key'))

    css_instance_name = template.add_parameter(
        Parameter('CSSInstanceName',
                  Default='css-server',
                  Type='String',
                  Description='The Name tag for the CSS Server instance.'))

    ami_id_linux = template.add_parameter(
        Parameter('AmiIdLinux',
                  Default='ami-82f4dae7',
                  Type='AWS::EC2::Image::Id',
                  Description='Instances in the DMZ will use this AMI.'))

    instance_type = template.add_parameter(
        Parameter(
            'InstanceType',
            Type='String',
            Description='Instances launched will use this EC2 Instance type.',
            AllowedValues=[
                't2.nano', 't2.micro', 't2.small', 't2.medium', 'c3.large',
                'c3.xlarge', 'c3.2xlarge', 'c4.large', 'c4.xlarge',
                'c4.2xlarge', 'm4.large'
            ],
            ConstraintDescription='must be a supported EC2 Instance type'))

    vpc_id = template.add_parameter(Parameter(
        'VPCId',
        Type='String',
    ))

    public_subnet = template.add_parameter(
        Parameter(
            'PublicSubnet1',
            Type='String',
        ))

    iam_role = template.add_parameter(
        Parameter('IAMRole',
                  Type='String',
                  Description='The IAM role associated with the instances.'))

    keyname = template.add_parameter(
        Parameter(
            'KeyName',
            Type='AWS::EC2::KeyPair::KeyName',
            Description=
            'Instances in the Auto Scaling Group will use this ssh key.'))

    css_init_config_script = template.add_parameter(
        Parameter("CSSInitConfigScript",
                  Type="String",
                  Description="File containing initial configuration script"))

    css_install_script = template.add_parameter(
        Parameter(
            "CSSInstallScript",
            Type="String",
            Description="File containing installation script for CSS server"))

    css_mods_tgz = template.add_parameter(
        Parameter("CSSModsTgz",
                  Type="String",
                  Description="File containing mods of the CSS server"))

    css_mapcycle_txt = template.add_parameter(
        Parameter("CSSMapcycleTxt",
                  Type="String",
                  Description="mapcycle.txt of the CSS server"))

    css_server_cfg = template.add_parameter(
        Parameter("CSSServerCfg",
                  Type="String",
                  Description="server.cfg of the CSS server"))

    css_rcon_password = template.add_parameter(
        Parameter("CSSRconPassword",
                  Type="String",
                  Description="RCON password of the CSS server"))

    bucket_name = template.add_parameter(
        Parameter("BucketName",
                  Type="String",
                  Description="Name of the S3 Bucket"))

    # Create Security Groups

    sshlocation_param = template.add_parameter(
        Parameter(
            'SSHLocation',
            Description=
            ' The IP address range that can be used to SSH to the EC2 instances',
            Type='String',
            MinLength='9',
            MaxLength='18',
            Default='0.0.0.0/0',
            AllowedPattern=
            "(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})",
            ConstraintDescription=(
                "must be a valid IP CIDR range of the form x.x.x.x/x."),
        ))

    public_security_group = template.add_resource(
        SecurityGroup(
            'PublicSecurityGroup',
            GroupDescription='Security group for instances in the DMZ',
            SecurityGroupIngress=[
                SecurityGroupRule(IpProtocol='icmp',
                                  FromPort='8',
                                  ToPort='-1',
                                  CidrIp='0.0.0.0/0'),
                SecurityGroupRule(IpProtocol='tcp',
                                  FromPort='22',
                                  ToPort='22',
                                  CidrIp=Ref(sshlocation_param)),
                SecurityGroupRule(IpProtocol='tcp',
                                  FromPort='1200',
                                  ToPort='1200',
                                  CidrIp='0.0.0.0/0'),
                SecurityGroupRule(IpProtocol='udp',
                                  FromPort='1200',
                                  ToPort='1200',
                                  CidrIp='0.0.0.0/0'),
                SecurityGroupRule(IpProtocol='udp',
                                  FromPort='27005',
                                  ToPort='27005',
                                  CidrIp='0.0.0.0/0'),
                SecurityGroupRule(IpProtocol='tcp',
                                  FromPort='27015',
                                  ToPort='27015',
                                  CidrIp='0.0.0.0/0'),
                SecurityGroupRule(IpProtocol='udp',
                                  FromPort='27015',
                                  ToPort='27015',
                                  CidrIp='0.0.0.0/0'),
                SecurityGroupRule(IpProtocol='udp',
                                  FromPort='27020',
                                  ToPort='27020',
                                  CidrIp='0.0.0.0/0'),
                SecurityGroupRule(IpProtocol='udp',
                                  FromPort='26901',
                                  ToPort='26901',
                                  CidrIp='0.0.0.0/0'),
                SecurityGroupRule(IpProtocol='icmpv6',
                                  FromPort='-1',
                                  ToPort='-1',
                                  CidrIpv6='::/0'),
                SecurityGroupRule(IpProtocol='tcp',
                                  FromPort='22',
                                  ToPort='22',
                                  CidrIpv6='::/0'),
                SecurityGroupRule(IpProtocol='tcp',
                                  FromPort='1200',
                                  ToPort='1200',
                                  CidrIpv6='::/0'),
                SecurityGroupRule(IpProtocol='udp',
                                  FromPort='1200',
                                  ToPort='1200',
                                  CidrIpv6='::/0'),
                SecurityGroupRule(IpProtocol='udp',
                                  FromPort='27005',
                                  ToPort='27005',
                                  CidrIpv6='::/0'),
                SecurityGroupRule(IpProtocol='tcp',
                                  FromPort='27015',
                                  ToPort='27015',
                                  CidrIpv6='::/0'),
                SecurityGroupRule(IpProtocol='udp',
                                  FromPort='27015',
                                  ToPort='27015',
                                  CidrIpv6='::/0'),
                SecurityGroupRule(IpProtocol='udp',
                                  FromPort='27020',
                                  ToPort='27020',
                                  CidrIpv6='::/0'),
                SecurityGroupRule(IpProtocol='udp',
                                  FromPort='26901',
                                  ToPort='26901',
                                  CidrIpv6='::/0')
            ],
            SecurityGroupEgress=[
                SecurityGroupRule(IpProtocol='icmp',
                                  FromPort='8',
                                  ToPort='-1',
                                  CidrIp='0.0.0.0/0'),
                SecurityGroupRule(IpProtocol='tcp',
                                  FromPort='80',
                                  ToPort='80',
                                  CidrIp='0.0.0.0/0'),
                SecurityGroupRule(IpProtocol='tcp',
                                  FromPort='443',
                                  ToPort='443',
                                  CidrIp='0.0.0.0/0'),
                SecurityGroupRule(IpProtocol='icmpv6',
                                  FromPort='-1',
                                  ToPort='-1',
                                  CidrIpv6='::/0'),
                SecurityGroupRule(IpProtocol='tcp',
                                  FromPort='80',
                                  ToPort='80',
                                  CidrIpv6='::/0'),
                SecurityGroupRule(IpProtocol='tcp',
                                  FromPort='443',
                                  ToPort='443',
                                  CidrIpv6='::/0')
            ],
            VpcId=Ref(vpc_id),
        ))

    # Create CSS Server instance in the public subnet
    css_server_instance = template.add_resource(
        Instance(
            'CSSServerInstance',
            ImageId=Ref(ami_id_linux),
            InstanceType=Ref(instance_type),
            KeyName=Ref(keyname),
            IamInstanceProfile=Ref(iam_role),
            NetworkInterfaces=[
                NetworkInterfaceProperty(GroupSet=[Ref(public_security_group)],
                                         AssociatePublicIpAddress='false',
                                         DeviceIndex='0',
                                         DeleteOnTermination='true',
                                         SubnetId=Ref(public_subnet))
            ],
            Tags=Tags(Name=Ref(css_instance_name), Application=ref_stack_id),
            UserData=Base64(
                Join('', [
                    '#!/bin/bash -xe\n',
                    'echo LC_ALL="en_US.UTF-8" >> /etc/environment\n',
                    'export LC_ALL="en_US.UTF-8"\n', 'apt-get update\n',
                    'apt-get -y install python-minimal\n',
                    'echo -e "import sys\nreload(sys)\nsys.setdefaultencoding(\'utf8\')" > /usr/local/lib/python2.7/dist-packages/setEncoding.py\n'
                    'echo PYTHONSTARTUP=/usr/local/lib/python2.7/dist-packages/setEncoding.py >> /etc/environment\n',
                    'export PYTHONSTARTUP=/usr/local/lib/python2.7/dist-packages/setEncoding.py\n',
                    'curl https://bootstrap.pypa.io/get-pip.py > /tmp/get-pip.py\n',
                    'python /tmp/get-pip.py\n',
                    'pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz\n',
                    '/usr/local/bin/cfn-init -v ', '         --stack ',
                    ref_stack_name, '         --resource CSSServerInstance ',
                    '         --region ', ref_region, '\n'
                ])),
            Metadata=Metadata(
                Authentication({
                    "S3AccessCreds":
                    AuthenticationBlock(type="S3",
                                        accessKeyId=Ref(aws_access_key),
                                        secretKey=Ref(aws_secret_key),
                                        buckets=Ref(bucket_name))
                }),
                Init({
                    "config":
                    InitConfig(
                        sources={
                            '/tmp/mods': Ref(css_mods_tgz),
                        },
                        files={
                            '/tmp/init-config.sh': {
                                'source': Ref(css_init_config_script),
                                'authentication': 'S3AccessCreds',
                                'mode': '000755',
                                'owner': 'root',
                                'group': 'root'
                            },
                            '/tmp/css-install-script.sh': {
                                'source': Ref(css_install_script),
                                'authentication': 'S3AccessCreds',
                                'mode': '000755',
                                'owner': 'root',
                                'group': 'root'
                            },
                            '/tmp/cfg/mapcycle.txt': {
                                'source': Ref(css_mapcycle_txt),
                                'authentication': 'S3AccessCreds'
                            },
                            '/tmp/cfg/server.cfg': {
                                'source': Ref(css_server_cfg),
                                'authentication': 'S3AccessCreds'
                            }
                        },
                        commands={
                            '1_run_init-config.sh': {
                                'command': '/tmp/init-config.sh',
                                'cwd': '~',
                                'env': {
                                    'RCON_PASSWORD': Ref(css_rcon_password)
                                }
                            }
                        },
                    )
                }))))

    css_server_instance_ip_address = template.add_resource(
        EIP('IPAddress', Domain='vpc', InstanceId=Ref(css_server_instance)))

    template.add_output(
        Output(
            'InstanceIp',
            Value=Ref(css_server_instance_ip_address),
            Description='Linux Instance IP',
        ))

    return template
Ejemplo n.º 7
0
def main():
    '''Function: Generates the Cloudformation template'''
    template = Template()
    template.set_description("Server Stack")

    keyname_param = template.add_parameter(
        Parameter(
            'KeyName',
            Description='An existing EC2 KeyPair.',
            ConstraintDescription='An existing EC2 KeyPair.',
            Type='AWS::EC2::KeyPair::KeyName',
        )
    )

    template.add_mapping('RegionMap', {'eu-north-1': {'ami': 'ami-a536bedb'}, 'ap-south-1': {'ami': 'ami-00b2a5e29f669c903'}, 'eu-west-3': {'ami': 'ami-0d8581d2794d7df68'}, 'eu-west-2': {'ami': 'ami-02369579484abae2e'}, 'eu-west-1': {'ami': 'ami-0c17a2bccea3e36f9'}, 'ap-northeast-2': {'ami': 'ami-05daa9d0230f30d79'}, 'ap-northeast-1': {'ami': 'ami-03a90fe15b63befea'}, 'sa-east-1': {'ami': 'ami-0c04bf4cfbf3e9dbe'}, 'ca-central-1': {'ami': 'ami-013d2a414e834a144'}, 'ap-southeast-1': {'ami': 'ami-07ed1f021e2eea7cb'}, 'ap-southeast-2': {'ami': 'ami-068e6346d66ed62c8'}, 'eu-central-1': {'ami': 'ami-00aa61be0e9a8f948'}, 'us-east-1': {'ami': 'ami-0dd925351e231e8c7'}, 'us-east-2': {'ami': 'ami-06cb7cbcc0e8e90e8'}, 'us-west-1': {'ami': 'ami-0d8e4e7b60cd5f225'}, 'us-west-2': {'ami': 'ami-06ad92f74f2c20787'}})

    ec2_security_group = template.add_resource(
        ec2.SecurityGroup(
            'EC2SecurityGroup',
            Tags=[{'Key':'Name', 'Value':Ref('AWS::StackName')},],
            GroupDescription='EC2 Security Group',
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(
                    IpProtocol='tcp',
                    FromPort='22',
                    ToPort='22',
                    CidrIp='0.0.0.0/0',
                    Description='SSH'),
                ec2.SecurityGroupRule(
                    IpProtocol='tcp',
                    FromPort='80',
                    ToPort='80',
                    CidrIp='0.0.0.0/0',
                    Description='HTTP'),
                ec2.SecurityGroupRule(
                    IpProtocol='tcp',
                    FromPort='443',
                    ToPort='443',
                    CidrIp='0.0.0.0/0',
                    Description='HTTPS'),
            ],
        )
    )

    ec2_instance = template.add_resource(
        ec2.Instance(
            'Instance',
            Metadata=Metadata(
                Init({
                    "config": InitConfig(
                        files=InitFiles({
                            "/tmp/instance.txt": InitFile(
                                content=Ref('AWS::StackName'),
                                mode="000644",
                                owner="root",
                                group="root"
                            )
                        }),
                    )
                }),
            ),
            CreationPolicy=CreationPolicy(
                ResourceSignal=ResourceSignal(Timeout='PT15M')
            ),
            Tags=[{'Key':'Name', 'Value':Ref('AWS::StackName')},],
            ImageId=FindInMap('RegionMap', Ref('AWS::Region'), 'ami'),
            InstanceType='t2.2xlarge',
            KeyName=Ref(keyname_param),
            SecurityGroups=[Ref(ec2_security_group)],
            UserData=Base64(
                Join(
                    '',
                    [
                        '#!/bin/bash -x\n',
                        'exec > /tmp/user-data.log 2>&1\n',
                        'unset UCF_FORCE_CONFFOLD\n',
                        'export UCF_FORCE_CONFFNEW=YES\n',
                        'ucf --purge /boot/grub/menu.lst\n',
                        'export DEBIAN_FRONTEND=noninteractive\n',
                        'apt-get update\n',
                        'apt-get -o Dpkg::Options::="--force-confnew" --force-yes -fuy upgrade\n',
           		'apt-get install -y python-pip\n',
			'pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz\n',
                        '# Signal Cloudformation when set up is complete\n',
                        '/usr/local/bin/cfn-signal -e $? --resource=Instance --region=', Ref('AWS::Region'), ' --stack=', Ref('AWS::StackName'), '\n',
                    ]
                )
            )
        )
    )

    template.add_resource(
        ec2.EIP(
            'ElasticIP',
            InstanceId=Ref(ec2_instance),
            Domain='vpc'
        )
    )

    template.add_output([
        Output(
            'InstanceDnsName',
            Description='PublicDnsName',
            Value=GetAtt(ec2_instance, 'PublicDnsName'),
        ),
    ])

    print(template.to_yaml())
Ejemplo n.º 8
0
    SecurityGroups=['ckan-bot'],
    UserData=Base64(netkan_userdata),
    # t3 instances are unlimited by default
    CreditSpecification=CreditSpecification(CPUCredits='standard'),
    Tags=[
        Tag(Key='Name', Value='NetKAN Indexer'),
        Tag(Key='Service', Value='Indexer'),
    ],
    Metadata=Metadata(
        Init({
            'config':
            InitConfig(
                files=InitFiles({
                    '/etc/cfn/cfn-hup.conf': cfn_hup,
                    '/etc/cfn/hooks.d/cfn-auto-reloader.conf': reloader,
                    '/etc/docker/daemon.json': docker,
                })),
            'services': {
                'sysvinit': {
                    'cfn': cfn_service,
                    'docker': docker_service,
                }
            },
        })),
    BlockDeviceMappings=[
        BlockDeviceMapping(DeviceName='/dev/xvdh',
                           Ebs=EBSBlockDevice(
                               VolumeSize='50',
                               VolumeType='standard',
                           ))
    ])
t.add_resource(netkan_instance)