One place for hosting & domains

      How To Set Up the code-server Cloud IDE Platform on Ubuntu 20.04


      The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      With developer tools moving to the cloud, creation and adoption of cloud IDE (Integrated Development Environment) platforms is growing. Cloud IDEs allow for real-time collaboration between developer teams to work in a unified development environment that minimizes incompatibilities and enhances productivity. Accessible through web browsers, cloud IDEs are available from every type of modern device.

      code-server is Microsoft Visual Studio Code running on a remote server and accessible directly from your browser. Visual Studio Code is a modern code editor with integrated Git support, a code debugger, smart autocompletion, and customizable and extensible features. This means that you can use various devices running different operating systems, and always have a consistent development environment on hand.

      In this tutorial, you will set up the code-server cloud IDE platform on your Ubuntu 20.04 machine and expose it at your domain, secured with free Let’s Encrypt TLS certificates. In the end, you’ll have Microsoft Visual Studio Code running on your Ubuntu 20.04 server, available at your domain and protected with a password.

      Prerequisites

      • A server running Ubuntu 20.04 with at least 2GB RAM, root access, and a sudo, non-root account. You can set this up by following this initial server setup guide.

      • Nginx installed on your server. For a guide on how to do this, complete Steps 1 to 4 of How To Install Nginx on Ubuntu 20.04.

      • A fully registered domain name to host code-server, pointed to your server. This tutorial will use code-server.your-domain throughout. You can purchase a domain name on Namecheap, get one for free on Freenom, or use the domain registrar of your choice. For DigitalOcean, you can follow this introduction to DigitalOcean DNS for details on how to add them.

      Step 1 — Installing code-server

      In this section, you will set up code-server on your server. This entails downloading the latest version and creating a systemd service that will keep code-server always running in the background. You’ll also specify a restart policy for the service, so that code-server stays available after possible crashes or reboots.

      You’ll store all data pertaining to code-server in a folder named ~/code-server. Create it by running the following command:

      Navigate to it:

      You’ll need to head over to the Github releases page of code-server and pick the latest Linux build (the file will contain ‘linux’ in its name). At the time of writing, the latest version was 3.3.1. Download it using wget by running the following command:

      • wget https://github.com/cdr/code-server/releases/download/v3.3.1/code-server-3.3.1-linux-amd64.tar.gz

      Then, unpack the archive by running:

      • tar -xzvf code-server-3.3.1-linux-amd64.tar.gz

      You’ll get a folder named exactly as the original file you downloaded, which contains the code-server source code. Copy it to /usr/lib/code-server so you’ll be able to access it system wide by running the following command:

      • sudo cp -r code-server-3.3.1-linux-amd64 /usr/lib/code-server

      Then, create a symbolic link at /usr/bin/code-server, pointing to the code-server executable:

      • sudo ln -s /usr/lib/code-server/bin/code-server /usr/bin/code-server

      Next, create a folder for code-server, where it will store user data:

      • sudo mkdir /var/lib/code-server

      Now that you’ve downloaded code-server and made it available system-wide, you will create a systemd service to keep code-server running in the background at all times.

      You’ll store the service configuration in a file named code-server.service, in the /lib/systemd/system directory, where systemd stores its services. Create it using your text editor:

      • sudo nano /lib/systemd/system/code-server.service

      Add the following lines:

      /lib/systemd/system/code-server.service

      [Unit]
      Description=code-server
      After=nginx.service
      
      [Service]
      Type=simple
      Environment=PASSWORD=your_password
      ExecStart=/usr/bin/code-server --bind-addr 127.0.0.1:8080 --user-data-dir /var/lib/code-server --auth password
      Restart=always
      
      [Install]
      WantedBy=multi-user.target
      

      Here you first specify the description of the service. Then, you state that the nginx service must be started before this one. After the [Unit] section, you define the type of the service (simple means that the process should be simply run) and provide the command that will be executed.

      You also specify that the global code-server executable should be started with a few arguments specific to code-server. --bind-addr 127.0.0.1:8080 binds it to localhost at port 8080, so it’s only directly accessible from inside of your server. --user-data-dir /var/lib/code-server sets its user data directory, and --auth password specifies that it should authenticate visitors with a password, specified in the PASSWORD environment variable declared on the line above it.

      Remember to replace your_password with your desired password, then save and close the file.

      The next line tells systemd to restart code-server in all malfunction events (for example, when it crashes or the process is killed). The [Install] section orders systemd to start this service when it becomes possible to log in to your server.

      Start the code-server service by running the following command:

      • sudo systemctl start code-server

      Check that it’s started correctly by observing its status:

      • sudo systemctl status code-server

      You’ll see output similar to:

      Output

      ● code-server.service - code-server Loaded: loaded (/lib/systemd/system/code-server.service; disabled; vendor preset: enabled) Active: active (running) since Wed 2020-05-20 13:03:40 UTC; 12s ago Main PID: 14985 (node) Tasks: 18 (limit: 2345) Memory: 26.1M CGroup: /system.slice/code-server.service ├─14985 /usr/lib/code-server/bin/../lib/node /usr/lib/code-server/bin/.. --bind-addr 127.0.0.1:8080 --user-data-dir /var/lib/code-server --auth> └─15010 /usr/lib/code-server/lib/node /usr/lib/code-server --bind-addr 127.0.0.1:8080 --user-data-dir /var/lib/code-server --auth password May 20 13:03:40 code-server-update-2004 systemd[1]: Started code-server. May 20 13:03:40 code-server-update-2004 code-server[15010]: info Wrote default config file to ~/.config/code-server/config.yaml May 20 13:03:40 code-server-update-2004 code-server[15010]: info Using config file ~/.config/code-server/config.yaml May 20 13:03:40 code-server-update-2004 code-server[15010]: info Using user-data-dir /var/lib/code-server May 20 13:03:40 code-server-update-2004 code-server[15010]: info code-server 3.3.1 6f1309795e1cb930edba68cdc7c3dcaa01da0ab3 May 20 13:03:40 code-server-update-2004 code-server[15010]: info HTTP server listening on http://127.0.0.1:8080 May 20 13:03:40 code-server-update-2004 code-server[15010]: info - Using password from $PASSWORD May 20 13:03:40 code-server-update-2004 code-server[15010]: info - To disable use `--auth none` May 20 13:03:40 code-server-update-2004 code-server[15010]: info - Not serving HTTPS

      To make code-server start automatically after a server reboot, enable its service by running the following command:

      • sudo systemctl enable code-server

      In this step, you’ve downloaded code-server and made it available globally. Then, you’ve created a systemd service for it and enabled it, so code-server will start at every server boot. Next, you’ll expose it at your domain by configuring Nginx to serve as a reverse proxy between the visitor and code-server.

      Step 2 — Exposing code-server at Your Domain

      In this section, you will configure Nginx as a reverse proxy for code-server.

      As you have learned in the Nginx prerequisite step, its site configuration files are stored under /etc/nginx/sites-available and must later be symlinked to /etc/nginx/sites-enabled to become active.

      You’ll store the configuration for exposing code-server at your domain in a file named code-server.conf, under /etc/nginx/sites-available. Start off by creating it using your editor:

      • sudo nano /etc/nginx/sites-available/code-server.conf

      Add the following lines:

      /etc/nginx/sites-available/code-server.conf

      server {
          listen 80;
          listen [::]:80;
      
          server_name code-server.your-domain;
      
          location / {
            proxy_pass http://localhost:8080/;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection upgrade;
            proxy_set_header Accept-Encoding gzip;
          }
      }
      

      Replace code-server.your-domain with your desired domain, then save and close the file.

      In this file, you define that Nginx should listen to HTTP port 80. Then, you specify a server_name that tells Nginx for which domain to accept requests and apply this particular configuration. In the next block, for the root location (/), you specify that requests should be passed back and forth to code-server running at localhost:8080. The next three lines (starting with proxy_set_header) order Nginx to carry over some HTTP request headers that are needed for correct functioning of WebSockets, which code-server extensively uses.

      To make this site configuration active, you will need to create a symlink of it in the /etc/nginx/sites-enabled folder by running:

      • sudo ln -s /etc/nginx/sites-available/code-server.conf /etc/nginx/sites-enabled/code-server.conf

      To test the validity of the configuration, run the following command:

      You’ll see the following output:

      Output

      nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

      For the configuration to take effect, you’ll need to restart Nginx:

      • sudo systemctl restart nginx

      You now have your code-server installation accessible at your domain. In the next step, you’ll secure it by applying a free Let’s Encrypt TLS certificate.

      Step 3 — Securing Your Domain

      In this section, you will secure your domain using a Let’s Encrypt TLS certificate, which you’ll provision using Certbot.

      To install the latest version of Certbot and its Nginx plugin, run the following command:

      • sudo apt install certbot python3-certbot-nginx

      As part of the prerequisites, you have enabled ufw (Uncomplicated Firewall) and configured it to allow unencrypted HTTP traffic. To be able to access the secured site, you’ll need to configure it to accept encrypted traffic by running the following command:

      The output will be:

      Output

      Rule added Rule added (v6)

      Similarly to Nginx, you’ll need to reload it for the configuration to take effect:

      The output will show:

      Output

      Firewall reloaded

      Then, in your browser, navigate to the domain you used for code-server. You will see the code-server login prompt.

      code-server login prompt

      code-server is asking you for your password. Enter the one you set in the previous step and press Enter IDE. You’ll now enter code-server and immediately see its editor GUI.

      code-server GUI

      Now that you’ve checked that code-server is correctly exposed at your domain, you’ll install Let’s Encrypt TLS certificates to secure it, using Certbot.

      To request certificates for your domain, run the following command:

      • sudo certbot --nginx -d code-server.your-domain

      In this command, you run certbot to request certificates for your domain—you pass the domain name with the -d parameter. The --nginx flag tells it to automatically change Nginx site configuration to support HTTPS. Remember to replace code-server.your-domain with your domain name.

      If this is your first time running Certbot, you’ll be asked to provide an email address for urgent notices and to accept the EFF’s Terms of Service. Certbot will then request certificates for your domain from Let’s Encrypt. It will then ask you if you’d like to redirect all HTTP traffic to HTTPS:

      Output

      Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1: No redirect - Make no further changes to the webserver configuration. 2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for new sites, or if you're confident your site works on HTTPS. You can undo this change by editing your web server's configuration. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Select the appropriate number [1-2] then [enter] (press 'c' to cancel):

      It is recommended to select the second option in order to maximize security. After you input your selection, press ENTER.

      The output will be similar to this:

      Output

      IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/code-server.your-domain/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/code-server.your-domain/privkey.pem Your cert will expire on ... To obtain a new or tweaked version of this certificate in the future, simply run certbot again with the "certonly" option. To non-interactively renew *all* of your certificates, run "certbot renew" - Your account credentials have been saved in your Certbot configuration directory at /etc/letsencrypt. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal. - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le

      This means that Certbot has successfully generated TLS certificates and applied them to the Nginx configuration for your domain. You can now reload your code-server domain in your browser and observe a padlock to the left of the site address, which means that your connection is properly secured.

      Now that you have code-server accessible at your domain through a secured Nginx reverse proxy, you’re ready to review the user interface of code-server.

      Step 4 — Using the code-server Interface

      In this section, you’ll use some of the features of the code-server interface. Since code-server is Visual Studio Code running in the cloud, it has the same interface as the standalone desktop edition.

      On the left-hand side of the IDE, there is a vertical row of six buttons opening the most commonly used features in a side panel known as the Activity Bar.

      code-server GUI - Sidepanel

      This bar is customizable so you can move these views to a different order or remove them from the bar. By default, the first button opens the general menu in a dropdown, while the second view opens the Explorer panel that provides tree-like navigation of the project’s structure. You can manage your folders and files here—creating, deleting, moving, and renaming them as necessary. The next view provides access to a search and replace functionality.

      Following this, in the default order, is your view of the source control systems, like Git. Visual Studio code also supports other source control providers and you can find further instructions for source control work flows with the editor in this documentation.

      Git pane with context-menu open

      The debugger option on the Activity Bar provides all the common actions for debugging in the panel. Visual Studio Code comes with built-in support for the Node.js runtime debugger and any language that transpiles to Javascript. For other languages you can install extensions for the required debugger. You can save debugging configurations in the launch.json file.

      Debugger View with launch.json open

      The final view in the Activity Bar provides a menu to access available extensions on the Marketplace.

      code-server GUI - Tabs

      The central part of the GUI is your editor, which you can separate by tabs for your code editing. You can change your editing view to a grid system or to side-by-side files.

      Editor Grid View

      After creating a new file through the File menu, an empty file will open in a new tab, and once saved, the file’s name will be viewable in the Explorer side panel. Creating folders can be done by right clicking on the Explorer sidebar and clicking on New Folder. You can expand a folder by clicking on its name as well as dragging and dropping files and folders to upper parts of the hierarchy to move them to a new location.

      code-server GUI - New Folder

      You can gain access to a terminal by entering CTRL+SHIFT+`, or by clicking on Terminal in the upper menu dropdown, and selecting New Terminal. The terminal will open in a lower panel and its working directory will be set to the project’s workspace, which contains the files and folders shown in the Explorer side panel.

      You’ve explored a high-level overview of the code-server interface and reviewed some of the most commonly used features.

      Conclusion

      You now have code-server, a versatile cloud IDE, installed on your Ubuntu 20.04 server, exposed at your domain and secured using Let’s Encrypt certificates. You can now work on projects individually, as well as in a team-collaboration setting. Running a cloud IDE frees resources on your local machine and allows you to scale the resources when needed. For further information, see the Visual Studio Code documentation for additional features and detailed instructions on other components of code-server.

      If you would like to run code-server on your DigitalOcean Kubernetes cluster check out our tutorial on How To Set Up the code-server Cloud IDE Platform on DigitalOcean Kubernetes.



      Source link

      Comment configurer la plate-forme Eclipse Theia Cloud IDE sur DigitalOcean Kubernetes


      L’auteur a choisi le Free and Open Source Fund pour recevoir une donation dans le cadre du programme Write for DOnations.

      Introduction

      Avec la migration des outils de développement vers le cloud, la création et l’adoption de plateformes IDE (Integrated Development Environment) en nuage se développent. Les IDE cloud sont accessibles depuis chaque type de dispositif moderne via les navigateurs web, et ils offrent de nombreux avantages pour les scénarios de collaboration en temps réel. Travailler dans un IDE cloud fournit un environnement de développement et de test unifié pour vous et votre équipe, tout en minimisant les incompatibilités de plate-forme. Parce qu’ils sont basés nativement sur les technologies cloud, ils sont capables d’utiliser le cluster pour réaliser des tâches qui peuvent largement dépasser la puissance et la fiabilité d’un seul ordinateur de développement.

      Eclipse Theia est un IDE cloud extensible fonctionnant sur un serveur distant et accessible depuis un navigateur web. Visuellement, il est conçu pour ressembler et se comporter de manière similaire à Microsoft Visual Studio Code, ce qui signifie qu’il prend en charge de nombreuses langues de programmation, dispose d’un schéma flexible et d’un terminal intégré. Ce qui différencie Eclipse Theia d’autres logiciels IDE cloud est son extensibilité ; il peut être modifié en utilisant des extensions personnalisées, ce qui vous permet de créer un IDE cloud adapté à vos besoins.

      Dans ce tutoriel, vous allez configurer la version par défaut de la plateforme Eclipse Theia cloud IDE sur votre cluster DigitalOcean Kubernetes et l’exposer à votre domaine, sécurisé par des certificats Let’s Encrypt et exigeant que le visiteur s’authentifie. Au bout du compte, vous disposerez d’Eclipse Theia sur cluster Kubernetes, disponible via HTTPS et exigeant que le visiteur se connecte.

      Conditions préalables

      • Un cluster DigitalOcean Kubernetes avec votre connexion configurée comme kubectl par défaut. Les instructions sur la façon de configurer kubectl sont indiquées dans l’étape Se connecter à votre cluster lorsque vous créez votre cluster. Pour créer un cluster Kubernetes sur DigitalOcean, voir notre Kubernetes Quickstart.

      • Le gestionnaire de paquets Helm installé sur votre machine locale, et Tiller installé sur votre cluster. Pour ce faire, suivez les étapes 1 et 2 du tutoriel Comment installer un logiciel sur les clusters de Kubernetes avec le gestionnaire de paquets de Helm.

      • Le Nginx Ingress Controller et le Cert Manager installés sur votre cluster en utilisant Helm afin d’exposer Eclipse Theia en utilisant Ingress Resources. Pour ce faire, suivez Comment configurer une entrée Nginx sur DigitalOcean Kubernetes en utilisant Helm.

      • Un nom de domaine entièrement enregistré pour héberger Eclipse Theia. Ce tutoriel utilisera theia.your-domain tout au long du cours. Vous pouvez acheter un nom de domaine sur Namecheap, en obtenir un gratuitement sur Freenom, ou utiliser le bureau d’enregistrement de domaine de votre choix.

      Étape 1 — Installation et exposition d’Eclipse Theia

      Pour commencer, vous allez installer Eclipse Theia sur votre cluster DigitalOcean Kubernetes. Ensuite, vous allez l’exposer au domaine de votre choix en utilisant une entrée Nginx.

      Comme vous avez créé deux exemples de déploiements et une ressource comme faisant partie des conditions préalables, vous pouvez les supprimer librement en exécutant les commandes suivantes :

      • kubectl delete -f hello-kubernetes-ingress.yaml
      • kubectl delete -f hello-kubernetes-first.yaml
      • kubectl delete -f hello-kubernetes-second.yaml

      Pour les besoins de ce tutoriel, vous allez stocker la configuration du déploiement sur votre machine locale, dans un fichier nommé eclipse-theia.yaml. Créez-le en utilisant la commande suivante :

      Ajoutez les lignes suivantes au fichier :

      eclipse-theia.yaml

      apiVersion: v1
      kind: Namespace
      metadata:
        name: theia
      ---
      apiVersion: networking.k8s.io/v1beta1
      kind: Ingress
      metadata:
        name: theia-next
        namespace: theia
        annotations:
          kubernetes.io/ingress.class: nginx
      spec:
        rules:
        - host: theia.your_domain
          http:
            paths:
            - backend:
                serviceName: theia-next
                servicePort: 80
      ---
      apiVersion: v1
      kind: Service
      metadata:
       name: theia-next
       namespace: theia
      spec:
       ports:
       - port: 80
         targetPort: 3000
       selector:
         app: theia-next
      ---
      apiVersion: apps/v1
      kind: Deployment
      metadata:
        labels:
          app: theia-next
        name: theia-next
        namespace: theia
      spec:
        selector:
          matchLabels:
            app: theia-next
        replicas: 1
        template:
          metadata:
            labels:
              app: theia-next
          spec:
            containers:
            - image: theiaide/theia:next
              imagePullPolicy: Always
              name: theia-next
              ports:
              - containerPort: 3000
      

      Cette configuration définit un espace de noms, un déploiement, un service et une Ingress (entrée réseau). L’espace de noms est appelé theia et contiendra tous les objets Kubernetes liés à Eclipse Theia, séparés du reste du cluster. Le déploiement consiste en un exemple de l’image Docker theiaide/theia:next avec le port 3000 exposé sur le conteneur. Le service recherche le déploiement et renvoie le port conteneur au port HTTP habituel, 80, permettant l’accès in-cluster à Eclipse Theia.

      L’Ingress contient une règle pour servir le service au port 80 en externe sur le domaine de votre choix. Dans ses annotations, vous spécifiez que le Nginx Ingress Controller doit être utilisé pour le traitement de la requête. N’oubliez pas de remplacer theia.votre_domaine par le domaine souhaité (que vous avez pointé vers l’équilibreur de charge de votre cluster), puis enregistrez et fermez le fichier.

      Enregistrez et quittez le fichier.

      Ensuite, créez la configuration dans Kubernetes en exécutant la commande suivante :

      • kubectl create -f eclipse-theia.yaml

      Vous verrez la sortie suivante :

      Output

      namespace/theia created ingress.networking.k8s.io/theia-next created service/theia-next created deployment.apps/theia-next created

      Vous pouvez voir la création du module Eclipse Theia en exécutant :

      • kubectl get pods -w -n theia

      La sortie finale ressemblera à ceci :

      Output

      NAME READY STATUS RESTARTS AGE theia-next-847d8c8b49-jt9bc 0/1 ContainerCreating 0 22s

      Après un certain temps, le statut va passer à RUNNING, ce qui signifie que vous avez bien installé Eclipse Theia sur votre cluster.

      Naviguez vers votre domaine dans votre navigateur. Vous verrez l’interface graphique par défaut de l’éditeur Eclipse Theia.

      Interface graphique par défaut de l'éditeur Eclipse Theia.

      Vous avez déployé Eclipse Theia sur votre cluster Kubernetes DigitalOcean et l’avez exposé au domaine de votre choix avec une Ingress. Ensuite, vous allez sécuriser l’accès à votre déploiement Eclipse Theia en activant l’authentification de la connexion.

      Étape 2 — Activation de l’authentification de la connexion pour votre domaine

      Dans cette étape, vous allez activer l’authentification du nom d’utilisateur et du mot de passe pour le déploiement d’Eclipse Theia. Vous y parviendrez en établissant d’abord une liste de combinaisons de connexion valides à l’aide de l’utilitaire htpasswd. Ensuite, vous créerez un secret Kubernetes contenant cette liste et configurerez l’entrée pour authentifier les visiteurs en fonction de celle-ci. En fin de compte, votre domaine ne sera accessible que lorsque le visiteur entrera une combinaison de nom d’utilisateur et de mot de passe valide. Cela empêchera les invités et autres visiteurs indésirables d’accéder à Eclipse Theia.

      L’utilitaire htpasswd vient du serveur web Apache et est utilisé pour créer des fichiers qui stockent les listes des combinaisons d’identifiants. Le format des fichiers htpasswd est une combinaison username:hashed_password par ligne, ce qui correspond au format attendu par le Nginx Ingress Controller pour la liste.

      Commencez par installer htpasswd sur votre système en exécutant la commande suivante :

      • sudo apt install apache2-utils -y

      Vous allez stocker la liste dans un fichier appelé auth. Créez-le en exécutant :

      Ce fichier doit être nommé auth parce que le Nginx Ingress Controller s’attend à ce que le secret contienne une clé appelée data.auth. S’il est manquant, le contrôleur renverra l’état HTTP 503 Service Indisponible.

      Ajoutez une combinaison nom d’utilisateur et mot de passe à auth en exécutant la commande suivante :

      N’oubliez pas de remplacer username par le nom d’utilisateur de votre choix. Un mot de passe vous sera demandé et la combinaison sera ajoutée dans le fichier auth. Vous pouvez répéter cette commande pour le nombre d’utilisateurs que vous souhaitez ajouter.

      Remarque : si le système sur lequel vous travaillez n’a pas de htpasswd installé, vous pouvez utiliser une version Dockerisée à la place.

      Vous devrez avoir Docker installé sur votre machine. Pour obtenir des instructions sur la façon de procéder, consultez les documents officiels.

      Exécutez la commande suivante pour utiliser une version dockerisée :

      • docker run --rm -it httpd htpasswd -n <username>

      N’oubliez pas de remplacer <username> par le nom d’utilisateur que vous voulez utiliser. Un mot de passe vous sera demandé. La combinaison hachée de login sera écrite sur la console, et vous devrez l’ajouter manuellement à la fin du fichier auth. Répétez ce processus pour le nombre de logins que vous souhaitez ajouter.

      Lorsque vous avez terminé, créez un nouveau secret dans Kubernetes avec le contenu du fichier, en exécutant la commande suivante :

      • kubectl create secret generic theia-basic-auth --from-file=auth -n theia

      Vous pouvez voir le secret avec :

      • kubectl get secret theia-basic-auth -o yaml -n theia

      La sortie ressemblera à :

      Output

      apiVersion: v1 data: auth: c2FtbXk6JGFwcjEkVFMuSDdyRWwkaFNSNWxPbkc0OEhncmpGZVFyMzEyLgo= kind: Secret metadata: creationTimestamp: "..." name: theia-basic-auth namespace: default resourceVersion: "10900" selfLink: /api/v1/namespaces/default/secrets/theia-basic-auth uid: 050767b9-8823-4fd3-b498-5f11074f768b type: Opaque

      Ensuite, vous devrez modifier l’Ingress pour qu’elle utilise le secret. Ouvrez la configuration du déploiement pour modification :

      Ajoutez les lignes surlignées à votre fichier :

      eclipse-theia.yaml

      apiVersion: v1
      kind: Namespace
      metadata:
        name: theia
      ---
      apiVersion: networking.k8s.io/v1beta1
      kind: Ingress
      metadata:
        name: theia-next
        namespace: theia
        annotations:
          kubernetes.io/ingress.class: nginx
          nginx.ingress.kubernetes.io/auth-type: basic
          nginx.ingress.kubernetes.io/auth-secret: theia-basic-auth
          nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required - Eclipse Theia'
      spec:
        rules:
        - host: theia.your_domain
          http:
            paths:
            - backend:
                serviceName: theia-next
                servicePort: 80
      ...
      

      Tout d’abord, dans l’annotation auth-type​​​1​​​, vous spécifiez que le type d’authentification est basic. Cela signifie que Nginx demandera à l’utilisateur de saisir un nom d’utilisateur et un mot de passe. Ensuite, dans auth-secret, vous spécifiez que le secret qui contient la liste des combinaisons valables est theia-basic-auth, que vous venez de créer. L’annotation auth-realm restante spécifie un message qui sera montré à l’utilisateur pour expliquer pourquoi l’authentification est nécessaire.  Vous pouvez changer le message contenu dans ce champ à votre convenance.

      Enregistrez et fermez le fichier.

      Pour propager les changements à votre cluster, exécutez la commande suivante :

      • kubectl apply -f eclipse-theia.yaml

      Vous verrez la sortie :

      Output

      namespace/theia unchanged ingress.networking.k8s.io/theia-next configured service/theia-next unchanged deployment.apps/theia-next unchanged

      Accédez à votre domaine dans votre navigateur, où il vous sera demandé de vous connecter.

      Vous avez activé l’authentification de base sur votre Ingress en le configurant pour utiliser le secret contenant les combinaisons hachées de nom d’utilisateur et de mot de passe. Dans l’étape suivante, vous allez sécuriser davantage l’accès en ajoutant des certificats TLS, afin que le trafic entre vous et votre déploiement Eclipse Theia reste crypté.

      Étape 3 — Appliquer les certificats HTTPS Let’s Encrypt

      Maintenant,vous allez sécuriser votre installation Eclipse Theia en appliquant des certificats Let’s Encrypt à votre Ingress, que Cert-Manager fournira automatiquement. Après avoir terminé cette étape, votre installation Eclipse Theia sera accessible via HTTPS.

      Ouvrez eclipse-theia.yaml​​​​ pour le modifier :

      Ajoutez les lignes surlignées à votre fichier, en veillant à remplacer l’espace réservé au domaine par le vôtre :

      eclipse-theia.yaml

      apiVersion: v1
      kind: Namespace
      metadata:
        name: theia
      ---
      apiVersion: networking.k8s.io/v1beta1
      kind: Ingress
      metadata:
        name: theia-next
        namespace: theia
        annotations:
          kubernetes.io/ingress.class: nginx
          nginx.ingress.kubernetes.io/auth-type: basic
          nginx.ingress.kubernetes.io/auth-secret: theia-basic-auth
          nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required - Eclipse Theia'
          cert-manager.io/cluster-issuer: letsencrypt-prod
      spec:
        tls:
        - hosts:
          - theia.your_domain
          secretName: theia-prod
        rules:
        - host: theia.your_domain
          http:
            paths:
            - backend:
                serviceName: theia-next
                servicePort: 80
      ...
      

      Tout d’abord, vous spécifiez le ClusterIssuer letsencrypt-prod que vous avez créé dans le cadre des conditions préalables en tant qu’émetteur ; il sera utilisé dans le but de fournir des certificats pour cette Ingress. Ensuite, dans la section tls, vous spécifiez le domaine exact qui doit être sécurisé, ainsi qu’un nom pour un secret qui détiendra ces certificats.

      Enregistrez et quittez le fichier.

      Appliquez les changements à votre cluster en exécutant la commande suivante :

      • kubectl apply -f eclipse-theia.yaml

      La sortie ressemblera à :

      Output

      namespace/theia unchanged ingress.networking.k8s.io/theia-next configured service/theia-next unchanged deployment.apps/theia-next unchanged

      Il faudra quelques minutes pour que les certificats soient provisionnés et entièrement appliqués. Vous pouvez suivre les progrès en observant la sortie de la commande suivante :

      • kubectl describe certificate theia-prod -n theia

      Lorsque ce sera terminé, la fin de la sortie ressemblera à ceci :

      Output

      ... Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal GeneratedKey 42m cert-manager Generated a new private key Normal Requested 42m cert-manager Created new CertificateRequest resource "theia-prod-3785736528" Normal Issued 42m cert-manager Certificate issued successfully

      Rafraîchissez votre domaine dans votre navigateur. Vous verrez un cadenas vert à l’extrémité gauche de la barre d’adresse, ce qui signifie que la connexion est sécurisée.

      Vous avez configuré l’Ingress pour utiliser les certificats Let’s Encrypt, ce qui rend votre déploiement Eclipse Theia plus sécurisé. Vous pouvez maintenant revoir l’interface utilisateur par défaut d’Eclipse Theia.

      Étape 4 — Utilisation de l’interface d’Eclipse Theia

      Dans cette section, vous allez explorer certaines des caractéristiques de l’interface d’Eclipse Theia.

      Sur le côté gauche de l’IDE, se trouve une rangée verticale de quatre boutons qui ouvrent les caractéristiques les plus couramment utilisées dans un panneau latéral.

      Interface graphique Eclipse Theia - Panneau latéral

      Cette barre est personnalisable, de sorte que vous pouvez modifier l’ordre de ces vues ou les retirer de la barre. Par défaut, la première vue ouvre le panneau de l’explorateur, qui permet une navigation arborescente de la structure du projet. Vous pouvez gérer vos dossiers et fichiers ici – en les créant, les supprimant, les déplaçant et les renommant si nécessaire.

      Après avoir créé un nouveau fichier via le menu Fichier, vous verrez un fichier vide ouvert dans un nouvel onglet. Une fois que vous l’aurez enregistré, vous pourrez visualiser son nom dans le panneau latéral de l’explorateur. Pour créer des dossiers, faites un clic droit sur la barre latérale de l’explorateur et cliquez sur Nouveau dossier. Vous pouvez développer un dossier en cliquant sur son nom ainsi qu’en glissant et déposant des fichiers et des dossiers dans les parties supérieures de la hiérarchie afin de les déplacer vers un nouvel emplacement.

      Interface graphique Eclipse Theia - Nouveau dossier

      Les deux options suivantes donnent accès à la fonctionnalité de recherche et de remplacement. La suivante donne un aperçu des systèmes de contrôle de source que vous pourriez utiliser, tels que Git.

      La vue finale est l’option de débogage, qui fournit toutes les actions courantes de débogage dans le panneau. Vous pouvez enregistrer des configurations de débogage dans le fichier launch.json

      Debugger View avec launch.json ouvert

      La partie centrale de l’interface graphique est votre éditeur, que vous pouvez séparer en onglets pour éditer votre code. Vous pouvez modifier votre vue d’édition en un système de grille ou en fichiers côte à côte. Comme tous les IDE modernes, Eclipse Theia prend en charge la surbrillance syntaxique de votre code.

      Vue de l'éditeur sous forme de grille

      Vous pouvez accéder à un terminal en tapant CTRL+SHIFT+` ou en cliquant sur Terminal dans le menu supérieur, et en sélectionnant Nouveau terminal. Le terminal s’ouvrira dans un panneau inférieur et son répertoire de travail sera défini sur l’espace de travail du projet, qui contient les fichiers et les dossiers affichés dans le panneau latéral de l’explorateur.

      Terminal ouvert

      Vous avez exploré un aperçu de haut niveau de l’interface Eclipse Theia et examiné certaines des caractéristiques les plus couramment utilisées.

      Conclusion

      Vous disposez maintenant d’Eclipse Theia, un IDE cloud polyvalent, installé sur votre cluster DigitalOcean Kubernetes. Vous l’avez sécurisé avec un certificat gratuit Let’s Encrypt TLS et vous avez configuré l’instance de façon à exiger des identifiants de connexion de la part du visiteur. Vous pouvez travailler avec lui sur votre code source et vos documents individuellement ou collaborer avec votre équipe. Vous pouvez également essayer de développer votre propre version d’Eclipse Theia si vous avez besoin de fonctionnalités supplémentaires. Pour plus d’informations sur la façon de procéder, consultez les docs Theia.



      Source link

      Como configurar a plataforma IDE na nuvem do Eclipse Theia no Ubuntu 18.04 [Início rápido]


      Introdução

      O Eclipse Theia é um IDE em nuvem extensível que executa em um servidor remoto, podendo ser acessado a partir de um navegador Web. Visualmente, ele foi projetado para parecer e se comportar de maneira similar ao Microsoft Visual Studio Code. O que separa o Eclipse Theia de outros softwares de IDE em nuvem é a sua extensibilidade; ele pode ser modificado com extensões personalizadas, o que permite que você crie um IDE em nuvem adequado às suas necessidades.

      Neste tutorial, você implantará o Eclipse Theia para seu servidor Ubuntu 18.04, usando o Docker Compose. Você irá expô-lo em seu domínio usando o nginx-proxy e o protegerá com um certificado TLS do Let’s Encrypt, o qual você irá provisionar com um add-on. Para obter uma versão mais detalhada deste tutorial, consulte o artigo sobre Como configurar a plataforma de IDE em nuvem Eclipse Theia no Ubuntu 18.04.

      Pré-requisitos

      Crie o diretório para armazenar todos os dados do Eclipse Theia:

      Navegue até ele:

      Crie o nginx-proxy-compose.yaml para armazenar a configuração do Docker Compose para o nginx-proxy:

      • nano nginx-proxy-compose.yaml

      Adicione as linhas a seguir:

      ~/eclipse-theia/nginx-proxy-compose.yaml

      version: '2'
      
      services:
        nginx-proxy:
          restart: always
          image: jwilder/nginx-proxy
          ports:
            - "80:80"
            - "443:443"
          volumes:
            - "/etc/nginx/htpasswd:/etc/nginx/htpasswd"
            - "/etc/nginx/vhost.d"
            - "/usr/share/nginx/html"
            - "/var/run/docker.sock:/tmp/docker.sock:ro"
            - "/etc/nginx/certs"
      
        letsencrypt-nginx-proxy-companion:
          restart: always
          image: jrcs/letsencrypt-nginx-proxy-companion
          volumes:
            - "/var/run/docker.sock:/var/run/docker.sock:ro"
          volumes_from:
            - "nginx-proxy"
      

      Aqui, você definirá dois serviços que o Docker Compose irá executar, o nginx-proxy e seu companheiro Let’s Encrypt. Para o proxy, você especificará o jwilder/nginx-proxy como a imagem, mapeando as portas HTTP e HTTPS e definindo os volumes que ficarão acessíveis para o proxy durante o tempo de execução.

      Salve e feche o arquivo.

      Implante a configuração:

      • docker-compose -f nginx-proxy-compose.yaml up -d

      O resultado final ficará parecido com este:

      Output

      Creating network "eclipse-theia_default" with the default driver Pulling nginx-proxy (jwilder/nginx-proxy:)... latest: Pulling from jwilder/nginx-proxy 8d691f585fa8: Pull complete 5b07f4e08ad0: Pull complete ... Digest: sha256:dfc0666b9747a6fc851f5fb9b03e65e957b34c95d9635b4b5d1d6b01104bde28 Status: Downloaded newer image for jwilder/nginx-proxy:latest Pulling letsencrypt-nginx-proxy-companion (jrcs/letsencrypt-nginx-proxy-companion:)... latest: Pulling from jrcs/letsencrypt-nginx-proxy-companion 89d9c30c1d48: Pull complete 668840c175f8: Pull complete ... Digest: sha256:a8d369d84079a923fdec8ce2f85827917a15022b0dae9be73e6a0db03be95b5a Status: Downloaded newer image for jrcs/letsencrypt-nginx-proxy-companion:latest Creating eclipse-theia_nginx-proxy_1 ... done Creating eclipse-theia_letsencrypt-nginx-proxy-companion_1 ... done

      Passo 2 — Implantando o Eclipse Theia em Docker

      O nginx-proxy espera que as combinações de login estejam em um arquivo que tem o mesmo nome do domínio exposto, no formato htpasswd e armazenadas sob o diretório /etc/nginx/htpasswd, no contêiner.

      Instale o htpasswd:

      • sudo apt install apache2-utils

      O pacote apache2-utils contém o utilitário htpasswd.

      Crie o diretório /etc/nginx/htpasswd:

      • sudo mkdir -p /etc/nginx/htpasswd

      Crie um arquivo para armazenar os logins do seu domínio:

      • sudo touch /etc/nginx/htpasswd/theia.your-domain

      Execute o comando a seguir com um nome de usuário e uma combinação de senha:

      • sudo htpasswd /etc/nginx/htpasswd/theia.your-domain username

      O htpasswd adicionará o nome de usuário e a senha hash ao final do arquivo.

      Crie a configuração para a implantação do Eclipse Theia:

      • nano eclipse-theia-compose.yaml

      Adicione as linhas a seguir:

      ~/eclipse-theia/eclipse-theia-compose.yaml

      version: '2.2'
      
      services:
        eclipse-theia:
          restart: always
          image: theiaide/theia:next
          init: true
          environment:
            - VIRTUAL_HOST=theia.your-domain
            - LETSENCRYPT_HOST=theia.your-domain
      

      Você define um serviço único chamado eclipse-theia com o restart configurado para always e o theiaide/theia:next como a imagem do contêiner. Defina também o init para true. Em seguida, especifique duas variáveis de ambiente na seção de environment: VIRTUAL_HOST e LETSENCRYPT_HOST.

      Salve e feche o arquivo.

      Agora, implante o Eclipse Theia, executando:

      • docker-compose -f eclipse-theia-compose.yaml up -d

      O resultado final se parecerá com o seguinte:

      Output

      ... Pulling eclipse-theia (theiaide/theia:next)... next: Pulling from theiaide/theia 63bc94deeb28: Pull complete 100db3e2539d: Pull complete ... Digest: sha256:c36dff04e250f1ac52d13f6d6e15ab3e9b8cad9ad68aba0208312e0788ecb109 Status: Downloaded newer image for theiaide/theia:next Creating eclipse-theia_eclipse-theia_1 ... done

      Navegue para o domínio que estiver usando para o Eclipse Theia. Seu navegador mostrará um prompt pedindo que você faça login. Você entrará no Eclipse Theia e verá a GUI do seu editor. Você verá também um cadeado indicando que a conexão é segura.

      Interface Gráfica do Usuário (GUI) do Eclipse Theia

      Conclusão

      Agora, você tem o Eclipse Theia, um IDE em nuvem versátil, instalado no seu servidor Ubuntu 18.04, usando o Docker Compose e o nginx-proxy. Você o protegeu com um certificado TLS do Let’s Encrypt gratuito e configurou a instância para exigir as credenciais de login do usuário. Você pode trabalhar no seu código-fonte e nos documentos com ele, de maneira independente ou em colaboração com sua equipe. Você também pode tentar compilar sua própria versão do Eclipse Theia se precisar de recursos adicionais. Para obter mais informações sobre como fazer isso, acesse os documentos do Theia.



      Source link