Beispiel #1
0
def verify_data(r):
    t = r.resource_type
    if t != "pulumi-nodejs:dynamic:Resource":
        return

    # Verify is_dry_run()
    assert is_dry_run() == r.props["isDryRun"]

    # Verify get_project()
    assert "PULUMI_TEST_PROJECT" in os.environ
    assert get_project() == os.environ["PULUMI_TEST_PROJECT"]
    assert get_project() == r.props["getProject"]

    # Verify get_stack()
    assert "PULUMI_TEST_STACK" in os.environ
    assert get_stack() == os.environ["PULUMI_TEST_STACK"]
    assert get_stack() == r.props["getStack"]

    # Verify Config
    assert json.dumps(CONFIG,
                      sort_keys=True) == json.dumps(dict(r.props["allConfig"]),
                                                    sort_keys=True)
    config = Config()
    value = config.require("aConfigValue")
    assert value == "this value is a value"
    assert aws_config.region == "us-west-2"
Beispiel #2
0
def validate(r):
    config = Config()
    test_scenario = config.require_int("scenario")

    # We only validate during the first test scenario. The subsequent test scenario is only
    # used to unprotect protected resources in preparation for destroying the stack.
    if test_scenario != 1:
        return

    t = r.resource_type
    if (t == "pulumi:pulumi:Stack" or t == "pulumi:providers:pulumi-nodejs"
            or t == "pulumi:providers:random"):
        assert options_equal(
            PolicyResourceOptions(
                protect=False,
                ignore_changes=[],
                delete_before_replace=None,
                aliases=[],
                additional_secret_outputs=[],
                custom_timeouts=PolicyCustomTimeouts(0, 0, 0),
            ), r.opts)
    elif t == "pulumi-nodejs:dynamic:Resource":
        validate_dynamic_resource(r)
    elif t == "random:index/randomUuid:RandomUuid":
        assert options_equal(
            PolicyResourceOptions(
                protect=False,
                ignore_changes=[],
                delete_before_replace=None,
                aliases=[],
                additional_secret_outputs=[],
                custom_timeouts=PolicyCustomTimeouts(0, 0, 0),
            ), r.opts)
    else:
        raise AssertionError(f"Unexpected resource of type: '{t}'.")
Beispiel #3
0
 def __init__(
     self,
     provider_param1: Optional[str] = None,
     provider_param2: Optional[str] = None,
 ):
     config = Config()
     self.provider_param1 = (
         provider_param1 if provider_param1 else config.require("provider_param1")
     )
     self.provider_param2 = (
         provider_param2 if provider_param2 else config.require("provider_param2")
     )
Beispiel #4
0
def read_pulumi_config() -> EnvironmentDescriptor:
    moduleCfg = Config()
    awsCfg = Config("aws")

    return EnvironmentDescriptor(
        provider=moduleCfg.require('provider'),
        stage=moduleCfg.require('stage'),
        region=awsCfg.require('region'),
        name=moduleCfg.require('name'),
        access_key=awsCfg.get_secret('access_key'),
        secret_key=awsCfg.get_secret('secret_key'),
    )
Beispiel #5
0
 def from_config(pulumi_config: pulumi.Config) -> ArtifactGetter:
     """
     If local-grapl:
         - We don't require an `artifacts:` field
         - `.get()` can be None
     Else:
         - We require an `artifacts:` field
         - `.get()` must resolve a value for that key or raise KeyError
     """
     artifact_dict = (pulumi_config.get_object("artifacts") or {}
                      if config.LOCAL_GRAPL else
                      pulumi_config.require_object("artifacts"))
     return ArtifactGetter(
         artifacts=artifact_dict,
         require_artifact=(not config.LOCAL_GRAPL),
     )
Beispiel #6
0
def create_storage_nodes(subnets, security_groups):

    rds_config = Config().require_object("rds_config")
    redis_sg = security_groups['redis_sg']
    rds_sg = security_groups['rds_sg']

    # Create a redis Subnet Group
    redis_subnet_group = elasticache.SubnetGroup(
        "RedisSubGroup", subnet_ids=[subnet.id for subnet in subnets])

    # To-do: Auth and encryption support

    # Create a redis cluster
    # To-do: Handle encryption. Don't see any way from pulumi specs
    redis_cluster = elasticache.Cluster(
        "redisnode",
        engine="redis",
        engine_version="3.2.10",
        node_type="cache.t3.micro",
        num_cache_nodes=1,
        parameter_group_name="default.redis3.2",
        port=6379,
        subnet_group_name=redis_subnet_group.id,
        security_group_ids=[redis_sg.id])

    rds_subnet_group = rds.SubnetGroup(
        "rdssubgroup", subnet_ids=[subnet.id for subnet in subnets])

    # To-do: Secret managment and get from Config
    rds_username = rds_config["username"]
    rds_password = rds_config["password"]
    rds_database_name = rds_config["database_name"]

    # Create a rds instance
    rds_instance = rds.Instance("default",
                                allocated_storage=20,
                                engine="mysql",
                                engine_version="5.7",
                                instance_class="db.t3.micro",
                                name=rds_database_name,
                                parameter_group_name="default.mysql5.7",
                                password=rds_password,
                                storage_type="gp2",
                                username=rds_username,
                                storage_encrypted=True,
                                db_subnet_group_name=rds_subnet_group.id,
                                vpc_security_group_ids=[rds_sg.id],
                                skip_final_snapshot=True)
    return {"rds": rds_instance, "redis": redis_cluster}
Beispiel #7
0
 def __init__(
         self,
         username: str = None,
         password: str = None,
         account_name: str = None,
         role: str = None,
         database: str = None,
         schema: str = None
 ):
     config = Config()
     self.username = username if username else config.require('snowflakeUsername')
     self.password = password if password else config.require('snowflakePassword')
     self.account_name = account_name if account_name else config.get('snowflakeAccountName')
     self.role = role if role else config.get('snowflakeRole')
     self.database = database if database else config.get('snowflakeDatabase')
     self.schema = schema if schema else config.get('snowflakeSchema')
Beispiel #8
0
import pulumi
from pulumi import Config, ResourceOptions, Output
from pulumi_azure import core, storage, compute, network, sql

config = Config("sso-lab")

# retrieve password from config
pwd = config.require_secret("pwd")
sqlpwd = config.require_secret("sqlpwd")
print("Secrets retrieved...")

# set some vars
server_user = "******"
sql_user = "******"

# Create an Azure Resource Group
rg = core.ResourceGroup("rg-ssolab")

# create vnet
vnet = network.VirtualNetwork("vnet-sso",
                              address_spaces=["10.2.0.0/16"],
                              resource_group_name=rg.name,
                              dns_servers=["10.2.0.4"])

subnet = network.Subnet("servers",
                        virtual_network_name=vnet.name,
                        address_prefix="10.2.0.0/24",
                        resource_group_name=rg.name)

bastionSubnet = network.Subnet("bastion",
                               name="AzureBastionSubnet",
Beispiel #9
0
import pulumi
from pulumi import Config, ResourceOptions
from pulumi_kubernetes import Provider
from pulumi_kubernetes.apps.v1 import Deployment

config = Config()

namespace = config.get("namespace") or "default"

provider = Provider("kubernetes", namespace=namespace)

app_labels = {"app": "nginx"}

deployment = Deployment(
    "nginx",
    spec={
        "selector": {"match_labels": app_labels},
        "replicas": 1,
        "template": {
            "metadata": {"labels": app_labels},
            "spec": {"containers": [{"name": "nginx", "image": "nginx"}]},
        },
    },
    opts=ResourceOptions(provider=provider),
)

pulumi.export("name", deployment.metadata["name"])
## Note how you can't destroy the stack as long as protect is true.
# Doc: https://www.pulumi.com/docs/intro/concepts/resources/#protect
# Doc: https://www.pulumi.com/docs/reference/cli/pulumi_state_unprotect/

import base64
import pulumi
from pulumi import Config, ResourceOptions
from pulumi_tls import PrivateKey
from pulumi_azure_native import resources, containerservice
import pulumi_azuread as azuread
import pulumi_kubernetes as k8s
from pulumi_kubernetes.helm.v3 import Chart, ChartOpts
import pulumi_random as random

# Config values or defaults
config = Config()
k8s_version = config.get('k8sVersion') or '1.18.14'
admin_username = config.get('adminUserName') or 'testuser'
node_count = config.get_int('nodeCount') or 2
node_size = config.get('nodeSize') or 'Standard_D2_v2'
password = config.get_secret("password")
if not password:
    rando_password = random.RandomPassword(
        'password',
        length=16,
        special=True,
        override_special='@_#',
    )
    password = rando_password.result

# Resource Group
    GetPolicyDocumentStatementArgs,
    GetPolicyDocumentStatementPrincipalArgs,
    Role,
    RolePolicy,
    get_policy_document,
)

tagger = Tagger(
    environment_name="alpha",
    source_code=(
        "https://github.com/moj-analytical-services/"
        "data-engineering-database-access-deploy"
    ),
)

GIT_CRYPT_KEY = Config().require("git_crypt_key")
GITHUB_TOKEN = Config().require("github_token")

account_id = get_caller_identity().account_id

assume_role_policy = get_policy_document(
    statements=[
        GetPolicyDocumentStatementArgs(
            actions=["sts:AssumeRole"],
            effect="Allow",
            principals=[
                GetPolicyDocumentStatementPrincipalArgs(
                    identifiers=["codebuild.amazonaws.com"], type="Service"
                )
            ],
        )
Beispiel #12
0
import pulumi_aws as aws
from pulumi_aws.config.vars import region
from pulumi import Config, ResourceOptions, export


def require_region():
    """
    require_region fetches the AWS region, requiring that it exists. if it does
    not exist, an exception is raised.
    """
    if not region:
        raise Exception('No AWS region has been configured')
    return region


config = Config()
role_to_assume_arn = config.require('roleToAssumeARN')

provider = aws.Provider('privileged',
                        assume_role={
                            'role_arn': role_to_assume_arn,
                            'session_name': 'PulumiSession',
                            'externalId': 'PulumiApplication',
                        },
                        region=require_region())

# Creates an AWS resource (S3 Bucket)
bucket = aws.s3.Bucket('my-bucket', opts=ResourceOptions(provider=provider))

# Exports the DNS name of the bucket
export('bucket_name', bucket.bucket_domain_name)
Beispiel #13
0
    """Base class for exceptions in this module."""
    pass

class ConfigError(Error):
    """Exception raised for errors in Pulumi Config.

    Attributes:
        keys -- Config keys with the error
        message -- explanation of the error
    """
    def __init__(self, keys: [str], message: str):
        self.keys = keys
        self.message = message

# retrieve the stack configuration data
config = Config()

# set default tags to be applied to all taggable resources
stack = get_stack()
default_tags = {
    'environment': stack
}

# Azure Bastion hosts in hub and spokes (until functional across peerings)
azure_bastion = config.get_bool('azure_bastion')

# Azure Firewall to route all Internet-bound traffic to designated next hop
forced_tunnel = config.get('forced_tunnel')
if forced_tunnel:
    ft_ip = ip_address(forced_tunnel) # check IP address is valid
Beispiel #14
0

class ConfigError(Error):
    """Exception raised for errors in Pulumi Config.

    Attributes:
        keys -- Config keys with the error
        message -- explanation of the error
    """
    def __init__(self, keys: [str], message: str):
        self.keys = keys
        self.message = message


# retrieve the stack configuration data
config = Config()

# retrieve optional separator choice and suffix
separator = config.get('separator') or '-'
separator = separator[0]
if separator == ' ':
    separator = ''
suffix = config.get('suffix') or ''

# retrieve project and stack (org not yet available)
project = get_project()
stack = get_stack()
# set default tags to be applied to all taggable resources
default_tags = {
    'manager': 'pulumi',
    'project': project,
Beispiel #15
0
def pulumi_program():
    config = Config()
    export("exp_static", "foo")
    export("exp_cfg", config.get("bar"))
    export("exp_secret", config.get_secret("buzz"))
Beispiel #16
0
import pulumi_digitalocean as do
from pulumi import Config, export, Output, ResourceOptions
from pulumi_kubernetes import Provider
from pulumi_kubernetes.apps.v1 import Deployment
from pulumi_kubernetes.core.v1 import Service

config = Config()
node_count = config.get_float("nodeCount") or 3
app_replica_count = config.get_float("appReplicaCount") or 5
domain_name = config.get("domainName")

cluster = do.KubernetesCluster("do-cluster",
                               region="sfo2",
                               version="latest",
                               node_pool={
                                   "name": "default",
                                   "size": "s-2vcpu-2gb",
                                   "node_count": node_count
                               })

k8s_provider = Provider("do-k8s",
                        kubeconfig=cluster.kube_configs[0]["rawConfig"])

app_labels = {"app": "app-nginx"}
app = Deployment("do-app-dep",
                 spec={
                     'selector': {
                         'matchLabels': app_labels
                     },
                     'replicas': 1,
                     'template': {
Beispiel #17
0
import pulumi_azure_native.insights as insights
import pulumi_azure_native.resources as resource
import pulumi_azure_native.sql as sql
import pulumi_azure_native.storage as storage
import pulumi_azure_native.web as web
from pulumi import Config, Output, asset, export
from pulumi_azure_native.storage import (BlobContainer, PublicAccess,
                                         StorageAccount)

username = "******"

config = Config()
pwd = config.require("sqlPassword")

resource_group = resource.ResourceGroup("appservicerg")

storage_account = storage.StorageAccount(
    "appservicesa",
    resource_group_name=resource_group.name,
    kind=storage.Kind.STORAGE_V2,
    sku=storage.SkuArgs(name=storage.SkuName.STANDARD_LRS))

app_service_plan = web.AppServicePlan("appservice-asp",
                                      resource_group_name=resource_group.name,
                                      kind="App",
                                      sku=web.SkuDescriptionArgs(
                                          tier="Basic",
                                          name="B1",
                                      ))

storage_container = BlobContainer("appservice-c",
Beispiel #18
0
# Copyright 2016-2020, Pulumi Corporation.  All rights reserved.

import base64
from pulumi import Config, Output, export
from pulumi_azure_nextgen.compute import latest as compute
from pulumi_azure_nextgen.network import latest as network
from pulumi_azure_nextgen.resources import latest as resources

config = Config()
location = config.get("location") or "westus"
username = config.require("username")
password = config.require("password")

resource_group = resources.ResourceGroup("server",
                                         resource_group_name="server",
                                         location=location)

net = network.VirtualNetwork("server-network",
                             resource_group_name=resource_group.name,
                             location=location,
                             virtual_network_name="server-network",
                             address_space=network.AddressSpaceArgs(
                                 address_prefixes=["10.0.0.0/16"], ),
                             subnets=[
                                 network.SubnetArgs(
                                     name="default",
                                     address_prefix="10.0.1.0/24",
                                 )
                             ])

public_ip = network.PublicIPAddress("server-ip",
Beispiel #19
0
    """
    Returns the subdomain and the parent domain.
    """

    parts = domain.split('.')
    if len(parts) < 2:
        raise Exception(f'No TLD found on ${domain}')
    if len(parts) == 2:
        return '', domain
    subdomain = parts[0]
    parts.pop(0)
    return subdomain, '.'.join(parts) + '.'


# Read the configuration for this stack.
stack_config = Config()
target_domain = stack_config.require('targetDomain')
path_to_website_contents = stack_config.require('pathToWebsiteContents')
certificate_arn = stack_config.get('certificateArn')

# Create an S3 bucket configured as a website bucket.
content_bucket = pulumi_aws.s3.Bucket('contentBucket',
                                      bucket=target_domain,
                                      acl='public-read',
                                      website={
                                          'index_document': 'index.html',
                                          'error_document': '404.html'
                                      })


def crawl_directory(content_dir, f):
Beispiel #20
0
from pulumi import Config, export, get_project, get_stack, Output, ResourceOptions
from pulumi_gcp.config import project, zone
from pulumi_gcp.container import Cluster, get_engine_versions
from pulumi_kubernetes import Provider
from pulumi_kubernetes.apps.v1 import Deployment
from pulumi_kubernetes.core.v1 import Service
from pulumi_random import RandomPassword

# Read in some configurable settings for our cluster:
config = Config(None)

# nodeCount is the number of cluster nodes to provision. Defaults to 3 if unspecified.
NODE_COUNT = config.get('node_count') or 3
# nodeMachineType is the machine type to use for cluster nodes. Defaults to n1-standard-1 if unspecified.
# See https://cloud.google.com/compute/docs/machine-types for more details on available machine types.
NODE_MACHINE_TYPE = config.get('node_machine_type') or 'n1-standard-1'
# username is the admin username for the cluster.
USERNAME = config.get('username') or 'admin'
# password is the password for the admin user in the cluster.
PASSWORD = config.get_secret('password') or RandomPassword(
    "password", length=20, special=True).result
# master version of GKE engine
MASTER_VERSION = config.get('master_version')

# Now, actually create the GKE cluster.
k8s_cluster = Cluster(
    'gke-cluster',
    initial_node_count=NODE_COUNT,
    node_version=MASTER_VERSION,
    min_master_version=MASTER_VERSION,
    master_auth={
Beispiel #21
0
# Copyright 2016-2018, Pulumi Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pulumi import CustomResource, Config


class MyResource(CustomResource):
    def __init__(self, name):
        CustomResource.__init__(self, "test:index:MyResource", name)


config = Config("foo")
MyResource(config.require("name"))
Beispiel #22
0
"""An Azure RM Python Pulumi program"""
import pulumi
import pulumi_azure_nextgen.resources.latest as resources
import pulumi_azure_nextgen.databricks.latest as databricks

from pulumi import Output, export, Config, StackReference, get_stack, get_project

config = Config()
# reading in StackReference Path from local config
mystackpath = config.require("stackreference")
# setting the StackReference
my_network_stackreference = StackReference(mystackpath)
my_secondvirtualnetwork_output = my_network_stackreference.get_output(
    "virtual_network_name")
my_remote_resourcegroup_output = my_network_stackreference.get_output(
    "resource_group_name")
#my_secondvirtualnetwork = my_secondvirtualnetwork_output.apply(lambda my_secondvirtualnetwork_output: f"{my_secondvirtualnetwork_output}")
#my_remote_resourcegroup = my_remote_resourcegroup_output.apply(lambda my_remote_resourcegroup_output: f"{my_remote_resourcegroup_output}")

# The values for my_secondvirtualnetwork & my_remote_resourcegroup are from the virtualnetwork that has
# already been created using another pulumi stack.  This has to exist before this code can run.
my_secondvirtualnetwork = "shaht-vnet-peering-to-databricks"  # 2nd virtual network.  Needed for vpn peering block FROM databricks.
my_remote_resourcegroup = "shaht-rg-peering-to-databricks"

# local variables from config file
#   my subscription id
mysubid = config.get("mysubid")
#   azure location
my_location = config.get("location")
#   resource group name
my_resource_group_name = config.get("resource_group_name")
Beispiel #23
0
    which can be used to control which principals may assume an IAM Role, by 
    granting the `sts:AssumeRole` action to those principals.
    """
    return {
        'Version':
        '2012-10-17',
        'Statement': [{
            'Sid': 'AllowAssumeRole',
            'Effect': 'Allow',
            'Principal': principal,
            'Action': 'sts:AssumeRole'
        }]
    }


config = Config()
unprivileged_username = config.require('unprivilegedUsername')

unprivileged_user = aws.iam.User('unprivileged-user',
                                 name=unprivileged_username)

unprivileged_user_creds = aws.iam.AccessKey(
    'unprivileged-user-key',
    user=unprivileged_user.name,
    # additional_secret_outputs specify properties that must be encrypted as secrets
    # https://www.pulumi.com/docs/intro/concepts/resources/#additionalsecretoutputs
    opts=ResourceOptions(additional_secret_outputs=["secret"]))

allow_s3_management_role = aws.iam.Role(
    'allow-s3-management',
    description='Allow management of S3 buckets',
Beispiel #24
0
# Copyright 2016-2020, Pulumi Corporation.  All rights reserved.

import provisioners
import pulumi
import base64
from pulumi import Config, Output, export
from pulumi_azure_nextgen.compute import latest as compute
from pulumi_azure_nextgen.network import latest as network
from pulumi_azure_nextgen.resources import latest as resources

# Get the config ready to go.
config = Config()
key_name = config.get('keyName')
public_key = config.get('publicKey')
admin_username = config.get('admin_username')
admin_password = config.get('admin_password')
location = config.get('location')


# The privateKey associated with the selected key must be provided (either directly or base64 encoded),
# along with an optional passphrase if needed.
def decode_key(key):
    if key.startswith('-----BEGIN RSA PRIVATE KEY-----'):
        return key
    return key.encode('ascii')


private_key = config.require_secret('privateKey').apply(decode_key)
private_key_passphrase = config.get_secret('privateKeyPassphrase')

# Create a resource group to hold project resources.
Beispiel #25
0
def mock_config(config_settings):
    set_all_config(config_settings)
    return Config("test-config")
Beispiel #26
0
import pulumi
from pulumi import Config, ResourceOptions
from pulumi_azure import core, network
from webserver import WebServerArgs, WebServer

config = Config()
username = config.require_secret("username")
password = config.require_secret("password")

resource_group = core.ResourceGroup("server", location="West US")

net = network.VirtualNetwork(
    "server-network",
    resource_group_name=resource_group.name,
    location=resource_group.location,
    address_spaces=["10.0.0.0/16"],
    subnets=[
        network.VirtualNetworkSubnetArgs(name="default",
                                         address_prefix="10.0.1.0/24")
    ],
    opts=ResourceOptions(parent=resource_group),
)

subnet = network.Subnet(
    "server-subnet",
    resource_group_name=resource_group.name,
    virtual_network_name=net.name,
    address_prefixes=["10.0.2.0/24"],
    opts=ResourceOptions(parent=net),
)
Beispiel #27
0
        def program():
            config = Config()

            config.get("plainstr1")
            config.require("plainstr2")
            config.get_secret("plainstr3")
            config.require_secret("plainstr4")

            config.get_bool("plainbool1")
            config.require_bool("plainbool2")
            config.get_secret_bool("plainbool3")
            config.require_secret_bool("plainbool4")

            config.get_int("plainint1")
            config.require_int("plainint2")
            config.get_secret_int("plainint3")
            config.require_secret_int("plainint4")

            config.get_float("plainfloat1")
            config.require_float("plainfloat2")
            config.get_secret_float("plainfloat3")
            config.require_secret_float("plainfloat4")

            config.get_object("plainobj1")
            config.require_object("plainobj2")
            config.get_secret_object("plainobj3")
            config.require_secret_object("plainobj4")

            config.get("str1")
            config.require("str2")
            config.get_secret("str3")
            config.require_secret("str4")

            config.get_bool("bool1")
            config.require_bool("bool2")
            config.get_secret_bool("bool3")
            config.require_secret_bool("bool4")

            config.get_int("int1")
            config.require_int("int2")
            config.get_secret_int("int3")
            config.require_secret_int("int4")

            config.get_float("float1")
            config.require_float("float2")
            config.get_secret_float("float3")
            config.require_secret_float("float4")

            config.get_object("obj1")
            config.require_object("obj2")
            config.get_secret_object("obj3")
            config.require_secret_object("obj4")
Beispiel #28
0
from pulumi import Config, get_stack, export, Output
import pulumi_azuread as ad
import pulumi_random as random
from pulumi_azure import core, containerservice

config = Config()
password = config.get_secret("password") or random.RandomPassword(
    "pwd", length=20, special=True).result
ssh_public_key = config.require("sshPublicKey")

resource_group = core.ResourceGroup("aksresourcegroup")

ad_app = ad.Application("aks")

ad_sp = ad.ServicePrincipal("aksSp", application_id=ad_app.application_id)

ad_sp_password = ad.ServicePrincipalPassword("aksSpPassword",
                                             service_principal_id=ad_sp.id,
                                             value=password,
                                             end_date="2099-01-01T00:00:00Z")

aks_cluster_config = [
    {
        "name": "east",
        "location": "eastus",
        "node_count": 2,
        "node_size": "Standard_D2_v2"
    },
    {
        "name": "west",
        "location": "westus",
Beispiel #29
0
from pulumi import Config, export, get_project, get_stack, Output, ResourceOptions
from pulumi_gcp.config import project, zone, region
from pulumi_gcp.container import Cluster, get_engine_versions
from pulumi_kubernetes import Provider
from pulumi_kubernetes.apps.v1 import Deployment
from pulumi_kubernetes.core.v1 import Service
from pulumi_random import RandomPassword

# Read in some configurable settings for our cluster:
config = Config(None)

NODE_COUNT = config.get("node_count")
NODE_MACHINE_TYPE = config.get("node_machine_type")
IMAGE_TYPE = config.get("image_type")
DISK_TYPE = config.get("disk_type")
DISK_SIZE_GB = config.get("disk_size_gb")

# master version of GKE engine
MASTER_VERSION = config.get("master_version")
CLUSTER_NAME = config.get("pulumi-gke")

print(f"Master version: {MASTER_VERSION}")
print(f"Project: {project} | Region: {region} | Zone: {zone}")

# Now, actually create the GKE cluster.
# Pulumi docs: https://www.pulumi.com/docs/reference/pkg/python/pulumi_gcp/container/#pulumi_gcp.container.Cluster
# Terraform docs: https://www.terraform.io/docs/providers/google/r/container_cluster.html
k8s_cluster = Cluster(
    "gke-cluster",
    name=CLUSTER_NAME,
    # Zone is read automagically from the stack config file
Beispiel #30
0
from pulumi import Config, export, get_project, get_stack, Output, ResourceOptions
from pulumi_gcp.config import project, zone
from pulumi_gcp.container import Cluster, get_engine_versions
from pulumi_kubernetes import Provider
from pulumi_kubernetes.apps.v1 import Deployment
from pulumi_kubernetes.core.v1 import Service
from pulumi_random import RandomString

# Read in some configurable settings for our cluster:
config = Config(None)

# nodeCount is the number of cluster nodes to provision. Defaults to 3 if unspecified.
NODE_COUNT = config.get('node_count') or 3
# nodeMachineType is the machine type to use for cluster nodes. Defaults to n1-standard-1 if unspecified.
# See https://cloud.google.com/compute/docs/machine-types for more details on available machine types.
NODE_MACHINE_TYPE = config.get('node_machine_type') or 'n1-standard-1'
# username is the admin username for the cluster.
USERNAME = config.get('username') or 'admin'
# password is the password for the admin user in the cluster.
PASSWORD = config.get_secret('password') or RandomString(
    "password", length=20, special=True).result

engine_version = Output.from_input(get_engine_versions()).latest_master_version

# Now, actually create the GKE cluster.
k8s_cluster = Cluster(
    'gke-cluster',
    initial_node_count=NODE_COUNT,
    node_version=engine_version,
    min_master_version=engine_version,
    master_auth={