コード例 #1
0
def create_launch_template_resource(template,
                                    api_launch_template_name_variable,
                                    api_instance_class_parameter,
                                    ec2_instance_profile_resource,
                                    api_security_group_resource,
                                    ecs_cluster_resource):
    return template.add_resource(
        ec2.LaunchTemplate(
            'LaunchTemplate',
            LaunchTemplateName=api_launch_template_name_variable,
            LaunchTemplateData=ec2.LaunchTemplateData(
                ImageId='ami-0ae254c8a2d3346a7',
                InstanceType=Ref(api_instance_class_parameter),
                IamInstanceProfile=ec2.IamInstanceProfile(
                    Arn=GetAtt(ec2_instance_profile_resource, 'Arn')),
                InstanceInitiatedShutdownBehavior='terminate',
                Monitoring=ec2.Monitoring(Enabled=True),
                SecurityGroups=[Ref(api_security_group_resource)],
                BlockDeviceMappings=[
                    ec2.BlockDeviceMapping(DeviceName='/dev/xvdcz',
                                           Ebs=ec2.EBSBlockDevice(
                                               DeleteOnTermination=True,
                                               VolumeSize=22,
                                               VolumeType='gp2'))
                ],
                UserData=Base64(
                    Join('', [
                        '#!/bin/bash\n', 'echo ECS_CLUSTER=',
                        Ref(ecs_cluster_resource),
                        ' >> /etc/ecs/ecs.config;echo ECS_BACKEND_HOST= >> /etc/ecs/ecs.config;'
                    ])))))
コード例 #2
0
ファイル: cloudformation.py プロジェクト: BookATest/api
 ec2.LaunchTemplate(
     'LaunchTemplate',
     LaunchTemplateName=Ref(api_launch_template_name),
     LaunchTemplateData=ec2.LaunchTemplateData(
         ImageId='ami-066826c6a40879d75',
         InstanceType=Ref(api_instance_class),
         IamInstanceProfile=ec2.IamInstanceProfile(
             Arn=GetAtt(ec2_instance_profile, 'Arn')
         ),
         InstanceInitiatedShutdownBehavior='terminate',
         Monitoring=ec2.Monitoring(Enabled=True),
         SecurityGroups=[Ref(api_security_group)],
         BlockDeviceMappings=[
             ec2.BlockDeviceMapping(
                 DeviceName='/dev/xvdcz',
                 Ebs=ec2.EBSBlockDevice(
                     DeleteOnTermination=True,
                     VolumeSize=22,
                     VolumeType='gp2'
                 )
             )
         ],
         UserData=Base64(
             Join('', [
                 '#!/bin/bash\n',
                 'echo ECS_CLUSTER=',
                 Ref(ecs_cluster),
                 ' >> /etc/ecs/ecs.config;echo ECS_BACKEND_HOST= >> /etc/ecs/ecs.config;'
             ])
         )
     )
 )
コード例 #3
0
ファイル: autoscaling.py プロジェクト: mello7tre/AwsIBox
def AS_LaunchTemplate():
    cfg.use_cfn_init = True
    InitConfigSets = ASInitConfigSets()

    CfmInitArgs = {}
    IBoxEnvApp = []
    Tags_List = []
    UserDataApp = []

    for n in cfg.Apps:
        name = f"Apps{n}"  # Ex. Apps1
        envname = f"EnvApp{n}Version"  # Ex EnvApp1Version
        reponame = f"{name}RepoName"  # Ex Apps1RepoName

        UserDataApp.extend(["#${%s}\n" % envname])

        p_EnvAppVersion = Parameter(
            envname,
            Description=f"Application {n} version",
            AllowedPattern="^[a-zA-Z0-9-_.]*$",
        )

        p_AppsRepoName = Parameter(
            reponame,
            Description=f"App {n} Repo Name - empty for default based on env/role",
            AllowedPattern="^[a-zA-Z0-9-_.]*$",
        )

        # parameters
        add_obj(
            [
                p_EnvAppVersion,
                p_AppsRepoName,
            ]
        )

        # conditions
        add_obj(
            {
                name: And(
                    Not(Equals(Ref(envname), "")),
                    Not(get_condition("", "equals", "None", reponame)),
                )
            }
        )

        InitConfigApps = ASInitConfigApps(name)
        CfmInitArgs[name] = InitConfigApps

        InitConfigAppsBuilAmi = ASInitConfigAppsBuildAmi(name)
        # AUTOSPOT - Let cfn-init always prepare instances on boot
        # CfmInitArgs[name + 'BuildAmi'] = InitConfigAppsBuilAmi
        CfmInitArgs[name] = InitConfigAppsBuilAmi

        IBoxEnvApp.extend(
            [
                f"export EnvApp{n}Version=",
                Ref(envname),
                "\n",
                f"export EnvRepo{n}Name=",
                get_endvalue(reponame),
                "\n",
            ]
        )

        InitConfigSetsApp = If(name, name, Ref("AWS::NoValue"))
        InitConfigSetsAppBuilAmi = If(name, f"{name}BuildAmi", Ref("AWS::NoValue"))
        IndexSERVICES = InitConfigSets.data["default"].index("SERVICES")
        InitConfigSets.data["default"].insert(IndexSERVICES, InitConfigSetsApp)
        # AUTOSPOT - Let cfn-init always prepare instances on boot
        # InitConfigSets.data['buildamifull'].append(
        #    InitConfigSetsAppBuilAmi)
        InitConfigSets.data["buildamifull"].append(InitConfigSetsApp)

        Tags_List.append(asg.Tag(envname, Ref(envname), True))

        # outputs
        Output_app = Output(envname, Value=Ref(envname))
        Output_repo = Output(reponame, Value=get_endvalue(reponame))

        add_obj([Output_app, Output_repo])

    InitConfigSetup = ASInitConfigSetup()
    InitConfigSetup.ibox_env_app = IBoxEnvApp
    InitConfigSetup.setup()

    InitConfigCodeDeploy = ASInitConfigCodeDeploy()

    CfmInitArgs["SETUP"] = InitConfigSetup
    CfmInitArgs["CWAGENT"] = ASInitConfigCloudWatchAgent("")

    if cfg.CodeDeploy:
        CfmInitArgs["CODEDEPLOY"] = InitConfigCodeDeploy

    if not getattr(cfg, "IBOX_LAUNCH_TEMPLATE_NO_WAIT_ELB_HEALTH", False):
        for lb in cfg.LoadBalancer:
            # LoadBalancerClassic
            if cfg.LoadBalancerType == "Classic":
                InitConfigELB = ASInitConfigELBClassic(scheme=lb)
                CfmInitArgs["ELBWAITER"] = InitConfigELB

            # LoadBalancerApplication
            if cfg.LoadBalancerType == "Application":
                InitConfigELB = ASInitConfigELBApplication(scheme=lb)
                CfmInitArgs["ELBWAITER"] = InitConfigELB

            # LoadBalancerNetwork
            if cfg.LoadBalancerType == "Network":
                for k in cfg.Listeners:
                    InitConfigELB = ASInitConfigELBApplication(
                        scheme=f"TargetGroupListeners{k}{lb}"
                    )
                    CfmInitArgs["ELBWAITER"] = InitConfigELB

    if getattr(cfg, "IBOX_LAUNCH_TEMPLATE_NO_SG_EXTRA", False):
        SecurityGroups = []
    else:
        SecurityGroups = cfg.SecurityGroupsImport

    # Resources
    R_LaunchTemplate = ec2.LaunchTemplate(
        "LaunchTemplate",
        LaunchTemplateName=Sub("${AWS::StackName}-${EnvRole}"),
        LaunchTemplateData=ASLaunchTemplateData(
            "LaunchTemplateData", UserDataApp=UserDataApp
        ),
    )
    R_LaunchTemplate.LaunchTemplateData.NetworkInterfaces[0].Groups.extend(
        SecurityGroups
    )

    # Import role specific cfn definition
    try:
        # Do not use role but direct cfg yaml configuration (ecs + cluster)
        cfn_envrole = f"cfn_{cfg.IBOX_ROLE_EX}"
    except Exception:
        cfn_envrole = f"cfn_{cfg.envrole}"
    cfn_envrole = cfn_envrole.replace("-", "_")
    if cfn_envrole in globals():  # Ex cfn_client_portal
        CfnRole = globals()[cfn_envrole]()
        CfmInitArgs.update(CfnRole)

    if cfg.use_cfn_init:
        R_LaunchTemplate.Metadata = cfm.Metadata(
            {
                "CloudFormationInitVersion": If(
                    "CloudFormationInit",
                    Ref("EnvStackVersion"),
                    Ref("AWS::NoValue"),
                )
            },
            cfm.Init(InitConfigSets, **CfmInitArgs),
            cfm.Authentication(
                {
                    "CfnS3Auth": cfm.AuthenticationBlock(
                        type="S3",
                        buckets=[
                            Sub(cfg.BucketNameAppRepository),
                            Sub(cfg.BucketNameAppData),
                        ],
                        roleName=Ref("RoleInstance"),
                    )
                }
            ),
        )

    add_obj(R_LaunchTemplate)

    Tags = asg.Tags()
    Tags.tags = Tags_List
    return Tags
コード例 #4
0
ファイル: ac3.py プロジェクト: ghac3/cfwp
lc = template.add_resource(
    ec2.LaunchTemplate(
        "WordPressAsgLaunchTemplate",
        LaunchTemplateName='WordPressAsgLaunchTemplate',
        LaunchTemplateData=ec2.LaunchTemplateData(
            NetworkInterfaces=[
                ec2.NetworkInterfaces(DeviceIndex=0,
                                      Groups=[Ref(wpsg)],
                                      AssociatePublicIpAddress=True)
            ],
            Monitoring=ec2.Monitoring(Enabled=True),
            ImageId=Ref('pWordpressAmi'),
            KeyName=Ref('pSshKeyPair'),
            UserData=Base64(
                Join('', [
                    Sub(startup_script),
                    "sed -i 's@database_name_here@",
                    Ref('pDBName'),
                    "@' wp-config.php\n",
                    "sed -i 's@username_here@root@' wp-config.php\n",
                    "sed -i 's@password_here@oolohl1shih0Fie7Sodu@' wp-config.php\n",
                    "sed -i 's@localhost@",
                    GetAtt('WordPressRDS', 'Endpoint.Address'),
                    "@' wp-config.php\n",
                    "systemctl restart nginx\n",
                    "systemctl restart php7.2-fpm\n",
                ])),
            InstanceType=Ref('pAsgInstanceType'),
            CreditSpecification=ec2.LaunchTemplateCreditSpecification(
                CpuCredits='unlimited', ))))