コード例 #1
0
def _create_ip_address(ip_address, ports, protocol, dns_name_label, network_profile):
    """Create IP address. """
    if (ip_address and ip_address.lower() == 'public') or dns_name_label:
        return IpAddress(ports=[Port(protocol=protocol, port=p) for p in ports],
                         dns_name_label=dns_name_label, type=ContainerGroupIpAddressType.public)
    if network_profile:
        return IpAddress(ports=[Port(protocol=protocol, port=p) for p in ports],
                         type=ContainerGroupIpAddressType.private)
コード例 #2
0
def create_new_container_group(aci_client=None,
                               reg_client=None,
                               reg_name=None,
                               con_group_name=None,
                               con_group_image=None):
    try:
        res_request = ResourceRequests(memory_in_gb=2, cpu=1.0)
        res_requirement = ResourceRequirements(requests=res_request)
        res_group_obj = reg_client.resource_groups.get(reg_name)
        container_1 = Container(name=con_group_name,
                                image="microsoft\aci-helloworld:latest",
                                resources=res_requirement,
                                ports=[ContainerPort(port=80)])
        ports = [Port(protocol=ContainerGroupNetworkProtocol.tcp, port=80)]
        group_ip_address = IpAddress(ports=ports,
                                     dns_name_label=con_group_name,
                                     type="Public")

        group = ContainerGroup(location=res_group_obj.location,
                               containers=[container_1],
                               os_type=OperatingSystemTypes.linux,
                               ip_address=group_ip_address)
        aci_client.container_groups.begin_create_or_update(
            res_group_obj.name, con_group_name, group)

    except Exception as err:
        print(err)
コード例 #3
0
def create_container_group(resource_group_name, name, location, image,
                           env_vars):

    # setup default values
    port = 80
    container_resource_requirements = None
    command = None

    # set memory and cpu
    container_resource_requests = ResourceRequests(memory_in_gb=3.5, cpu=2)
    container_resource_requirements = ResourceRequirements(
        requests=container_resource_requests)

    container = Container(name=name,
                          image=image,
                          resources=container_resource_requirements,
                          command=command,
                          ports=[ContainerPort(port=port)],
                          environment_variables=env_vars)

    # defaults for container group
    cgroup_os_type = OperatingSystemTypes.linux
    cgroup_ip_address = IpAddress(
        ports=[Port(protocol=ContainerGroupNetworkProtocol.tcp, port=port)])
    image_registry_credentials = None

    cgroup = ContainerGroup(
        location=location,
        containers=[container],
        os_type=cgroup_os_type,
        ip_address=cgroup_ip_address,
        image_registry_credentials=image_registry_credentials)

    client.container_groups.create_or_update(resource_group_name, name, cgroup)
コード例 #4
0
ファイル: app.py プロジェクト: yolocs/prompt
def create_container(name, image, pr_number, user_id, resource_group, port=None, location='westus'):
    from azure.mgmt.containerinstance.models import (ContainerGroup, Container, ContainerPort, Port, IpAddress,
                                                     ImageRegistryCredential, ResourceRequirements, ResourceRequests,
                                                     ContainerGroupNetworkProtocol, OperatingSystemTypes, EnvironmentVariable,
                                                     Volume, AzureFileVolume, VolumeMount)
    from random import randint
    import secrets
    pr_number = str(pr_number)
    if port is None:
        port = randint(1000, 65000)
    instance_token = secrets.token_urlsafe(256)
    environment_variables = [EnvironmentVariable('PR_NUM', pr_number),
                             EnvironmentVariable('PORT', port),
                             EnvironmentVariable('INSTANCE_TOKEN', instance_token)]
    tags = {'userId': user_id, 'prNumber': pr_number}
    container_resource_requests = ResourceRequests(memory_in_gb='1.5', cpu='1')
    container_resource_requirements = ResourceRequirements(requests=container_resource_requests)
    container = Container(name=name,
                          image=image,
                          resources=container_resource_requirements,
                          ports=[ContainerPort(port=port)],
                          environment_variables=environment_variables,
                          volume_mounts=[VolumeMount('volume1', '/cert', read_only=True)])
    cgroup_ip_address = IpAddress(ports=[Port(protocol=ContainerGroupNetworkProtocol.tcp, port=port)])
    cgroup_os_type = OperatingSystemTypes.linux
    afv = AzureFileVolume(SHARE_NAME, SHARE_STORAGE_ACCOUNT_NAME, read_only=True, storage_account_key=SHARE_STORAGE_ACCOUNT_KEY)
    cgroup = ContainerGroup(location=location,
                            containers=[container],
                            os_type=cgroup_os_type,
                            ip_address=cgroup_ip_address,
                            tags=tags,
                            volumes=[Volume('volume1', afv)])
    return get_aci_client().container_groups.create_or_update(resource_group, name, cgroup)
コード例 #5
0
ファイル: custom.py プロジェクト: yolocs/azure-cli
def create_ip_address(ip_address, ports):
    """Create IP address. """
    if ip_address and ip_address.lower() == 'public':
        return IpAddress(ports=[
            Port(protocol=ContainerGroupNetworkProtocol.tcp, port=p)
            for p in ports
        ])
コード例 #6
0
ファイル: custom.py プロジェクト: stefangordon/azure-cli
def _create_ip_address(ip_address, ports, dns_name_label):
    """Create IP address. """
    if (ip_address and ip_address.lower() == 'public') or dns_name_label:
        return IpAddress(ports=[
            Port(protocol=ContainerGroupNetworkProtocol.tcp, port=p)
            for p in ports
        ],
                         dns_name_label=dns_name_label)
コード例 #7
0
def create_container_group_multi(aci_client, resource_group,
                                 container_group_name, container_image_1,
                                 container_image_2):
    """Creates a container group with two containers in the specified
       resource group.

    Arguments:
        aci_client {azure.mgmt.containerinstance.ContainerInstanceManagementClient}
                    -- An authenticated container instance management client.
        resource_group {azure.mgmt.resource.resources.models.ResourceGroup}
                    -- The resource group in which to create the container group.
        container_group_name {str}
                    -- The name of the container group to create.
        container_image_1 {str}
                    -- The first container image name and tag, for example:
                       microsoft\aci-helloworld:latest
        container_image_2 {str}
                    -- The second container image name and tag, for example:
                       microsoft\aci-tutorial-sidecar:latest
    """
    print("Creating container group '{0}'...".format(container_group_name))

    # Configure the containers
    container_resource_requests = ResourceRequests(memory_in_gb=2, cpu=1.0)
    container_resource_requirements = ResourceRequirements(
        requests=container_resource_requests)

    container_1 = Container(name=container_group_name + '-1',
                            image=container_image_1,
                            resources=container_resource_requirements,
                            ports=[ContainerPort(port=80)])

    container_2 = Container(name=container_group_name + '-2',
                            image=container_image_2,
                            resources=container_resource_requirements)

    # Configure the container group
    ports = [Port(protocol=ContainerGroupNetworkProtocol.tcp, port=80)]
    group_ip_address = IpAddress(ports=ports,
                                 dns_name_label=container_group_name,
                                 type='Public')
    group = ContainerGroup(location=resource_group.location,
                           containers=[container_1, container_2],
                           os_type=OperatingSystemTypes.linux,
                           ip_address=group_ip_address)

    # Create the container group
    aci_client.container_groups.create_or_update(resource_group.name,
                                                 container_group_name, group)

    # Get the created container group
    container_group = aci_client.container_groups.get(resource_group.name,
                                                      container_group_name)

    print("Once DNS has propagated, container group '{0}' will be reachable at"
          " http://{1}".format(container_group_name,
                               container_group.ip_address.fqdn))
コード例 #8
0
def create_container_group_multi(**kwargs):
    """Creates a container group with two containers in the specified
       resource group.

    Arguments:
        aci_client {azure.mgmt.containerinstance.ContainerInstanceManagementClient}
                    -- An authenticated container instance management client.
        resource_group {azure.mgmt.resource.resources.models.ResourceGroup}
                    -- The resource group in which to create the container group.
        container_group_name {str}
                    -- The name of the container group to create.
        containers {List[azure.mgmt.containerinstance.models.Container]}
        container_group_ports {List[azure.mgmt.containerinstance.models.Port]}
    """
    aci_client = kwargs.get('aci_client')
    resource_group = kwargs.get('resource_group')
    container_group_name = kwargs.get('container_group_name')
    containers = kwargs.get('containers')

    log.info("Creating container group '{0}'...".format(container_group_name))

    # Configure the container group
    ports = []
    for container_group_port in kwargs.get('container_group_ports'):
        ports.append(container_group_port)

    group_ip_address = IpAddress(ports=ports,
                                 dns_name_label=container_group_name)
    group = ContainerGroup(location=resource_group.location,
                           containers=containers,
                           os_type=OperatingSystemTypes.linux,
                           ip_address=group_ip_address,
                           restart_policy=ContainerGroupRestartPolicy.never)

    # Create the container group
    aci_client.container_groups.create_or_update(resource_group.name,
                                                 container_group_name, group)

    # Get the created container group
    container_group = aci_client.container_groups.get(resource_group.name,
                                                      container_group_name)

    log.info(
        "Once DNS has propagated, container group '{0}' will be reachable at"
        " http://{1}".format(container_group_name,
                             container_group.ip_address.fqdn))

    return container_group
コード例 #9
0
def _create_ip_address(ip_address, ports, protocol, dns_name_label):
    """Create IP address. """
    if (ip_address and ip_address.lower() == 'public') or dns_name_label:
        return IpAddress(ports=[Port(protocol=protocol, port=p) for p in ports], dns_name_label=dns_name_label)
コード例 #10
0
    def create_update_containerinstance(self):
        '''
        Creates or updates a container service with the specified configuration of orchestrator, masters, and agents.

        :return: deserialized container instance state dictionary
        '''
        self.log("Creating / Updating the container instance {0}".format(
            self.name))

        registry_credentials = None

        if self.registry_login_server is not None:
            registry_credentials = [
                ImageRegistryCredential(server=self.registry_login_server,
                                        username=self.registry_username,
                                        password=self.registry_password)
            ]

        ip_address = None

        if self.ip_address == 'public':
            # get list of ports
            if self.ports:
                ports = []
                for port in self.ports:
                    ports.append(Port(port=port, protocol="TCP"))
                ip_address = IpAddress(ports=ports, ip=self.ip_address)

        containers = []

        for container_def in self.containers:
            name = container_def.get("name")
            image = container_def.get("image")
            memory = container_def.get("memory", 1.5)
            cpu = container_def.get("cpu", 1)
            ports = []

            port_list = container_def.get("ports")
            if port_list:
                for port in port_list:
                    ports.append(ContainerPort(port))

            containers.append(
                Container(name=name,
                          image=image,
                          resources=ResourceRequirements(
                              ResourceRequests(memory_in_gb=memory, cpu=cpu)),
                          ports=ports))

        parameters = ContainerGroup(
            location=self.location,
            containers=containers,
            image_registry_credentials=registry_credentials,
            restart_policy=None,
            ip_address=ip_address,
            os_type=self.os_type,
            volumes=None)

        response = self.mgmt_client.container_groups.create_or_update(
            self.resource_group, self.name, parameters)

        return response.as_dict()
コード例 #11
0
ファイル: azure_aci.py プロジェクト: occopus/resource-handler
    def _start_container(self, resource_handler):
        log.debug('Starting Azure ACI')
        location = self.res['location'].lower()
        self.resource_client.resource_groups.create_or_update(
            self.res['resource_group'], {'location': self.res['location']})
        container_group_name = unique_vmname(self.node_def)
        network_type = self.res['network_type']
        network_profile = None
        if 'gpu_type' in self.res:
            count = self.res['gpu_count'] if 'gpu_count' in self.res else 1
            gpu = GpuResource(count=count, sku=self.res['gpu_type'])
            container_resource_requests = ResourceRequests(
                memory_in_gb=self.res['memory'],
                cpu=self.res['cpu_cores'],
                gpu=gpu)
        else:
            container_resource_requests = ResourceRequests(
                memory_in_gb=self.res['memory'], cpu=self.res['cpu_cores'])
        container_resource_requirements = ResourceRequirements(
            requests=container_resource_requests)
        ports = []
        ipports = []
        for porte in self.res.get('ports', []):
            port = porte
            protocol = 'TCP'
            if isinstance(porte, str) and '/' in porte:
                (port, protocol) = port.split('/')
                port = int(port)
            ports.append(ContainerPort(port=port, protocol=protocol))
            ipports.append(Port(protocol=protocol, port=port))
        environment = []
        if network_type.lower() == 'public':
            pubip_var = EnvironmentVariable(name='_OCCOPUS_ALLOCATED_FQDN',
                                            value='%s.%s.azurecontainer.io' %
                                            (container_group_name, location))
            environment.append(pubip_var)
        for env in self.env:
            edata = env.split('=', 1)
            if len(edata) != 2: continue
            env_var = EnvironmentVariable(name=edata[0], value=edata[1])
            environment.append(env_var)
        container = Container(
            name=container_group_name,
            image=self.res['image'],
            resources=container_resource_requirements,
            ports=ports,
            command=self.command if self.command is not None else None,
            environment_variables=environment)
        if network_type.lower() == 'public':
            group_ip_address = IpAddress(ports=ipports,
                                         dns_name_label=container_group_name,
                                         type='Public')
            self.vnet_name = None
        elif network_type.lower() == 'private':
            vnet_name = unique_vmname(self.node_def) + '-vnet' if self.res.get(
                'vnet_name', None) == None else self.res['vnet_name']
            self.vnet_name = vnet_name
            subnet_name = unique_vmname(
                self.node_def) + '-subnet' if self.res.get(
                    'subnet_name', None) == None else self.res['subnet_name']
            network_profile_name = unique_vmname(self.node_def) + '-netprofile'
            if self.res.get('vnet_name', None) == None:
                log.debug('Creating vnet')
                async_vnet_creation = self.network_client.virtual_networks.create_or_update(
                    self.res['resource_group'], vnet_name, {
                        'location': location,
                        'address_space': {
                            'address_prefixes': ['10.0.0.0/16']
                        }
                    })
                async_vnet_creation.wait()
                self.created_resources['virtual_network'] = vnet_name
                log.debug('Created vnet')
            if self.res.get('subnet_name', None) == None:
                # Create Subnet
                log.debug('Creating Subnet')
                aci_delegation_service_name = "Microsoft.ContainerInstance/containerGroups"
                aci_delegation = Delegation(
                    name=aci_delegation_service_name,
                    service_name=aci_delegation_service_name)
                subnet = Subnet(name=subnet_name,
                                location=location,
                                address_prefix='10.0.0.0/24',
                                delegations=[aci_delegation])
                subnet_info = self.network_client.subnets.create_or_update(
                    self.res['resource_group'], vnet_name, subnet_name,
                    subnet).result()
                self.created_resources['subnet'] = subnet_name
                log.debug('Creatied Subnet')
            else:
                subnet_info = self.network_client.subnets.get(
                    self.res['resource_group'], vnet_name, subnet_name)
            default_network_profile_name = "aci-network-profile-{}-{}".format(
                vnet_name, subnet_name)
            network_profile_ops = self.network_client.network_profiles
            network_profile = NetworkProfile(
                name=default_network_profile_name,
                location=location,
                container_network_interface_configurations=[
                    ContainerNetworkInterfaceConfiguration(
                        name="eth0",
                        ip_configurations=[
                            IPConfigurationProfile(name="ipconfigprofile",
                                                   subnet=subnet_info)
                        ])
                ])
            network_profile = network_profile_ops.create_or_update(
                self.res['resource_group'], network_profile_name,
                network_profile).result()
            group_ip_address = IpAddress(ports=ipports, type='Private')
        else:
            errormsg = '[{0}] Network type "{1}" is not supported. Please use either "Public" or "Private"'.format(
                resource_handler.name, network_type)
            log.debug(errormsg)
            raise NodeCreationError(None, errormsg)

        cg_network_profile = None
        if network_profile:
            cg_network_profile = ContainerGroupNetworkProfile(
                id=network_profile.id)
            self.created_resources['network_profile'] = network_profile_name

        group = ContainerGroup(location=location,
                               containers=[container],
                               os_type=self.res['os_type'],
                               ip_address=group_ip_address,
                               network_profile=cg_network_profile)
        # Create the container group
        self.aci_client.container_groups.create_or_update(
            self.res['resource_group'], container_group_name, group)
        return container_group_name