Categorías
Tecnología Tesla

Configurar TeslaMate autoalojado por $2 al mes en una porción de BuyVM

In this article I am going to walk you through step by step on how to install TeslaMate en su BuyVM Slice. From selecting your VM configuration to installing and configuring the tool onto your virtual machine. Looking for a guide on Vultr? Haga clic aquí. Otherwise, keep reading to learn how to setup self-hosted TeslaMate for $2 per month in a BuyVM Slice.

Características de TeslaMate:

  • Informes de conducción y cobro
  • Informe sobre la eficiencia de la conducción
  • Consumo de energía (neto / bruto)
  • Carga de energía añadida frente a la energía utilizada
  • Drenaje de Vampiros
  • Alcance proyectado del 100% (degradación de la batería)
  • Estadísticas de carga
  • Estadísticas de conducción
  • Historial de actualizaciones instaladas
  • Vea cuando su coche estaba conectado o dormido
  • Mapa de conducción de toda la vida
  • Direcciones visitadas

También puede comprobar el estado de su coche (incluido el nivel de la batería) sin despertar a tu coche.

SLICE Selection

In this tutorial we will be using the SLICE 512 from BuyVM which includes 1 Core @ 3.50+ GHz (Fair Share CPU Usage Applies), 512 MB of Memory, 10 GB of SSD Storage and Unmetered Bandwidth.

buyvmsliceplans 512andup 20200529 | graydonschwartz.com
Note: SLICE 4096 ($15) and up include dedicated CPU Usage.

I recommend signing up for one of their new AMD Ryzen VPS in the Las Vegas Data Center to pop up again because they are higher performing, brand new and at no additional cost. They also offer cloud servers in New York and Luxembourg but with older Intel hardware.

I have used more memory before for hosting TeslaMate but found 512MB has been plenty adequate for running TeslaMate for one Model 3 and access for myself only.

Order Slice

buyvm order512slice 20200529 | graydonschwartz.com
Out of sock.
  1. Select a location:
    Order – Las Vegas
    Order – New York
    Order – Luxembourg
  2. What would you like to do today? Click on ‘Order Hosting‘.
  3. Select the size of your slice and click on ‘Order Now‘.
  4. Enter your domain o subdomain into the order form.
    Example: teslamate.tesla.com
  5. They accept PayPal, stripe, along with a bunch of other options. Be sure that your account information matches your payment information or your purchase may get cancelled.

You should be setup within 1-3 hours during their regular business hours however new accounts can take up to 24-hours. Orders placed over the weekend are activated on Monday if they don't have anyone available.

Prerequisite

  1. LV RYZEN KVM 512MB or greater slice
  2. Two FQDN, for example teslamate.example.com y grafana.example.com
  3. PuTTY SSH Client

Log Into Stallion

buyvmstallionloginscreen20200529 | graydonschwartz.com
Setup Self-Hosted TeslaMate for $2 per Month in a BuyVM Slice 9

Stallion is the web interface that BuyVM developed for you to load your slice with an operating system, view status and manage all other tasks on your virtual server. You will find a link to Stallion at the top of the page when you login to the frantech client portal.

We will need to setup Docker manually because there isn't a pre-setup Docker but it's really no trouble at all to setup.

Select Image and Power On VM

buyvm reinstallcentos7 64bit 20200529 | graydonschwartz.com
Setup Self-Hosted TeslaMate for $2 per Month in a BuyVM Slice 10

Select ‘Reinstall' from the tab menus. Now, click on ‘Redhat Based (7)' from the list on the left. Click on ‘Reinstall' next to ‘CentOS 7.0 64bit' to bring up the install prompt. You will be asked to enter a password. This is for your root (or administration) password for your virtual server. Make sure to write this down in a safe place.

Click on the checkbox by: Yes, please wipe all data off yourhostname.com (IP ADDRESS)

Click ‘Reinstall' when you're ready to proceed.

Manual Install Docker

Install the yum-utils package (which provides the yum-config-manager utility)

sudo yum install -y yum-utils

and set up the stable repository.

sudo yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo

Instale el latest version of Docker Engine and containerd:

sudo yum install docker-ce docker-ce-cli containerd.io

Start Docker.

sudo systemctl start docker

Verify

sudo docker run hello-world

Configure Docker to start on boot

sudo systemctl enable docker

To disable this behavior, use disable instead:

sudo systemctl disable docker

Source: Docker

Configuración - docker-compose.yml

version: '3'

services:
  teslamate:
    image: teslamate/teslamate:latest
    restart: always
    depends_on:
      - database
    environment:
      - DATABASE_USER=${TM_DB_USER}
      - DATABASE_PASS=${TM_DB_PASS}
      - DATABASE_NAME=${TM_DB_NAME}
      - DATABASE_HOST=database
      - MQTT_HOST=mosquitto
      - VIRTUAL_HOST=${FQDN_TM}
      - CHECK_ORIGIN=true
      - TZ={$TM_TZ}
    volumes:
      - ./import:/opt/app/import
    labels:
      - 'traefik.enable=true'
      - 'traefik.port=4000'
      - "traefik.http.middlewares.redirect.redirectscheme.scheme=https"
      - "traefik.http.middlewares.auth.basicauth.usersfile=/auth/.htpasswd"
      - "traefik.http.routers.teslamate-insecure.rule=Host(`${FQDN_TM}`)"
      - "traefik.http.routers.teslamate-insecure.middlewares=redirect"
      - "traefik.http.routers.teslamate.rule=Host(`${FQDN_TM}`)"
      - "traefik.http.routers.teslamate.middlewares=auth"
      - "traefik.http.routers.teslamate.entrypoints=websecure"
      - "traefik.http.routers.teslamate.tls.certresolver=tmhttpchallenge"

  database:
    image: postgres:12
    restart: always
    environment:
      - POSTGRES_USER=${TM_DB_USER}
      - POSTGRES_PASSWORD=${TM_DB_PASS}
      - POSTGRES_DB=${TM_DB_NAME}
    volumes:
      - teslamate-db:/var/lib/postgresql/data

  grafana:
    image: teslamate/grafana:latest
    restart: always
    environment:
      - DATABASE_USER=${TM_DB_USER}
      - DATABASE_PASS=${TM_DB_PASS}
      - DATABASE_NAME=${TM_DB_NAME}
      - DATABASE_HOST=database
      - GRAFANA_PASSWD=${GRAFANA_PW}
      - GF_SECURITY_ADMIN_USER=${GRAFANA_USER}
      - GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PW}
      - GF_AUTH_BASIC_ENABLED=true
      - GF_AUTH_ANONYMOUS_ENABLED=false
      - GF_SERVER_ROOT_URL=https://${FQDN_GRAFANA}
    volumes:
      - teslamate-grafana-data:/var/lib/grafana
    labels:
      - 'traefik.enable=true'
      - 'traefik.port=3000'
      - "traefik.http.middlewares.redirect.redirectscheme.scheme=https"
      - "traefik.http.routers.grafana-insecure.rule=Host(`${FQDN_GRAFANA}`)"
      - "traefik.http.routers.grafana-insecure.middlewares=redirect"
      - "traefik.http.routers.grafana.rule=Host(`${FQDN_GRAFANA}`)"
      - "traefik.http.routers.grafana.entrypoints=websecure"
      - "traefik.http.routers.grafana.tls.certresolver=tmhttpchallenge"

  mosquitto:
    image: eclipse-mosquitto:1.6
    restart: always
    ports:
      - 127.0.0.1:1883:1883
    volumes:
      - mosquitto-conf:/mosquitto/config
      - mosquitto-data:/mosquitto/data

  proxy:
    image: traefik:v2.1
    restart: always
    command:
      - "--global.sendAnonymousUsage=false"
      - "--providers.docker"
      - "--providers.docker.exposedByDefault=false"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.websecure.address=:443"
      - "--certificatesresolvers.tmhttpchallenge.acme.httpchallenge=true"
      - "--certificatesresolvers.tmhttpchallenge.acme.httpchallenge.entrypoint=web"
      - "--certificatesresolvers.tmhttpchallenge.acme.email=${LETSENCRYPT_EMAIL}"
      - "--certificatesresolvers.tmhttpchallenge.acme.storage=/etc/acme/acme.json"
    ports:
      - 80:80
      - 443:443
    volumes:
      - ./.htpasswd:/auth/.htpasswd
      - ./acme/:/etc/acme/
      - /var/run/docker.sock:/var/run/docker.sock:ro

volumes:
    teslamate-db:
    teslamate-grafana-data:
    mosquitto-conf:
    mosquitto-data:

Configuración - .env

TM_DB_USER=teslamate
TM_DB_PASS=secret
TM_DB_NAME=teslamate

GRAFANA_USER=admin
GRAFANA_PW=admin

FQDN_GRAFANA=grafana.example.com
FQDN_TM=teslamate.example.com

TM_TZ=Europe/Berlin

LETSENCRYPT_EMAIL=yourperson@example.com

Configuración - .htpasswd

Según la documentación de TeslaMate. Le recomiendo que utilice esta herramienta para crear su archivo .htpasswd:
http://www.htaccesstools.com/htpasswd-generator/
Ingrese su deseo nombre de usuario, contraseña y seleccione Bcrypt (Apache v2.4 en adelante)
En el siguiente ejemplo, he introducido nombre de usuario y contraseña para estos campos:

Ejemplo:

mi:$2y$10$as5PEnYaoGEx2ebCFjdK0e9PBshAsvzIeAKijwNgeMSC9oJkDNo2.

Ahora copie y pegue esta información en su archivo .htpasswd.

vi .htpasswd (o su editor de texto favorito)

Asegúrese de configurar su contraseña antes de iniciar el Teslamate con Docker.

docker-compose up

Nota: Es posible que tenga que ejecutar este comando dos veces para que funcione.

Configuración del DNS

You will need to point teslamate.example.com + grafana.exampe.com (your subdomain) to the IP Address provided to you by BuyShared when you created your virtual server. This is done by contacting your web host or logging into your control panel to manage your DNS records and having these entries added.

Cómo iniciar sesión en TeslaMate

  1. Abrir la interfaz web https://teslamate.example.com
    Inicie sesión con los datos que introdujo en el archivo .htpasswd y, a continuación, se le pedirá que inicie sesión con su cuenta de Tesla.
  2. Inicia sesión con tu cuenta de Tesla
  3. Los cuadros de mando de Grafana están disponibles en:https://grafana.example.com.
  4. Introduzca el nombre de usuario y la contraseña:admin:admin primero y se le pedirá que cambie la contraseña en su primer acceso.

Upgrade Available?

I always check out the release notes before upgrading.

docker-compose pull

[root@localhost ~]# docker-compose pull
Pulling database  ... done
Pulling teslamate ... done
Pulling grafana   ... done
Pulling mosquitto ... done
Pulling proxy     ... done

docker-compose up

[root@localhost ~]# docker-compose up
Recreating root_grafana_1 ...
Recreating root_database_1 ...
Recreating root_grafana_1  ... done
Recreating root_database_1 ... done
Recreating root_teslamate_1 ... done
....update messages
16:57:45.350 [info] Tzdata has updated the release from 2019c to 2020a

Your install is now upgraded and you can close out of the terminal. You can check the version by logging into your TeslaMate control panel.

Extra Protection

Let's start by disabling/uninstalling FirewallD:

sudo yum remove -y firewalld

Now, let's install/activate IPTables.

sudo yum install -y iptables-services
sudo systemctl start iptables

Configure IPTables to start automatically at boot time.

sudo systemctl enable iptables

IPTables on CentOS 7 comes with a default set of rules, which you can view with the following command.

sudo iptables -L -n

The output will resemble:

Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0           
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            state NEW tcp dpt:22
REJECT     all  --  0.0.0.0/0            0.0.0.0/0            reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         
REJECT     all  --  0.0.0.0/0            0.0.0.0/0            reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

You can see that one of those rules allows SSH traffic, so your SSH session is safe.

Because those rules are runtime rules and will be lost on reboot, it's best to save them to a file using:

sudo /usr/libexec/iptables/iptables.init save

That command will save the rules to the /etc/sysconfig/iptables file. You can edit the rules anytime by changing this file with your favorite text editor.

Next, Allow Additional Traffic Through the Firewall

Since you'll most likely be going to use your new server to host some websites at some point, you'll have to add new rules to the firewall to allow HTTP and HTTPS traffic. To accomplish that, open the IPTables file:

sudo nano /etc/sysconfig/iptables

Just after or before the SSH rule, add the rules for HTTP (port 80) and HTTPS (port 443) traffic, so that that portion of the file appears as shown in the code block below.

-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited

Save and close the file, then reload IPTables.

sudo systemctl reload iptables

With the above step completed, your CentOS 7 server should now be reasonably secure and be ready for use in production.

Other Security?

I want to preface this next idea by saying that you may run into issues because TeslaMate's SSL Cert requires the subdomains be pointed to the IP Address of your VPS, however if you hide it behind Cloudflare, this won't be the case and SSL will fail to renew on restarts of TeslaMate. So, I no longer recommend enabling CF until it's fully supported by the developer. I am going to leave it here for food for thought.

cloudflare | graydonschwartz.com
Setup Self-Hosted TeslaMate for $2 per Month in a BuyVM Slice 11

This is an extra step that isn't required to get going but might provide a little bit of extra security to your subdomains. Sign-up for Cloudflare! It's a free service that protects and speeds up your website.

  1. Click on ‘DNS'.
  2. For your grafana (A Record):
    Set Proxy status to Proxied.
  3. Also, for your teslamate (A Record):
    Set Proxy status to Proxied.

You will now notice that if you ping your subdomains they now have a lower ping and a different IP address because you are now routing your traffic through the Cloudflare Network and your IP address with BuyVM is now hidden during DNS requests.

I have tested enabling proxy mode for awhile now and haven't encountered any issues so far.

Espero que esta guía de configuración te haya resultado útil 🙂 .

Affordable BuyVM Slices

Agradecimiento especial

TESMAT en el Supercargador de Tesla

TESMAT

TESMAT podría ser el colchón adecuado para su próxima siesta en el Supercargador, su viaje de acampada en coche o el regalo perfecto para su propietario favorito del Tesla Model 3/Y. Puedes usar mi código de cupón para ahorrar en tu compra.

Más información:

logo luminar neo para fondos claros actualizado | graydonschwartz.com

Luminar Neo

Utilice el botón de abajo y no dude en utilizar el código de descuento (GRAYDON) para darse un descuento dulce en el momento de la compra en Luminar:

Es posible que gane una pequeña comisión por mi aprobación, recomendación, testimonios y/o enlaces a productos o servicios enlazados arriba. Tu compra me ayuda a ofrecerte más fotografías, guías de viaje y más viajes alrededor del mundo.

Por Graydon Schwartz

Más información sobre Graydon en el Sobre mí página.