def import_image(repository, tags):
    mgmt_client = ContainerRegistryManagementClient(
        DefaultAzureCredential(),
        os.environ["CONTAINERREGISTRY_SUBSCRIPTION_ID"],
        api_version="2019-05-01")
    registry_uri = "registry.hub.docker.com"
    rg_name = os.environ["CONTAINERREGISTRY_RESOURCE_GROUP"]
    registry_name = os.environ["CONTAINERREGISTRY_REGISTRY_NAME"]

    import_source = ImportSource(source_image=repository,
                                 registry_uri=registry_uri)

    import_params = ImportImageParameters(mode=ImportMode.Force,
                                          source=import_source,
                                          target_tags=tags)

    result = mgmt_client.registries.begin_import_image(
        rg_name,
        registry_name,
        parameters=import_params,
    )

    while not result.done():
        pass

    # Do the same for anonymous
    mgmt_client = ContainerRegistryManagementClient(
        DefaultAzureCredential(),
        os.environ["CONTAINERREGISTRY_SUBSCRIPTION_ID"],
        api_version="2019-05-01")
    registry_uri = "registry.hub.docker.com"
    rg_name = os.environ["CONTAINERREGISTRY_RESOURCE_GROUP"]
    registry_name = os.environ["CONTAINERREGISTRY_ANONREGISTRY_NAME"]

    import_source = ImportSource(source_image=repository,
                                 registry_uri=registry_uri)

    import_params = ImportImageParameters(mode=ImportMode.Force,
                                          source=import_source,
                                          target_tags=tags)

    result = mgmt_client.registries.begin_import_image(
        rg_name,
        registry_name,
        parameters=import_params,
    )

    while not result.done():
        pass
Esempio n. 2
0
def acr(delete):
    creds = CredentialWrapper(DefaultAzureCredential())
    client = ContainerRegistryManagementClient(credentials=creds,
                                               subscription_id=SUBSCRIPTION_ID)
    if delete:
        delete_acr(ACR_NAMES, client)

    else:
        make_acr(ACR_NAMES, client)
Esempio n. 3
0
 def create_registry(self, auth, name, resource_group, location,
                     subscription_id, admin_user_enabled):
     client = ContainerRegistryManagementClient(auth, subscription_id)
     registry = models.Registry(sku=models.Sku(name="Standard"),
                                location=location,
                                admin_user_enabled=admin_user_enabled)
     return client.registries.create(
         resource_group, name, registry,
         subscription_id=subscription_id).result()
Esempio n. 4
0
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    REGISTRIES = "registriesxxyyzz"

    # Create client
    # # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    registry_client = ContainerRegistryManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)

    # Create resource group
    resource_client.resource_groups.create_or_update(GROUP_NAME,
                                                     {"location": "eastus"})

    # Create registries
    registries = registry_client.registries.begin_create(
        GROUP_NAME, REGISTRIES, {
            "location": "eastus",
            "tags": {
                "key": "value"
            },
            "sku": {
                "name": "Standard"
            },
            "admin_user_enabled": True
        }).result()
    print("Create registries:\n{}".format(registries))

    # Get registries
    registries = registry_client.registries.get(GROUP_NAME, REGISTRIES)
    print("Get registries:\n{}".format(registries))

    # Update registries
    registries = registry_client.registries.begin_update(
        GROUP_NAME, REGISTRIES, {
            "tags": {
                "key": "value"
            },
            "sku": {
                "name": "Standard"
            },
            "admin_user_enabled": True
        }).result()
    print("Update registries:\n{}".format(registries))

    # Delete registries
    registries = registry_client.registries.begin_delete(
        GROUP_NAME, REGISTRIES).result()
    print("Delete registries.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()
 def __init__(self,
              client_data,
              resource_helper,
              storage,
              name='containersample'):
     self.resources = resource_helper
     self.storage = storage
     self.name = name
     self._registry = None
     self._credentials = None
     self.credentials_file_name = 'docker.tar.gz'
     self.registry_client = ContainerRegistryManagementClient(*client_data)
Esempio n. 6
0
    def getCredential(self):
        self.credentials = ServicePrincipalCredentials(
            client_id=self.client_id,
            secret=self.secret,
            tenant=self.tenant_id)

        self.compute_client = ComputeManagementClient(self.credentials,
                                                      self.subscription_id)
        self.network_client = NetworkManagementClient(self.credentials,
                                                      self.subscription_id)
        self.storage_client = StorageManagementClient(self.credentials,
                                                      self.subscription_id)
        self.container_regisry_client = ContainerRegistryManagementClient(
            self.credentials, self.subscription_id)
        self.sql_client = SqlManagementClient(self.credentials,
                                              self.subscription_id)
        self.dns_client = DnsManagementClient(self.credentials,
                                              self.subscription_id)
Esempio n. 7
0
def _get_acr_username_password(subscription,
                               resource_group,
                               acr_name,
                               service_principal_authentication,
                               password_id=0):
    """
    Use the ACR management SDK to retrieve ACR username and password

    :param subscription:
    :param resource_group:
    :param acr_name:
    :param service_principal_authentication:
    :param password_id:
    :return:
    """
    credentials = ContainerRegistryManagementClient(service_principal_authentication, subscription) \
        .registries \
        .list_credentials(resource_group, acr_name)
    return credentials.username, credentials.passwords[password_id].value
def import_image(authority, repository, tags):
    logger.warning("Import image authority: {}".format(authority))
    credential = ClientSecretCredential(
        tenant_id=os.environ["CONTAINERREGISTRY_TENANT_ID"],
        client_id=os.environ["CONTAINERREGISTRY_CLIENT_ID"],
        client_secret=os.environ["CONTAINERREGISTRY_CLIENT_SECRET"],
        authority=authority)
    sub_id = os.environ["CONTAINERREGISTRY_SUBSCRIPTION_ID"]
    base_url = get_base_url(authority)
    audience = [base_url.endpoints.resource_manager + "/.default"]
    mgmt_client = ContainerRegistryManagementClient(
        credential,
        sub_id,
        api_version="2019-05-01",
        base_url=base_url.endpoints.resource_manager,
        credential_scopes=audience)
    logger.warning("LOGGING: {}{}".format(
        os.environ["CONTAINERREGISTRY_SUBSCRIPTION_ID"],
        os.environ["CONTAINERREGISTRY_TENANT_ID"]))
    registry_uri = "registry.hub.docker.com"
    rg_name = os.environ["CONTAINERREGISTRY_RESOURCE_GROUP"]
    registry_name = os.environ["CONTAINERREGISTRY_REGISTRY_NAME"]

    import_source = ImportSource(source_image=repository,
                                 registry_uri=registry_uri)

    import_params = ImportImageParameters(mode=ImportMode.Force,
                                          source=import_source,
                                          target_tags=tags)

    result = mgmt_client.registries.begin_import_image(
        rg_name,
        registry_name,
        parameters=import_params,
    )

    while not result.done():
        pass

    # Do the same for anonymous
    mgmt_client = ContainerRegistryManagementClient(
        credential,
        sub_id,
        api_version="2019-05-01",
        base_url=base_url.endpoints.resource_manager,
        credential_scopes=audience)
    registry_uri = "registry.hub.docker.com"
    rg_name = os.environ["CONTAINERREGISTRY_RESOURCE_GROUP"]
    registry_name = os.environ["CONTAINERREGISTRY_ANONREGISTRY_NAME"]

    import_source = ImportSource(source_image=repository,
                                 registry_uri=registry_uri)

    import_params = ImportImageParameters(mode=ImportMode.Force,
                                          source=import_source,
                                          target_tags=tags)

    result = mgmt_client.registries.begin_import_image(
        rg_name,
        registry_name,
        parameters=import_params,
    )

    while not result.done():
        pass
Esempio n. 9
0
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    PIPELINE = "pipelinexxyyzz"
    REGISTRIES = "registriesxxyyzz"

    # Create client
    # # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    containerregistry_client = ContainerRegistryManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id=SUBSCRIPTION_ID,
        api_version="2019-12-01-preview")

    # Create resource group
    resource_client.resource_groups.create_or_update(GROUP_NAME,
                                                     {"location": "eastus"})

    # - init depended resources -
    registries = containerregistry_client.registries.begin_create(
        GROUP_NAME, REGISTRIES, {
            "location": "eastus",
            "tags": {
                "key": "value"
            },
            "sku": {
                "name": "Premium"
            },
            "admin_user_enabled": True
        }).result()
    # - end -

    # Create import pipeline
    pipeline = containerregistry_client.import_pipelines.begin_create(
        GROUP_NAME,
        REGISTRIES,
        PIPELINE,
        {
            "location":
            "eastus",
            "identity": {
                "type": "SystemAssigned"
                # "user_assigned_identities": {}
            },
            "source": {
                "type":
                "AzureStorageBlobContainer",
                "uri":
                "https://accountname.blob.core.windows.net/containername",
                "key_vault_uri":
                "https://myvault.vault.azure.net/secrets/acrimportsas"
            },
            "options":
            ["OverwriteTags", "DeleteSourceBlobOnSuccess", "ContinueOnErrors"]
        }).result()
    print("Create import pipeline:\n{}".format(pipeline))

    # Create export pipeline
    pipeline = containerregistry_client.export_pipelines.begin_create(
        GROUP_NAME, REGISTRIES, PIPELINE, {
            "location": "eastus",
            "identity": {
                "type": "SystemAssigned"
            },
            "target": {
                "type":
                "AzureStorageBlobContainer",
                "uri":
                "https://accountname.blob.core.windows.net/containername",
                "key_vault_uri":
                "https://myvault.vault.azure.net/secrets/acrexportsas"
            },
            "options": ["OverwriteBlobs"]
        }).result()
    print("Create import pipeline:\n{}".format(pipeline))

    # Get import pipeline
    pipeline = containerregistry_client.import_pipelines.get(
        GROUP_NAME, REGISTRIES, PIPELINE)
    print("Get import pipeline:\n{}".format(pipeline))

    # Get export pipeline
    pipeline = containerregistry_client.export_pipelines.get(
        GROUP_NAME, REGISTRIES, PIPELINE)
    print("Get export pipeline:\n{}".format(pipeline))

    # Delete import pipeline
    pipeline = containerregistry_client.import_pipelines.begin_delete(
        GROUP_NAME, REGISTRIES, PIPELINE).result()
    print("Delete import pipeline.\n")

    # Delete export pipeline
    pipeline = containerregistry_client.export_pipelines.begin_delete(
        GROUP_NAME, REGISTRIES, PIPELINE).result()
    print("Delete export pipeline.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()
Esempio n. 10
0
container_reg = ws.get_details()["containerRegistry"]
reg_name = container_reg.split("/")[-1]
container_url = "\"" + image.image_location + "\","
subscription_id = ws.subscription_id
resource_group_name = ws.resource_group

print('Image location: {}'.format(image.image_location))
print('Register name: {}'.format(reg_name))
print('Subscription: {}'.format(subscription_id))
print('Resource group: {}'.format(resource_group_name))

from azure.mgmt.containerregistry import ContainerRegistryManagementClient
from azure.mgmt import containerregistry

client = ContainerRegistryManagementClient(ws._auth, subscription_id)
result = client.registries.list_credentials(resource_group_name,
                                            reg_name,
                                            custom_headers=None,
                                            raw=False)
username = result.username
password = result.passwords[0].value

#%%
with open('DeployContainerFromAML/.env', 'w') as env_file:
    env_file.write("MODULE_NAME={}\n".format(cfg.MODULE_NAME))
    env_file.write("REGISTRY_NAME={}\n".format(reg_name))
    env_file.write("REGISTRY_USER_NAME={}\n".format(username))
    env_file.write("REGISTRY_PASSWORD={}\n".format(password))
    env_file.write("REGISTRY_IMAGE_LOCATION={}\n".format(image.image_location))
Esempio n. 11
0
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    WEBHOOK = "webhookxxyyzz"
    REGISTRIES = "registriesxxyyzz"

    # Create client
    # # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id=SUBSCRIPTION_ID
    )
    containerregistry_client = ContainerRegistryManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id=SUBSCRIPTION_ID
    )

    # Create resource group
    resource_client.resource_groups.create_or_update(
        GROUP_NAME,
        {"location": "eastus"}
    )

    # - init depended resources -
    registries = containerregistry_client.registries.begin_create(
        GROUP_NAME,
        REGISTRIES,
        {
          "location": "eastus",
          "tags": {
            "key": "value"
          },
          "sku": {
            "name": "Standard"
          },
          "admin_user_enabled": True
        }
    ).result()
    # - end -

    # Create webhook
    webhook = containerregistry_client.webhooks.begin_create(
        GROUP_NAME,
        REGISTRIES,
        WEBHOOK,
        {
          "location": "eastus",
          "service_uri": "http://www.microsoft.com",
          "status": "enabled",
          "actions": [
            "push"
          ]
        }
    ).result()
    print("Create webhook:\n{}".format(webhook))

    # Get webhook
    webhook = containerregistry_client.webhooks.get(
        GROUP_NAME,
        REGISTRIES,
        WEBHOOK
    )
    print("Get webhook:\n{}".format(webhook))

    # Update webhook
    webhook = containerregistry_client.webhooks.begin_update(
        GROUP_NAME,
        REGISTRIES,
        WEBHOOK,
        {
          "location": "eastus",
          "service_uri": "http://www.microsoft.com",
          "status": "enabled",
          "actions": [
            "push"
          ]

        }
    ).result()
    print("Update webhook:\n{}".format(webhook))
    
    # Delete webhook
    webhook = containerregistry_client.webhooks.begin_delete(
        GROUP_NAME,
        REGISTRIES,
        WEBHOOK
    ).result()
    print("Delete webhook.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(
        GROUP_NAME
    ).result()
Esempio n. 12
0
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    TASK = "taskxxyyzz"
    REGISTRIES = "registriesxxyyzz"

    # Create client
    # # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    containerregistry_client = ContainerRegistryManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id=SUBSCRIPTION_ID,
        api_version="2019-12-01-preview")

    # Create resource group
    resource_client.resource_groups.create_or_update(GROUP_NAME,
                                                     {"location": "eastus"})

    # - init depended resources -
    registries = containerregistry_client.registries.begin_create(
        GROUP_NAME, REGISTRIES, {
            "location": "eastus",
            "tags": {
                "key": "value"
            },
            "sku": {
                "name": "Premium"
            },
            "admin_user_enabled": True
        }).result()
    # - end -

    # Create task
    task = containerregistry_client.tasks.begin_create(
        GROUP_NAME, REGISTRIES, TASK, {
            "location": "eastus",
            "tags": {
                "testkey": "value"
            },
            "status": "Enabled",
            "platform": {
                "os": "Linux",
                "architecture": "amd64"
            },
            "agent_configuration": {
                "cpu": "2"
            },
            "step": {
                "type": "Docker",
                "context_path":
                "https://github.com/SteveLasker/node-helloworld",
                "image_names": ["testtask:v1"],
                "docker_file_path": "DockerFile",
                "is_push_enabled": True,
                "no_cache": False,
            },
            "trigger": {
                "base_image_trigger": {
                    "name": "myBaseImageTrigger",
                    "base_image_trigger_type": "Runtime",
                    "update_trigger_payload_type": "Default",
                    "status": "Enabled"
                }
            }
        }).result()
    print("Create task:\n{}".format(task))

    # Get task
    task = containerregistry_client.tasks.get(GROUP_NAME, REGISTRIES, TASK)
    print("Get task:\n{}".format(task))

    # Update task
    task = containerregistry_client.tasks.begin_update(
        GROUP_NAME, REGISTRIES, TASK, {
            "location": "eastus",
            "tags": {
                "testkey": "value"
            },
            "status": "Enabled",
            "platform": {
                "os": "Linux",
                "architecture": "amd64"
            },
            "agent_configuration": {
                "cpu": "2"
            },
            "step": {
                "type": "Docker",
                "context_path":
                "https://github.com/SteveLasker/node-helloworld",
                "image_names": ["testtask:v1"],
                "docker_file_path": "DockerFile",
                "is_push_enabled": True,
                "no_cache": False,
            },
            "trigger": {
                "base_image_trigger": {
                    "name": "myBaseImageTrigger",
                    "base_image_trigger_type": "Runtime",
                    "update_trigger_payload_type": "Default",
                    "status": "Enabled"
                }
            }
        }).result()
    print("Update task:\n{}".format(task))

    # Delete task
    task = containerregistry_client.tasks.begin_delete(GROUP_NAME, REGISTRIES,
                                                       TASK).result()
    print("Delete task.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()
Esempio n. 13
0
 def delete_registry(self, auth, name, resource_group, subscription_id):
     client = ContainerRegistryManagementClient(auth, subscription_id)
     return client.registries.delete(resource_group, name).result()
Esempio n. 14
0
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    SCOPE_MAP = "scopemapxxyyzz"
    REGISTRIES = "registriesxxyyzz"

    # Create client
    # # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    containerregistry_client = ContainerRegistryManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id=SUBSCRIPTION_ID,
        api_version="2019-12-01-preview")

    # Create resource group
    resource_client.resource_groups.create_or_update(GROUP_NAME,
                                                     {"location": "eastus"})

    # - init depended resources -
    registries = containerregistry_client.registries.begin_create(
        GROUP_NAME, REGISTRIES, {
            "location": "eastus",
            "tags": {
                "key": "value"
            },
            "sku": {
                "name": "Premium"
            },
            "admin_user_enabled": True
        }).result()
    # - end -

    # Create scope map
    scope_map = containerregistry_client.scope_maps.begin_create(
        GROUP_NAME, REGISTRIES, SCOPE_MAP, {
            "description":
            "Developer Scopes",
            "actions": [
                "repositories/foo/content/read",
                "repositories/foo/content/delete"
            ]
        }).result()
    print("Create scope map:\n{}".format(scope_map))

    # Get scope map
    scope_map = containerregistry_client.scope_maps.get(
        GROUP_NAME, REGISTRIES, SCOPE_MAP)
    print("Get scope map:\n{}".format(scope_map))

    # Update scope map
    scope_map = containerregistry_client.scope_maps.begin_update(
        GROUP_NAME, REGISTRIES, SCOPE_MAP, {
            "description":
            "Developer Scopes",
            "actions": [
                "repositories/foo/content/read",
                "repositories/foo/content/delete"
            ]
        }).result()
    print("Update scope map:\n{}".format(scope_map))

    # Delete scope map
    scope_map = containerregistry_client.scope_maps.begin_delete(
        GROUP_NAME, REGISTRIES, SCOPE_MAP).result()
    print("Delete scope map.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()
    def __init__(self, **kwargs):
        self.attributes = {
            'user': '******',
            'dockerfile_ext': None,
            'registry_version': 'v2',
            'deploy': False
        }
        self.logger = logging.get_logger(self.__class__.__name__)
        self.attributes.update(kwargs)
        if 'dockerfile_ext' in kwargs:
            self.attributes['dockerfile'] = "Dockerfile.{}".format(
                kwargs['dockerfile_ext'])
        else:
            self.attributes['dockerfile'] = "Dockerfile"

        self.task = self.attributes['task']
        self.attributes['app_main'] = self.attributes['cluster_config'][
            'APP_MAIN']
        self.attributes['user'] = self.attributes['cluster_config'][
            'APP_DATACENTER']
        self.app_main = self.attributes['app_main']
        self.attributes['datacenter'] = self.attributes['cluster_config'][
            'APP_DATACENTER']
        self.datacenter = self.attributes['datacenter']
        self.docker_user = self.attributes['cluster_config']['APP_DATACENTER']
        self.app_docker_registry = "{}acr{}.azurecr.io".format(
            self.attributes['cluster_config']['RESOURCE_GROUP_PREFIX'],
            self.datacenter)
        self.resource_group_prefix = self.attributes['cluster_config'][
            'RESOURCE_GROUP_PREFIX']
        self.resource_group = "{}-{}".format(self.resource_group_prefix,
                                             self.datacenter)
        self.attributes['commit'] = self._get_git_commit()
        self.attributes['datetime'] = self._get_utcnow()

        try:
            if ('AZURE_CLIENT_ID' in os.environ
                    and 'AZURE_CLIENT_SECRET' in os.environ
                    and 'AZURE_TENANT_ID' in os.environ
                    and 'AZURE_SUBSCRIPTION_ID' in os.environ):

                self.__dict__.update({
                    'subscription_id':
                    os.environ['AZURE_SUBSCRIPTION_ID'],
                    'client_id':
                    os.environ['AZURE_CLIENT_ID'],
                    'client_secret':
                    os.environ['AZURE_CLIENT_SECRET'],
                    'tenant_id':
                    os.environ['AZURE_TENANT_ID']
                })
            else:
                current_token_filename = os.path.join(
                    os.path.expanduser("~"), ".joara",
                    "{}.pickle".format(self.resource_group))
                read_from_cache = os.path.isfile(current_token_filename)

                if (read_from_cache):
                    azure_credential = pickle.load(
                        open(current_token_filename, "rb"))
                    self.client_id = azure_credential['AZURE_CLIENT_ID']
                    self.client_secret = azure_credential[
                        'AZURE_CLIENT_SECRET']
                    self.tenant_id = azure_credential['AZURE_TENANT_ID']
                    self.subscription_id = azure_credential[
                        'AZURE_SUBSCRIPTION_ID']

                os.environ['AZURE_CLIENT_ID'] = self.client_id
                os.environ['AZURE_CLIENT_SECRET'] = self.client_secret
                os.environ['AZURE_TENANT_ID'] = self.tenant_id
                os.environ['AZURE_SUBSCRIPTION_ID'] = self.subscription_id
        except Exception as e:
            logs = "### Please update your azure credentials under clusters.ini or to environment variables ###, {}".format(
                e)
            self.logger.error(logs)
            raise RuntimeError(logs)

        self.credentials = ServicePrincipalCredentials(
            client_id=self.client_id,
            secret=self.client_secret,
            tenant=self.tenant_id)

        self.client = ContainerRegistryManagementClient(
            self.credentials, self.subscription_id)

        if self.task == "build" or self.task == "push":
            if ('AZURE_CLIENT_ID' in os.environ
                    and 'AZURE_CLIENT_SECRET' in os.environ
                    and 'AZURE_TENANT_ID' in os.environ
                    and 'AZURE_SUBSCRIPTION_ID' in os.environ):
                storage_client = StorageManagementClient(
                    self.credentials, os.environ['AZURE_SUBSCRIPTION_ID'])

                storage_name = "{}{}".format(self.resource_group_prefix,
                                             self.datacenter)
                storage_keys = storage_client.storage_accounts.list_keys(
                    self.resource_group, storage_name)
                storage_keys = {v.key_name: v.value for v in storage_keys.keys}

                if storage_keys:
                    os.environ['AZURE_STORAGE_KEY'] = storage_keys['key1']
                    os.environ['AZURE_STORAGE_ACCOUNT'] = storage_name
                    run("az storage container create -n {}".format(
                        "imagesversion"))

            else:
                logs = "### Please update your azure credentials under clusters.ini or to environment variables ###, "
                self.logger.error(logs)
                raise RuntimeError(logs)

        if not self.attributes['image']:
            self.logger.error("Image name {} is not a valid".format(
                self.attributes['image']))
            sys.exit(1)

        if self.task == "build" or self.task == "push":
            run("az login -u {} -p {} --tenant {} --service-principal".format(
                os.environ['AZURE_CLIENT_ID'],
                os.environ['AZURE_CLIENT_SECRET'],
                os.environ['AZURE_TENANT_ID']))
            run("az acr login --name {}acr{}".format(
                self.resource_group_prefix, self.datacenter))
            #self._docker_login()
            self.attributes['version'] = self._get_next_version()

            self.attributes[
                'fqdi'] = "{registry}/{user}/{image}:{version}".format(
                    registry=self.app_docker_registry,
                    user=self.attributes['user'],
                    image=self.attributes['image'],
                    version=self.attributes['version'])
            self.version_manager = VersionManager(**self.__dict__)
Esempio n. 16
0
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    AGENT_POOL = "agentpoolxxyyzz"
    REGISTRIES = "registriesxxyyzz"

    # Create client
    # # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id=SUBSCRIPTION_ID
    )
    containerregistry_client = ContainerRegistryManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id=SUBSCRIPTION_ID,
        api_version="2019-12-01-preview"
    )

    # Create resource group
    resource_client.resource_groups.create_or_update(
        GROUP_NAME,
        {"location": "eastus"}
    )

    # - init depended resources -
    registries = containerregistry_client.registries.begin_create(
        GROUP_NAME,
        REGISTRIES,
        {
          "location": "eastus",
          "tags": {
            "key": "value"
          },
          "sku": {
            "name": "Premium"
          },
          "admin_user_enabled": True
        }
    ).result()
    # - end -

    # Create agent pool
    agent_pool = containerregistry_client.agent_pools.begin_create(
        GROUP_NAME,
        REGISTRIES,
        AGENT_POOL,
        {
          "location": "eastus",
          "tags": {
            "key": "value"
          },
          "count": "1",
          "tier": "S1",
          "os": "Linux"
        }
    ).result()
    print("Create agent pool:\n{}".format(agent_pool))

    # Get agent pool
    agent_pool = containerregistry_client.agent_pools.get(
        GROUP_NAME,
        REGISTRIES,
        AGENT_POOL
    )
    print("Get agent pool:\n{}".format(agent_pool))

    # Update agent pool
    agent_pool = containerregistry_client.agent_pools.begin_update(
        GROUP_NAME,
        REGISTRIES,
        AGENT_POOL,
        {
            "count": "1"
        }
    ).result()
    print("Update agent pool:\n{}".format(agent_pool))
    
    # Delete agent pool
    agent_pool = containerregistry_client.agent_pools.begin_delete(
        GROUP_NAME,
        REGISTRIES,
        AGENT_POOL
    ).result()
    print("Delete agent pool.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(
        GROUP_NAME
    ).result()
Esempio n. 17
0
def main():

    SUBSCRIPTION_ID = os.environ.get("SUBSCRIPTION_ID", None)
    GROUP_NAME = "testgroupx"
    TASK_RUN = "taskrunxxyyzz"
    REGISTRIES = "registriesxxyyzz"

    # Create client
    # # For other authentication approaches, please see: https://pypi.org/project/azure-identity/
    resource_client = ResourceManagementClient(
        credential=DefaultAzureCredential(), subscription_id=SUBSCRIPTION_ID)
    containerregistry_client = ContainerRegistryManagementClient(
        credential=DefaultAzureCredential(),
        subscription_id=SUBSCRIPTION_ID,
        api_version="2019-12-01-preview")

    # Create resource group
    resource_client.resource_groups.create_or_update(GROUP_NAME,
                                                     {"location": "eastus"})

    # - init depended resources -
    registries = containerregistry_client.registries.begin_create(
        GROUP_NAME, REGISTRIES, {
            "location": "eastus",
            "tags": {
                "key": "value"
            },
            "sku": {
                "name": "Premium"
            },
            "admin_user_enabled": True
        }).result()
    # - end -

    # Create task run
    task_run = containerregistry_client.task_runs.begin_create(
        GROUP_NAME, REGISTRIES, TASK_RUN, {
            "force_update_tag": "test",
            "run_request": {
                "type": "DockerBuildRequest",
                "image_names": ["testtaskrun:v1"],
                "is_push_enabled": True,
                "no_cache": False,
                "docker_file_path": "Dockerfile",
                "platform": {
                    "os": "linux",
                    "architecture": "amd64"
                },
                "source_location":
                "https://github.com/Azure-Samples/acr-build-helloworld-node.git",
                "is_archive_enabled": True
            }
        }).result()
    print("Create task run:\n{}".format(task_run))

    # Get task run
    task_run = containerregistry_client.task_runs.get(GROUP_NAME, REGISTRIES,
                                                      TASK_RUN)
    print("Get task run:\n{}".format(task_run))

    # Update task run
    task_run = containerregistry_client.task_runs.begin_update(
        GROUP_NAME, REGISTRIES, TASK_RUN, {
            "force_update_tag": "test",
            "run_request": {
                "type": "DockerBuildRequest",
                "image_names": ["testtaskrun:v1"],
                "is_push_enabled": True,
                "no_cache": False,
                "docker_file_path": "Dockerfile",
                "platform": {
                    "os": "linux",
                    "architecture": "amd64"
                },
                "source_location":
                "https://github.com/Azure-Samples/acr-build-helloworld-node.git",
                "is_archive_enabled": True
            }
        }).result()
    print("Update task run:\n{}".format(task_run))

    # Delete task run
    task_run = containerregistry_client.task_runs.begin_delete(
        GROUP_NAME, REGISTRIES, TASK_RUN).result()
    print("Delete task run.\n")

    # Delete Group
    resource_client.resource_groups.begin_delete(GROUP_NAME).result()