def __init__(self,
                 name: str,
                 content_dir: str,
                 index_document: str,
                 error_document: str,
                 opts: pulumi.ResourceOptions = None):

        super().__init__('StaticWebSite', name, None, opts)

        self.name = name

        # Create the S3 bucket
        self.s3_bucket = s3.Bucket(name,
                                   website={
                                       'index_document': index_document,
                                       'error_document': error_document
                                   })
        bucket_name = self.s3_bucket.id

        # Copy website content files to the newly created S3 bucket
        for file in os.listdir(content_dir):
            filepath = os.path.join(content_dir, file)
            mime_type, _ = mimetypes.guess_type(filepath)
            s3.BucketObject(file,
                            bucket=bucket_name,
                            source=FileAsset(filepath),
                            content_type=mime_type)

        # Set bucket policy to enable read access for all users
        s3.BucketPolicy("bucket-policy",
                        bucket=bucket_name,
                        policy=bucket_name.apply(public_read_policy_for_bucket))

        super().register_outputs({})
예제 #2
0
def bucket_object_converter(filepath):
    """
    Takes a file path and returns an bucket object managed by Pulumi
    """
    relative_path = filepath.replace(web_contents_root_path + '/', '')
    # Determine the mimetype using the `mimetypes` module.
    mime_type, _ = mimetypes.guess_type(filepath)
    content_file = pulumi_aws.s3.BucketObject(
        relative_path,
        key=relative_path,
        acl='public-read',
        bucket=content_bucket,
        content_type=mime_type,
        source=FileAsset(filepath),
        opts=ResourceOptions(parent=content_bucket))
BucketObject(
    resource_name="airflow-requirements",
    opts=ResourceOptions(parent=bucket),
    bucket=bucket.id,
    content=content,
    key="requirements.txt",
    server_side_encryption="AES256",
)

BucketObject(
    resource_name="airflow-dag",
    opts=ResourceOptions(parent=bucket),
    bucket=bucket.id,
    key="dags/dag.py",
    server_side_encryption="AES256",
    source=FileAsset(path="./dag.py"),
)


def prepare_kube_config(kube_config: str) -> str:
    kube_config["users"][0]["user"]["exec"][
        "command"] = "/usr/local/airflow/.local/bin/aws"
    return json.dumps(kube_config, indent=4)


BucketObject(
    resource_name="airflow-kube-config",
    opts=ResourceOptions(parent=bucket),
    bucket=bucket.id,
    content=cluster.kubeconfig.apply(prepare_kube_config),
    key="dags/.kube/config",
예제 #4
0
import mimetypes
import os

from pulumi import export, FileAsset
from pulumi_aws import s3

web_bucket = s3.Bucket('s3-website-bucket',
                       website={"index_document": "index.html"})

content_dir = "www"
for file in os.listdir(content_dir):
    filepath = os.path.join(content_dir, file)
    mime_type, _ = mimetypes.guess_type(filepath)
    obj = s3.BucketObject(file,
                          bucket=web_bucket.id,
                          source=FileAsset(filepath),
                          content_type=mime_type)


def public_read_policy_for_bucket(bucket_name):
    return json.dumps({
        "Version":
        "2012-10-17",
        "Statement": [{
            "Effect": "Allow",
            "Principal": "*",
            "Action": ["s3:GetObject"],
            "Resource": [
                f"arn:aws:s3:::{bucket_name}/*",
            ]
        }]
예제 #5
0
from pulumi import export, FileAsset, ResourceOptions, Output
from pulumi_aws import s3, lambda_, apigateway
import iam

LAMBDA_SOURCE = 'lambda.py'
LAMBDA_PACKAGE = 'lambda.zip'
LAMBDA_VERSION = '1.0.0'
os.system('zip %s %s' % (LAMBDA_PACKAGE, LAMBDA_SOURCE))

# Create an AWS resource (S3 Bucket)
bucket = s3.Bucket('lambda-api-gateway-example')

mime_type, _ = mimetypes.guess_type(LAMBDA_PACKAGE)
obj = s3.BucketObject(LAMBDA_VERSION + '/' + LAMBDA_PACKAGE,
                      bucket=bucket.id,
                      source=FileAsset(LAMBDA_PACKAGE),
                      content_type=mime_type)

example_fn = lambda_.Function(
    'ServerlessExample',
    s3_bucket=bucket.id,
    s3_key=LAMBDA_VERSION + '/' + LAMBDA_PACKAGE,
    handler="lambda.handler",
    runtime="python3.7",
    role=iam.lambda_role.arn,
)

example_api = apigateway.RestApi(
    'ServerlessExample', description='Pulumi Lambda API Gateway Example')

proxy_root_met = apigateway.Method('proxy_root',
예제 #6
0
def StaticSite(self, name, domain, zone, content_dir, __opts__):
    """
    A static site, at the given domain with the contents of the given directory.

    Uses S3, CloudFront, ACM, and Route53.
    """
    web_bucket = s3.Bucket(
        f'{name}-bucket',
        bucket=domain,
        website={
            "index_document": "index.html",
            "errorDocument": "404.html",
        },
        acl='public-read',
        website_domain=domain,
        **opts(parent=self),
    )

    for absp, relp in walk(content_dir):
        mime_type, _ = mimetypes.guess_type(str(absp))
        s3.BucketObject(
            f'{name}-{relp!s}',
            key=str(relp),
            bucket=web_bucket.id,
            source=FileAsset(str(absp)),
            content_type=mime_type,
            **opts(parent=web_bucket),
        )

    bucket_name = web_bucket.id
    s3.BucketPolicy(
        f"{name}-policy",
        bucket=bucket_name,
        policy=bucket_name.apply(public_read_policy_for_bucket),
        **opts(parent=web_bucket),
    )

    cert = Certificate(
        f"{name}-cert",
        domain=domain,
        zone=zone,
        **opts(parent=self, region='us-east-1'),
    )

    distro = cloudfront.Distribution(
        f"{name}-dist",
        enabled=True,
        # Alternate aliases the CloudFront distribution can be reached at, in addition to https://xxxx.cloudfront.net.
        # Required if you want to access the distribution via config.targetDomain as well.
        aliases=[domain],

        is_ipv6_enabled=True,

        # We only specify one origin for this distribution, the S3 content bucket.
        origins=[
            {
                "originId": web_bucket.arn,
                "domainName": web_bucket.website_endpoint,
                "customOriginConfig": {
                    # Amazon S3 doesn't support HTTPS connections when using an S3 bucket configured as a website endpoint.
                    "originProtocolPolicy": "http-only",
                    "httpPort": 80,
                    "httpsPort": 443,
                    "originSslProtocols": ["TLSv1.2"],
                },
            },
        ],

        default_root_object="index.html",

        # A CloudFront distribution can configure different cache behaviors based on the request path.
        # Here we just specify a single, default cache behavior which is just read-only requests to S3.
        default_cache_behavior={
            "targetOriginId": web_bucket.arn,

            "viewerProtocolPolicy": "redirect-to-https",
            "allowedMethods": ["GET", "HEAD", "OPTIONS"],
            "cachedMethods": ["GET", "HEAD", "OPTIONS"],

            "forwardedValues": {
                "cookies": {"forward": "none"},
                "queryString": False,
            },

            "minTtl": 0,
            "defaultTtl": 10*60,
            "maxTtl": 10*60,
        },

        # "All" is the most broad distribution, and also the most expensive.
        # "100" is the least broad, and also the least expensive.
        price_class="PriceClass_100",

        # You can customize error responses. When CloudFront recieves an error from the origin (e.g.
        # S3 or some other web service) it can return a different error code, and return the
        # response for a different resource.
        custom_error_responses=[
            {"errorCode": 404, "responseCode": 404, "responsePagePath": "/404.html"},
        ],

        restrictions={
            "geoRestriction": {
                "restrictionType": "none",
            },
        },

        viewer_certificate={
            "acmCertificateArn": cert.cert_arn,
            "sslSupportMethod": "sni-only",
        },

        # loggingConfig: {
        #     bucket: logsBucket.bucketDomainName,
        #     includeCookies: false,
        #     prefix: `${config.targetDomain}/`,
        # },
        **opts(parent=self),
    )

    a_aaaa(
        f"{name}-record",
        name=domain,
        zone_id=zone.zone_id,
        aliases=[
            {
                'name': distro.domain_name,
                'zone_id': distro.hosted_zone_id,
                'evaluate_target_health': True,
            },
        ],
        **opts(parent=self),
    )

    return {
        'url': f'https://{domain}/'
    }