Esempio n. 1
0
    def create_template(self):
        """Create template (main function called by Stacker)."""
        template = self.template
        template.add_version('2010-09-09')
        template.add_description('just a template')

        template.add_resource(cfn.WaitConditionHandle('FakeResource'))
Esempio n. 2
0
    def test_ref_hash(self):
        s = hash("AWS::NoValue")
        r = hash(Ref("AWS::NoValue"))

        wch = cloudformation.WaitConditionHandle("TestResource")

        self.assertEqual(s, r)
        self.assertEqual(s, hash(NoValue))
        self.assertEqual(r, hash(NoValue))
        self.assertEqual(hash(wch.Ref()), hash("TestResource"))

        self.assertNotEqual(r, hash("AWS::Region"))
        self.assertNotEqual(r, hash(Region))
        self.assertNotEqual(r, hash(Ref))
        self.assertNotEqual(hash(wch.Ref()), hash("NonexistantResource"))
Esempio n. 3
0
    def test_ref_eq(self):
        s = "AWS::NoValue"
        r = Ref(s)

        wch = cloudformation.WaitConditionHandle("TestResource")

        self.assertEqual(s, r)
        self.assertEqual(s, NoValue)
        self.assertEqual(r, NoValue)
        self.assertEqual(wch.Ref(), "TestResource")

        self.assertNotEqual(r, "AWS::Region")
        self.assertNotEqual(r, Region)
        self.assertNotEqual(r, Ref)
        self.assertNotEqual(wch.Ref(), "NonexistantResource")
Esempio n. 4
0
def _wait_condition(
    type_name: str, base_name: str
) -> (cloudformation.WaitCondition, cloudformation.WaitConditionHandle):
    """Construct a wait condition and handle.

    :param type_name:
    :param base_name:
    :return:
    """
    handle = cloudformation.WaitConditionHandle(
        VALUE_SEPARATOR.join(("Upload", type_name, base_name)))
    condition = cloudformation.WaitCondition(VALUE_SEPARATOR.join(
        ("WaitFor", handle.title)),
                                             Handle=handle.ref(),
                                             Count=1,
                                             Timeout=3600)
    return condition, handle
Esempio n. 5
0
    def add_resources(self):

        metadata = {
            "AWS::CloudFormation::Init": {
                "configSets": {
                    "wordpress_install": [
                        "install_wordpress"]
                },
                "install_wordpress": {
                    "packages": {
                        "apt": {
                            "apache2": [],
                            "php": [],
                            "php-mysql": [],
                            "php7.0": [],
                            "php7.0-mysql": [],
                            "libapache2-mod-php7.0": [],
                            "php7.0-cli": [],
                            "php7.0-cgi": [],
                            "php7.0-gd": [],
                            "mysql-client": [],
                            "sendmail": []
                        }
                    },
                    "sources": {
                        "/var/www/html": "http://wordpress.org/latest.tar.gz"
                    },
                    "files": {
                        "/tmp/create-wp-config": {
                            "content": {
                                "Fn::Join": ["", [
                                    "#!/bin/bash\n",
                                    "cp /var/www/html/wordpress/wp-config-sample.php /var/www/html/wordpress/wp-config.php\n",
                                    "sed -i \"s/'database_name_here'/'", Ref(
                                        self.DBName), "'/g\" wp-config.php\n",
                                    "sed -i \"s/'username_here'/'", Ref(
                                        self.DBUser), "'/g\" wp-config.php\n",
                                    "sed -i \"s/'password_here'/'", Ref(
                                        self.DBPass), "'/g\" wp-config.php\n",
                                    "sed -i \"s/'localhost'/'", Ref(
                                        self.RDSEndpoint), "'/g\" wp-config.php\n"
                                ]]
                            },
                            "mode": "000500",
                            "owner": "root",
                            "group": "root"
                        }
                    },
                    "commands": {
                        "01_configure_wordpress": {
                            "command": "/tmp/create-wp-config",
                            "cwd": "/var/www/html/wordpress"
                        }
                    }
                }
            }
        }

        self.WaitHandle = self.template.add_resource(cloudformation.WaitConditionHandle(
            "WaitHandle",
        ))

        self.WaitCondition = self.template.add_resource(cloudformation.WaitCondition(
            "WaitCondition",
            Handle=Ref(self.WaitHandle),
            Timeout="600",
            DependsOn="WebServerAutoScalingGroup",
        ))

        self.WebServerLaunchConfiguration = self.template.add_resource(autoscaling.LaunchConfiguration(
            "WebServerLaunchConfiguration",
            Metadata=metadata,
            UserData=Base64(Join("", [
                "#!/bin/bash -x\n",
                "apt-get update\n",
                "apt-get install python-pip nfs-common -y \n",
                "mkdir -p /var/www/html/\n",
                "EC2_AZ=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)\n",
                "echo \"$EC2_AZ.", Ref(self.FileSystemID), ".efs.", Ref(
                    "AWS::Region"), ".amazonaws.com:/ /var/www/html/ nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 0 0\" >> /etc/fstab\n"
                "mount -a\n",
                "pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz\n",

                # "exec > /tmp/userdata.log 2>&1\n",
                "/usr/local/bin/cfn-init -v  --stack ", Ref("AWS::StackName"),
                "         --resource WebServerLaunchConfiguration ",
                "         --configsets wordpress_install ",
                "         --region ", Ref("AWS::Region"),
                "\n",
                "/bin/mv /var/www/html/wordpress/* /var/www/html/\n",
                "/bin/rm -f /var/www/html/index.html\n",
                "/bin/rm -rf /var/www/html/wordpress/\n",
                "chown www-data:www-data /var/www/html/* -R\n",
                "/usr/sbin/service apache2 restart\n",
                "/usr/bin/curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar\n",
                "/bin/chmod +x wp-cli.phar\n",
                "/bin/mv wp-cli.phar /usr/local/bin/wp\n",
                "cd /var/www/html/\n",
                "if ! $(sudo -u www-data /usr/local/bin/wp core is-installed); then\n",
                "sudo -u www-data /usr/local/bin/wp core install ",
                "--url='", Ref(self.Hostname), ".", Ref(self.Domain), "' ",
                "--title='Cloudreach Meetup - ", Ref(
                    self.Environment), "' ",
                "--admin_user='******' ",
                "--admin_password='******' ",
                "--admin_email='*****@*****.**'\n",
                "wget  https://s3-eu-west-1.amazonaws.com/sceptre-meetup-munich/header.jpg -O /var/www/html/wp-content/themes/twentyseventeen/assets/images/header.jpg\n",
                "chown www-data:www-data /var/www/html/wp-content/themes/twentyseventeen/assets/images/header.jpg\n",

                "fi\n",

                "/usr/local/bin/cfn-signal -e $? --stack ", Ref(
                    "AWS::StackName"), "   -r \"Webserver setup complete\" '", Ref(self.WaitHandle), "'\n"

            ]
            )),
            ImageId=FindInMap("AWSRegion2AMI", Ref("AWS::Region"), "AMI"),
            KeyName=Ref(self.KeyName),
            SecurityGroups=[Ref(self.WebSecurityGroup)],
            InstanceType=Ref(self.InstanceType),
            AssociatePublicIpAddress=True,
        ))

        self.WebServerAutoScalingGroup = self.template.add_resource(autoscaling.AutoScalingGroup(
            "WebServerAutoScalingGroup",
            MinSize=Ref(self.WebServerCapacity),
            DesiredCapacity=Ref(self.WebServerCapacity),
            MaxSize=Ref(self.WebServerCapacity),
            VPCZoneIdentifier=[Ref(self.Subnet1), Ref(self.Subnet2)],
            AvailabilityZones=[Ref(self.AvailabilityZone1),
                               Ref(self.AvailabilityZone2)],
            Tags=autoscaling.Tags(
                Name=Join("-", [Ref(self.Project), "web", "asg"]),
                Environment=Ref(self.Environment),
                Project=Ref(self.Project),
            ),
            LoadBalancerNames=[Ref(self.ElasticLoadBalancer)],
            LaunchConfigurationName=Ref(self.WebServerLaunchConfiguration),
        ))

        self.WebServerScaleUpPolicy = self.template.add_resource(autoscaling.ScalingPolicy(
            "WebServerScaleUpPolicy",
            ScalingAdjustment="1",
            Cooldown="60",
            AutoScalingGroupName=Ref(self.WebServerAutoScalingGroup),
            AdjustmentType="ChangeInCapacity",
        ))

        self.WebServerScaleDownPolicy = self.template.add_resource(autoscaling.ScalingPolicy(
            "WebServerScaleDownPolicy",
            ScalingAdjustment="-1",
            Cooldown="60",
            AutoScalingGroupName=Ref(self.WebServerAutoScalingGroup),
            AdjustmentType="ChangeInCapacity",
        ))

        self.CPUAlarmLow = self.template.add_resource(cloudwatch.Alarm(
            "CPUAlarmLow",
            EvaluationPeriods="2",
            Dimensions=[
                cloudwatch.MetricDimension(
                    Name="AutoScalingGroupName",
                    Value=Ref(self.WebServerAutoScalingGroup)
                ),
            ],
            AlarmActions=[Ref(self.WebServerScaleDownPolicy)],
            AlarmDescription="Scale-down if CPU < 70% for 1 minute",
            Namespace="AWS/EC2",
            Period="60",
            ComparisonOperator="LessThanThreshold",
            Statistic="Average",
            Threshold="70",
            MetricName="CPUUtilization",
        ))

        self.CPUAlarmHigh = self.template.add_resource(cloudwatch.Alarm(
            "CPUAlarmHigh",
            EvaluationPeriods="2",
            Dimensions=[
                cloudwatch.MetricDimension(
                    Name="AutoScalingGroupName",
                    Value=Ref("WebServerAutoScalingGroup")
                ),
            ],
            AlarmActions=[Ref(self.WebServerScaleUpPolicy)],
            AlarmDescription="Scale-up if CPU > 50% for 1 minute",
            Namespace="AWS/EC2",
            Period="60",
            ComparisonOperator="GreaterThanThreshold",
            Statistic="Average",
            Threshold="50",
            MetricName="CPUUtilization",
        ))
Esempio n. 6
0
    "/health-check",
    [Ref("PublicSecurityGroup")]
)

InternalMembraneDNSRecord = t.add_resource(route53.RecordSetType(
    "InternalMembraneDNSRecord",
    HostedZoneName=Join("", cell_domain() + ["."]),
    Comment="CNAME redirect to internal membrane elb",
    Name=Join("", ["*", "."] + cell_domain()),
    Type="CNAME",
    TTL="900",
    ResourceRecords=[GetAtt("IGatewayElb", "DNSName")],
    DependsOn=["IGatewayElb", "HostedZone"]
))

WaitHandle = t.add_resource(cfn.WaitConditionHandle("WaitHandle",))

def create_cellos_substack(t, name=None, role=None, cell_modules=None, tags=[],
                           security_groups=[], load_balancers=[],
                           instance_profile=None, instance_type=None,
                           subnet=Ref(private_subnet),
                           associate_public_ip=False):
    params = {
        "Role": role,
        "Tags": tags,
        "CellModules": cell_modules,
        "SecurityGroups": Join(",", security_groups),
        "LoadBalancerNames": Join(",", load_balancers),
        "ZookeeperElb": GetAtt("ZookeeperElb", "DNSName"),
        "MarathonElb": GetAtt("MarathonElb", "DNSName"),
        "MesosElb": GetAtt("MesosElb", "DNSName"),
Esempio n. 7
0
def update_dummy_wch(template):
    template.add_resource(
        cloudformation.WaitConditionHandle(str(uuid4()).replace("-", "")))
Esempio n. 8
0
from troposphere import Template, cloudformation, route53, Output, Export, Sub, Parameter, Ref, GetAtt, Join
from uuid import uuid4

t = Template()

# def update_dummy_wch(template):
#     template.add_resource(cloudformation.WaitConditionHandle(
#         str(uuid4()).replace("-", "")
#     ))
#
#
# update_dummy_wch(t)

dummy_type_parameter = t.add_parameter(
    Parameter("DummyTypeParameter",
              Type="String",
              Description="Parameter from config.json init file.",
              Default=""))

dummy_resource = t.add_resource(
    cloudformation.WaitConditionHandle(str(uuid4()).replace("-", "")))

t.add_output(
    Output(
        "DummyResourceOutput",
        Description="Dummy resource name",
        Value=Ref(dummy_resource),
    ))

print(t.to_json())