Beispiel #1
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        ssm_ass = _ssm.CfnAssociation(
            self,
            'InventoryAssociation',
            name='AWS-GatherSoftwareInventory',
            #document_version="$DEFAULT",
            association_name='InventoryAssociation',
            apply_only_at_cron_interval=False,
            schedule_expression="rate(30 minutes)",
            #compliance_severity="CRITICAL",
            targets=[
                _ssm.CfnAssociation.TargetProperty(key='instanceids',
                                                   values=['*'])
            ],
        )
        ssm_ass.add_override('Properties.Parameters.applications', ['Enabled'])
        ssm_ass.add_override('Properties.Parameters.awsComponents',
                             ['Enabled'])
        ssm_ass.add_override('Properties.Parameters.billingInfo', ['Enabled'])
        ssm_ass.add_override('Properties.Parameters.customInventory',
                             ['Enabled'])
        ssm_ass.add_override('Properties.Parameters.files', [''])
        ssm_ass.add_override(
            'Properties.Parameters.instanceDetailedInformation', ['Enabled'])
        ssm_ass.add_override('Properties.Parameters.networkConfig',
                             ['Enabled'])
        ssm_ass.add_override('Properties.Parameters.services', ['Enabled'])
        ssm_ass.add_override('Properties.Parameters.windowsRegistry', [''])
        ssm_ass.add_override('Properties.Parameters.windowsRoles', ['Enabled'])
        ssm_ass.add_override('Properties.Parameters.windowsUpdates',
                             ['Enabled'])

        # Create association for Patch Baseline
        ssm_ass_patch = _ssm.CfnAssociation(
            self,
            'PatchScanAssociation',
            name='AWS-RunPatchBaseline',
            #document_version="1",  # there is a bug when creating resource with this arg, to avoid err on creation it should be commented
            association_name='PatchScanAssociation',
            apply_only_at_cron_interval=False,
            schedule_expression="rate(30 minutes)",
            #compliance_severity="HIGH",
            targets=[
                _ssm.CfnAssociation.TargetProperty(key='InstanceIds',
                                                   values=['*'])
            ],
            max_concurrency="1000",
            max_errors="1000")
        ssm_ass_patch.add_override('Properties.Parameters.Operation', ['Scan'])
        ssm_ass_patch.add_override('Properties.Parameters.RebootOption',
                                   ['NoReboot'])
Beispiel #2
0
  def __init__(self, scope:core.Construct, id:str, landing_zone:ILandingZone, **kwargs):
    """
    Configure Dns Resolver
    """
    super().__init__(scope,id, **kwargs)
    
    self.admin = 'admin'
    self.password = '******'
    self.mad = ds.CfnMicrosoftAD(self,'ActiveDirectory',
      name='virtual.world',
      password= self.password,
      short_name='virtualworld',
      enable_sso=False,
      edition= 'Standard',
      vpc_settings= ds.CfnMicrosoftAD.VpcSettingsProperty(
        vpc_id= landing_zone.vpc.vpc_id,
        subnet_ids= landing_zone.vpc.select_subnets(subnet_group_name='Hadoop').subnet_ids
      ))

    document_name='JoinDomain_'+self.mad.ref
    self.domain_join_document = ssm.CfnDocument(self,'JoinDomainDocument',
      name= document_name,
      content={
        "schemaVersion": "1.0",
        "description": "Domain Join {}".format(self.mad.ref),
        "runtimeConfig": {
          "aws:domainJoin": {
            "properties": {
              "directoryId": self.mad.ref,
              "directoryName": "virtual.world",
              "dnsIpAddresses": [ self.mad.attr_dns_ip_addresses ]
            }
          }
        }
      })

    self.association = ssm.CfnAssociation(self,'JoinTagAssociation',
      association_name='joindomain_by_tags_'+self.mad.ref,
      name= document_name,
      targets= [
        ssm.CfnAssociation.TargetProperty(
          key='tag:domain',
          values=[landing_zone.zone_name])
      ])

    self.association.add_depends_on(self.domain_join_document)
Beispiel #3
0
    def __init__(self, scope: core.Construct, id: str, mad: ad.CfnMicrosoftAD,
                 targets: List[str], **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        self.__mad = mad

        document_name = 'Join_HomeNet_Domain_' + self.mad.ref
        self.domain_join_document = ssm.CfnDocument(
            self,
            'JoinDomainDocument',
            name=document_name,
            content={
                "schemaVersion": "1.0",
                "description": "Domain Join {}".format(self.mad.ref),
                "runtimeConfig": {
                    "aws:domainJoin": {
                        "properties": {
                            "directoryId": self.mad.ref,
                            "directoryName": "virtual.world",
                            "dnsIpAddresses": self.mad.attr_dns_ip_addresses
                        }
                    }
                }
            })

        self.association = ssm.CfnAssociation(
            self,
            'JoinTagAssociation',
            association_name='joindomain_by_tags_' + self.mad.ref,
            name=document_name,
            targets=[
                ssm.CfnAssociation.TargetProperty(key='tag:domain',
                                                  values=targets)
            ])

        self.domain_join_document.add_depends_on(mad)
        self.association.add_depends_on(self.domain_join_document)
Beispiel #4
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Global variables to import cdk contexts from cdk.json
        _vpcID = self.node.try_get_context("VpcId")
        _sm_password = self.node.try_get_context("Secret_domain_password_arn")
        _dname = self.node.try_get_context("Domain_name")
        _subnet1 = self.node.try_get_context("Subnet1")
        _subnet2 = self.node.try_get_context("Subnet2")
        _sm_ec2keypair = self.node.try_get_context("Secret_keypair_arn")
        _ec2instance = self.node.try_get_context("Instance_type")

        # Import Vpc from the existing one in the AWS Account
        Vpc = _ec2.Vpc.from_lookup(self, "ImportVPC", vpc_id=_vpcID)
        Subnet1 = _ec2.Subnet.from_subnet_attributes(
            self,
            "subnetfromADManagedAD",
            subnet_id=_subnet1[0],
            availability_zone=_subnet1[1])

        # Import a Secret Manager Secret for Domain Password
        secret_adpassword = _sm.Secret.from_secret_arn(self,
                                                       "AdPasswordSecretStore",
                                                       secret_arn=_sm_password)

        #Import a Secret Manager Secre for EC2 KeyPair
        secret_ec2keypair = _sm.Secret.from_secret_arn(
            self, "ImportEC2KeyPairSecretStore", secret_arn=_sm_ec2keypair)

        # Create an AWS Managed AD Service in STANDARD Version
        ad = _ds.CfnMicrosoftAD(
            self,
            "ManagedAD",
            name=_dname,
            password=secret_adpassword.secret_value_from_json(
                "Key").to_string(),
            edition="Standard",
            vpc_settings={
                "vpcId": _vpcID,
                "subnetIds": [_subnet1[0], _subnet2[0]]
            })

        self.directory = ad

        # Create r53 hosted Zone for DNS DomainName
        hostedzone = _r53.HostedZone(self,
                                     "HostedZoneforAD",
                                     zone_name=_dname,
                                     vpcs=[Vpc])

        # Get the DNS IPs from AWS Managed AD
        targetip = _r53.RecordTarget(values=ad.attr_dns_ip_addresses)

        # Create A Record on Route 53 to point to AWS Managed AD IPs to later EC2 to join Domain
        r53Arecord = _r53.ARecord(self,
                                  "RecordAforAD",
                                  target=targetip,
                                  zone=hostedzone)

        # Create Policy to EC2JoinDomain Role
        ec2ssmpolicy = _iam.PolicyDocument(statements=[
            _iam.PolicyStatement(actions=[
                "ssm:DescribeAssociation", "ssm:GetDocument",
                "ssm:DescribeDocument", "ssm:GetManifest", "ssm:GetParameters",
                "ssm:ListAssociations", "ssm:ListInstanceAssociations",
                "ssm:UpdateAssociationStatus",
                "ssm:UpdateInstanceAssociationStatus",
                "ssm:UpdateInstanceInformation"
            ],
                                 resources=["*"]),
            _iam.PolicyStatement(actions=[
                "ssmmessages:CreateControlChannel",
                "ssmmessages:CreateDataChannel",
                "ssmmessages:OpenControlChannel", "ssmmessages:OpenDataChannel"
            ],
                                 resources=["*"]),
            _iam.PolicyStatement(actions=[
                "ec2messages:AcknowledgeMessage", "ec2messages:DeleteMessage",
                "ec2messages:FailMessage", "ec2messages:GetEndpoint",
                "ec2messages:GetMessages", "ec2messages:SendReply"
            ],
                                 resources=["*"]),
            _iam.PolicyStatement(actions=["ec2:DescribeInstanceStatus"],
                                 resources=["*"]),
            _iam.PolicyStatement(actions=["secretsmanager:GetSecretValue"],
                                 resources=["{}".format(_sm_password)])
        ])

        # Create role "EC2JoinDomain" to apply on Windows EC2JoinDomain (EC2)
        ssmrole = _iam.Role(
            self,
            "SSMRoleforEC2",
            assumed_by=_iam.ServicePrincipal('ec2.amazonaws.com'),
            inline_policies={"EC2SSMPolicy": ec2ssmpolicy},
            role_name="EC2JoinDomain")

        # Create Policy to workspaces_DefaultRole Role
        wsdefaultpolicy = _iam.PolicyDocument(statements=[
            _iam.PolicyStatement(actions=[
                "ec2:CreateNetworkInterface", "ec2:DeleteNetworkInterface",
                "ec2:DescribeNetworkInterfaces"
            ],
                                 resources=["*"]),
            _iam.PolicyStatement(actions=[
                "workspaces:RebootWorkspaces", "workspaces:RebuildWorkspaces",
                "workspaces:ModifyWorkspaceProperties"
            ],
                                 resources=["*"])
        ])

        # Create role workspaces_DefaultRole for later WorkSpaces API usage
        wsrole = _iam.Role(
            self,
            "WorkSpacesDefaultRole",
            assumed_by=_iam.ServicePrincipal('workspaces.amazonaws.com'),
            inline_policies={"WorkSpacesDefaultPolicy": wsdefaultpolicy},
            role_name="workspaces_DefaultRole")

        # Create a security group for RDP access on Windows EC2JoinDomain (EC2)
        rdpsg = _ec2.SecurityGroup(
            self,
            "SGForRDP",
            vpc=Vpc,
            description=
            "The Secrurity Group from local environment to Windows EC2 Instance"
        )

        rdpsg.add_ingress_rule(peer=_ec2.Peer.ipv4("192.168.1.1/32"),
                               connection=_ec2.Port.tcp(3389))

        # Create Windows EC2JoinDomain (EC2) as AD Admin server
        adadminEC2 = _ec2.Instance(
            self,
            "WindowsEC2",
            instance_type=_ec2.InstanceType(
                instance_type_identifier=_ec2instance),
            machine_image=_ec2.MachineImage.latest_windows(
                version=_ec2.WindowsVersion.
                WINDOWS_SERVER_2016_ENGLISH_FULL_BASE),
            vpc=Vpc,
            key_name=secret_ec2keypair.secret_value_from_json(
                "Key").to_string(),
            role=ssmrole,
            security_group=rdpsg,
            vpc_subnets=_ec2.SubnetSelection(subnets=[Subnet1]))

        adadminEC2.instance.add_depends_on(ad)

        # Create a SSM Parameter Store for Domain Name
        domain = _ssm.StringParameter(self,
                                      "ADDomainName",
                                      parameter_name="ad_join_domain_name",
                                      string_value=ad.name)

        # Create a SSM Parameter Store for Domain User
        aduser = _ssm.StringParameter(self,
                                      "ADDomainUser",
                                      parameter_name="ad_join_domain_user",
                                      string_value="Admin")

        domain.node.add_dependency(ad)
        aduser.node.add_dependency(ad)

        # Create SSM Document to join Window EC2 into AD
        ssmdocument = _ssm.CfnDocument(
            self,
            "SSMDocumentJoinAD",
            document_type="Command",
            name="SSMDocumentJoinAD",
            content={
                "description":
                "Run a PowerShell script to domain join a Windows instance securely",
                "schemaVersion":
                "2.0",
                "mainSteps": [{
                    "action": "aws:runPowerShellScript",
                    "name": "runPowerShellWithSecureString",
                    "inputs": {
                        "runCommand": [
                            "# Example PowerShell script to domain join a Windows instance securely",
                            "# Adopt the document from AWS Blog Join a Microsoft Active Directory Domain with Parameter Store and Amazon EC2 Systems Manager Documents",
                            "", "$ErrorActionPreference = 'Stop'", "", "try{",
                            "    # Parameter names",
                            "    # $dnsParameterStore = ([System.Net.Dns]::GetHostAddresses({}).IPAddressToString[0])"
                            .format(domain.parameter_name),
                            "    $domainNameParameterStore = \"{}\"".format(
                                domain.parameter_name),
                            "    $domainJoinUserNameParameterStore = \"{}\"".
                            format(aduser.parameter_name),
                            "    $domainJoinPasswordParameterStore = \"{}\"".
                            format(secret_adpassword.secret_arn), "",
                            "    # Retrieve configuration values from parameters",
                            "    $ipdns = ([System.Net.Dns]::GetHostAddresses(\"{}\").IPAddressToString[0])"
                            .format(_dname),
                            "    $domain = (Get-SSMParameterValue -Name $domainNameParameterStore).Parameters[0].Value",
                            "    $username = $domain + \"\\\" + (Get-SSMParameterValue -Name $domainJoinUserNameParameterStore).Parameters[0].Value",
                            "    $password = ((Get-SECSecretValue -SecretId $domainJoinPasswordParameterStore ).SecretString | ConvertFrom-Json ).Key | ConvertTo-SecureString -asPlainText -Force ",
                            "",
                            "    # Create a System.Management.Automation.PSCredential object",
                            "    $credential = New-Object System.Management.Automation.PSCredential($username, $password)",
                            "",
                            "    # Determine the name of the Network Adapter of this machine",
                            "    $networkAdapter = Get-WmiObject Win32_NetworkAdapter -Filter \"AdapterType = 'Ethernet 802.3'\"",
                            "    $networkAdapterName = ($networkAdapter | Select-Object -First 1).NetConnectionID",
                            "",
                            "    # Set up the IPv4 address of the AD DNS server as the first DNS server on this machine",
                            "    netsh.exe interface ipv4 add dnsservers name=$networkAdapterName address=$ipdns index=1",
                            "", "    # Join the domain and reboot",
                            "    Add-Computer -DomainName $domain -Credential $credential",
                            "    Restart-Computer -Force", "}",
                            "catch [Exception]{",
                            "    Write-Host $_.Exception.ToString()",
                            "    Write-Host 'Command execution failed.'",
                            "    $host.SetShouldExit(1)", "}"
                        ]
                    }
                }]
            })

        # Create SSM Associate to trigger SSM doucment to let Windows EC2JoinDomain (EC2) join Domain
        ssmjoinad = _ssm.CfnAssociation(self,
                                        "WindowJoinAD",
                                        name=ssmdocument.name,
                                        targets=[{
                                            "key":
                                            "InstanceIds",
                                            "values": [adadminEC2.instance_id]
                                        }])

        ssmjoinad.add_depends_on(ssmdocument)

        # Create a Policy for Lambda Role
        lambdapolicy = _iam.PolicyDocument(statements=[
            _iam.PolicyStatement(actions=["logs:CreateLogGroup"],
                                 resources=[
                                     "arn:aws:logs:{}:{}:*".format(
                                         self.region, self.account)
                                 ]),
            _iam.PolicyStatement(
                actions=["logs:CreateLogStream", "logs:PutLogEvents"],
                resources=[
                    "arn:aws:logs:{}:{}:log-group:/aws/lambda/*".format(
                        self.region, self.account)
                ]),
            _iam.PolicyStatement(actions=[
                "workspaces:RegisterWorkspaceDirectory",
                "workspaces:DeregisterWorkspaceDirectory",
                "ds:DescribeDirectories", "ds:AuthorizeApplication",
                "ds:UnauthorizeApplication", "iam:GetRole",
                "ec2:DescribeInternetGateways", "ec2:DescribeVpcs",
                "ec2:DescribeRouteTables", "ec2:DescribeSubnets",
                "ec2:DescribeNetworkInterfaces",
                "ec2:DescribeAvailabilityZones", "ec2:CreateSecurityGroup",
                "ec2:CreateTags"
            ],
                                 resources=["*"])
        ])

        # Creare a IAM Role for Lambda
        lambdarole = _iam.Role(
            self,
            "LambdaRoleForRegisterDS",
            assumed_by=_iam.ServicePrincipal('lambda.amazonaws.com'),
            inline_policies={"LambdaActicateDS": lambdapolicy},
            role_name="LambdaActivateDirectoryService")

        # Create a Lambda function to Register Directory Service on WorkSpaces
        dslambda = _lambda.Function(self,
                                    "LambdaStackForDSFunction",
                                    runtime=_lambda.Runtime.PYTHON_3_7,
                                    handler="workspaceds.handler",
                                    role=lambdarole,
                                    code=_lambda.Code.asset('lambda'),
                                    environment={"DIRECTORY_ID": ad.ref},
                                    timeout=core.Duration.seconds(120))
        # Create a customResource to trigger Lambda function after Lambda function is created
        _cf.CfnCustomResource(self,
                              "InvokeLambdaFunction",
                              service_token=dslambda.function_arn)
    def __init__(self, scope: core.Construct, id: str, vpc,
                 ec2_instance_type: str, es_endpoint_param_name: str,
                 es_region_param_name: str, stack_log_level: str,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Read BootStrap Script):
        try:
            with open(
                    "elastic_fluent_bit_kibana/stacks/back_end/bootstrap_scripts/deploy_app.sh",
                    encoding="utf-8",
                    mode="r") as f:
                user_data = f.read()
        except OSError as e:
            print("Unable to read UserData script")
            raise e

        # Get the latest AMI from AWS SSM
        linux_ami = _ec2.AmazonLinuxImage(
            generation=_ec2.AmazonLinuxGeneration.AMAZON_LINUX_2)

        # Get the latest ami
        amzn_linux_ami = _ec2.MachineImage.latest_amazon_linux(
            generation=_ec2.AmazonLinuxGeneration.AMAZON_LINUX_2)
        # ec2 Instance Role
        _instance_role = _iam.Role(
            self,
            "webAppClientRole",
            assumed_by=_iam.ServicePrincipal("ec2.amazonaws.com"),
            managed_policies=[
                _iam.ManagedPolicy.from_aws_managed_policy_name(
                    "AmazonSSMManagedInstanceCore")
            ])

        # Allow CW Agent to create Logs
        _instance_role.add_to_policy(
            _iam.PolicyStatement(actions=["logs:Create*", "logs:PutLogEvents"],
                                 resources=["arn:aws:logs:*:*:*"]))

        # Allow Access to ElasticSearch Domain
        # https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-ac.html#es-ac-types-resource
        _instance_role.add_to_policy(
            _iam.PolicyStatement(actions=[
                "es:Describe*",
                "es:List*",
                "es:ESHttpPost",
                "es:ESHttpPut",
            ],
                                 resources=["*"]))

        # fluent_bit_server Instance
        self.fluent_bit_server = _ec2.Instance(
            self,
            "fluentBitLogRouter",
            instance_type=_ec2.InstanceType(
                instance_type_identifier=f"{ec2_instance_type}"),
            instance_name="fluent_bit_log_router_01",
            machine_image=amzn_linux_ami,
            vpc=vpc,
            vpc_subnets=_ec2.SubnetSelection(
                subnet_type=_ec2.SubnetType.PUBLIC),
            role=_instance_role,
            user_data=_ec2.UserData.custom(user_data))

        # Allow Web Traffic to WebServer
        self.fluent_bit_server.connections.allow_from_any_ipv4(
            _ec2.Port.tcp(80), description="Allow Incoming HTTP Traffic")

        self.fluent_bit_server.connections.allow_from(
            other=_ec2.Peer.ipv4(vpc.vpc_cidr_block),
            port_range=_ec2.Port.tcp(443),
            description="Allow Incoming FluentBit Traffic")

        # Allow CW Agent to create Logs
        _instance_role.add_to_policy(
            _iam.PolicyStatement(actions=["logs:Create*", "logs:PutLogEvents"],
                                 resources=["arn:aws:logs:*:*:*"]))

        # Let us prepare our FluentBit Configuration Script

        # Use the script below, if you have a pre-written script, if not use the parts below to ASSEMBLE the script
        # Read BootStrap Script):
        try:
            with open(
                    "elastic_fluent_bit_kibana/stacks/back_end/bootstrap_scripts/configure_fluent_bit.sh",
                    encoding="utf-8",
                    mode="r") as f:
                bash_commands_to_run = f.read()
        except OSError as e:
            print("Unable to read bash commands file")
            raise e

        es_endpoint = _ssm.StringParameter.value_for_string_parameter(
            self, es_endpoint_param_name)
        es_region = _ssm.StringParameter.value_for_string_parameter(
            self, es_region_param_name)

        bash_commands_to_run_01 = """
#!/bin/bash
set -ex
set -o pipefail

# version: 22Nov2020

##################################################
#############     SET GLOBALS     ################
##################################################

REPO_NAME="elastic-fluent-bit-kibana"

GIT_REPO_URL="https://github.com/miztiik/$REPO_NAME.git"

APP_DIR="/var/$REPO_NAME"

LOG_FILE="/var/log/miztiik-automation-configure-fluent-bit.log"

function install_fluent_bit(){
# https://docs.fluentbit.io/manual/installation/linux/amazon-linux
cat > '/etc/yum.repos.d/td-agent-bit.repo' << "EOF"
[td-agent-bit]
name = TD Agent Bit
baseurl = https://packages.fluentbit.io/amazonlinux/2/$basearch/
gpgcheck=1
gpgkey=https://packages.fluentbit.io/fluentbit.key
enabled=1
EOF

# Install the agent
sudo yum -y install td-agent-bit
sudo service td-agent-bit start
service td-agent-bit status
}

function create_config_files(){
    mkdir -p ${APP_DIR}
    cd ${APP_DIR}

echo "
[INPUT]
    name            tail
    path            /var/log/httpd/*log
    tag             automate_log_parse
    Path_Key        filename
[FILTER]
    Name    record_modifier
    Match   *
    Record  hostname    ${HOSTNAME}
    Record  project     elastic-fluent-bit-kibana-demo
    Add     user        Mystique
" > ${APP_DIR}/es.conf
"""

        bash_commands_to_run_02 = f"""
echo "
[OUTPUT]
    Name            es
    Match           automate_log*
    Host            {es_endpoint}
    Port            443
    tls             On
    AWS_Auth        On
    AWS_Region      {es_region}
    Index           miztiik_automation
    Type            app_logs
    Include_Tag_Key On
" >> ${{APP_DIR}}/es.conf
}}
        """

        bash_commands_to_run_03 = """

function configure_fluent_bit(){
# Stop the agent
sudo service td-agent-bit stop

# DO NOT DO THIS IN ANY SERIOUS CONFIG FILE
# Null the defaults and start fresh
> /etc/td-agent-bit/td-agent-bit.conf

echo "
[SERVICE]
    Flush 3
@INCLUDE ${APP_DIR}/es.conf
" > /etc/td-agent-bit/td-agent-bit.conf

sudo service td-agent-bit start
sudo service td-agent-bit status
}

install_fluent_bit >> "${LOG_FILE}"
create_config_files >> "${LOG_FILE}"
configure_fluent_bit >> "${LOG_FILE}"
"""

        bash_commands_to_run = bash_commands_to_run_01 + \
            bash_commands_to_run_02 + bash_commands_to_run_03

        # Configure Fluent Bit using SSM Run Commands
        config_fluenbit_doc = CreateSsmRunCommandDocument(
            self,
            "configureFluentBitToEs",
            run_document_name="configureFluentBitToEs",
            _doc_desc="Bash script to configure FluentBit to send logs to ES",
            bash_commands_to_run=bash_commands_to_run,
            enable_log=False)

        # Create SSM Association to trigger SSM doucment to target (EC2)
        _run_commands_on_ec2 = _ssm.CfnAssociation(
            self,
            "runCommandsOnEc2",
            name=config_fluenbit_doc.get_ssm_linux_document_name,
            targets=[{
                "key": "InstanceIds",
                "values": [self.fluent_bit_server.instance_id]
            }])

        ###########################################
        ################# OUTPUTS #################
        ###########################################
        output_0 = core.CfnOutput(
            self,
            "AutomationFrom",
            value=f"{GlobalArgs.SOURCE_INFO}",
            description=
            "To know more about this automation stack, check out our github page."
        )
        output_1 = core.CfnOutput(
            self,
            "FluentBitPrivateIp",
            value=f"http://{self.fluent_bit_server.instance_private_ip}",
            description=f"Private IP of Fluent Bit Server on EC2")
        output_2 = core.CfnOutput(
            self,
            "FluentBitInstance",
            value=(f"https://console.aws.amazon.com/ec2/v2/home?region="
                   f"{core.Aws.REGION}"
                   f"#Instances:search="
                   f"{self.fluent_bit_server.instance_id}"
                   f";sort=instanceId"),
            description=
            f"Login to the instance using Systems Manager and use curl to access the Instance"
        )
        output_3 = core.CfnOutput(
            self,
            "AwsForFluentBit",
            value=
            (f"https://github.com/aws/aws-for-fluent-bit/tree/master/examples/fluent-bit/systems-manager-ec2"
             ),
            description=f"Amazon docs on fluent bit")

        output_4 = core.CfnOutput(
            self,
            "WebServerUrl",
            value=f"{self.fluent_bit_server.instance_public_dns_name}",
            description=f"Public IP of Web Server on EC2")
        output_5 = core.CfnOutput(
            self,
            "GenerateAccessTraffic",
            value=
            f"ab -n 10 -c 1 http://{self.fluent_bit_server.instance_public_dns_name}/",
            description=f"Public IP of Web Server on EC2")
        output_6 = core.CfnOutput(
            self,
            "GenerateFailedTraffic",
            value=
            f"ab -n 10 -c 1 http://{self.fluent_bit_server.instance_public_dns_name}/${{RANDOM}}",
            description=f"Public IP of Web Server on EC2")
Beispiel #6
0
    def __init__(self, scope: core.Construct, construct_id: str,
                 run_document_name: str, ec2_inst_id: str,
                 stack_log_level: str, **kwargs) -> None:

        super().__init__(scope, construct_id, **kwargs)

        # The code that defines your stack goes here
        # Read BootStrap Script):
        try:
            with open(
                    "elastic_fluent_bit_kibana/stacks/back_end/bootstrap_scripts/configure_fluent_bit.sh",
                    encoding="utf-8",
                    mode="r") as f:
                bash_commands_to_run = f.read()
        except OSError as e:
            print("Unable to read bash commands file")
            raise e

        # SSM Run Command Document should be JSON Syntax
        # Ref: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-document.html#cfn-ssm-document-content
        # Ref: https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_ssm/CfnDocument.html
        _run_cmds = {
            "schemaVersion":
            "2.2",
            "description":
            "Run script on Linux instances.",
            "parameters": {
                "commands": {
                    "type": "String",
                    "description":
                    "The commands to run or the path to an existing script on the instance.",
                    "default": f"{bash_commands_to_run}"
                }
            },
            "mainSteps": [{
                "action": "aws:runShellScript",
                "name": "runCommands",
                "inputs": {
                    "timeoutSeconds": "60",
                    "runCommand": ["{{ commands }}"]
                }
            }]
        }

        # Create Linux Shell Script Document
        ssm_linux_document = _ssm.CfnDocument(
            self,
            "ssmLinuxDocument",
            document_type="Command",
            # name=f"{run_document_name}",
            content=_run_cmds)

        # Create SSM Association to trigger SSM doucment to target (EC2)
        _run_commands_on_ec2 = _ssm.CfnAssociation(
            self,
            "runCommandsOnEc2",
            name=ssm_linux_document.name,
            targets=[{
                "key": "InstanceIds",
                "values": [ec2_inst_id]
            }])

        # As we are dealing with cloudformaiton resources, let us add a hard dependency
        _run_commands_on_ec2.add_depends_on(ssm_linux_document)

        ###########################################
        ################# OUTPUTS #################
        ###########################################
        output_0 = core.CfnOutput(
            self,
            "AutomationFrom",
            value=f"{GlobalArgs.SOURCE_INFO}",
            description=
            "To know more about this automation stack, check out our github page."
        )