diff --git a/Magento2/Kubernetes/azurefile/sc.yaml b/Magento2/Kubernetes/azurefile/sc.yaml new file mode 100644 index 0000000..2bb5d8e --- /dev/null +++ b/Magento2/Kubernetes/azurefile/sc.yaml @@ -0,0 +1,9 @@ +apiVersion: storage.k8s.io/v1 +kind: StorageClass +metadata: + name: azurefile-sc + annotations: + storageclass.kubernetes.io/is-default-class: "true" +provisioner: kubernetes.io/azure-file +reclaimPolicy: Retain +allowVolumeExpansion: true diff --git a/Magento2/Kubernetes/elasticsearch/pv.yaml b/Magento2/Kubernetes/elasticsearch/pv.yaml new file mode 100644 index 0000000..dd4299f --- /dev/null +++ b/Magento2/Kubernetes/elasticsearch/pv.yaml @@ -0,0 +1,23 @@ +apiVersion: v1 +kind: PersistentVolume +metadata: + name: elasticsearch-pv +spec: + capacity: + storage: 1Gi + accessModes: + - ReadWriteOnce + azureFile: + secretName: input-secrets + secretNamespace: magento + shareName: elasticsearch + readOnly: false + mountOptions: + - dir_mode=0777 + - file_mode=0777 + - mfsymlinks + - uid=1000 + - gid=1000 + - cache=none + persistentVolumeReclaimPolicy: Retain + storageClassName: azurefile-sc \ No newline at end of file diff --git a/Magento2/Kubernetes/elasticsearch/pvc.yaml b/Magento2/Kubernetes/elasticsearch/pvc.yaml new file mode 100644 index 0000000..fc006f7 --- /dev/null +++ b/Magento2/Kubernetes/elasticsearch/pvc.yaml @@ -0,0 +1,11 @@ +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: elasticsearch-pvc +spec: + accessModes: + - ReadWriteOnce + resources: + requests: + storage: 1Gi + storageClassName: azurefile-sc diff --git a/Magento2/Kubernetes/elasticsearch/services.yaml b/Magento2/Kubernetes/elasticsearch/services.yaml new file mode 100644 index 0000000..8ff6898 --- /dev/null +++ b/Magento2/Kubernetes/elasticsearch/services.yaml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: Service +metadata: + name: elasticsearch-service + namespace: magento +spec: + selector: + app: elasticsearch + ports: + - protocol: TCP + port: 9200 + targetPort: 9200 \ No newline at end of file diff --git a/Magento2/Kubernetes/elasticsearch/statefulset.yaml b/Magento2/Kubernetes/elasticsearch/statefulset.yaml new file mode 100644 index 0000000..3b79db0 --- /dev/null +++ b/Magento2/Kubernetes/elasticsearch/statefulset.yaml @@ -0,0 +1,35 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: elasticsearch + namespace: magento +spec: + replicas: 1 + selector: + matchLabels: + app: elasticsearch + serviceName: elasticsearch-service + template: + metadata: + labels: + app: elasticsearch + spec: + containers: + - name: elasticsearch + image: docker.elastic.co/elasticsearch/elasticsearch:7.17.24 + ports: + - containerPort: 9200 + name: main + env: + - name: discovery.type + value: "single-node" + - name: xpack.security.enabled + value: "false" + volumeMounts: + - mountPath: /usr/share/elasticsearch/data + name: elasticsearch-data + volumes: + - name: elasticsearch-data + persistentVolumeClaim: + claimName: elasticsearch-pvc + readOnly: false diff --git a/Magento2/Kubernetes/ingress/ingress-tls.yaml b/Magento2/Kubernetes/ingress/ingress-tls.yaml new file mode 100644 index 0000000..bf7b673 --- /dev/null +++ b/Magento2/Kubernetes/ingress/ingress-tls.yaml @@ -0,0 +1,33 @@ +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: magento-ingress + namespace: magento + annotations: + kubernetes.io/ingress.class: "nginx" + nginx.ingress.kubernetes.io/rewrite-target: / + nginx.ingress.kubernetes.io/ssl-redirect: "false" + nginx.ingress.kubernetes.io/proxy-buffer-size: "256k" + nginx.org/proxy-buffers: "4 256k" + nginx.ingress.kubernetes.io/proxy-buffers-number: "4" + nginx.ingress.kubernetes.io/proxy-busy-buffers-size: "256k" + nginx.org/proxy-connect-timeout: "60s" + nginx.org/proxy-read-timeout: "60s" + nginx.ingress.kubernetes.io/force-ssl-redirect: "false" +spec: + ingressClassName: nginx + tls: + - hosts: + - __FQDN__ + secretName: magento-secret + rules: + - host: __FQDN__ + http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: __SERVICE_NAME__ + port: + number: __SERVICE_PORT__ diff --git a/Magento2/Kubernetes/ingress/ingress.yaml b/Magento2/Kubernetes/ingress/ingress.yaml new file mode 100644 index 0000000..1e76092 --- /dev/null +++ b/Magento2/Kubernetes/ingress/ingress.yaml @@ -0,0 +1,28 @@ +apiVersion: networking.k8s.io/v1 +kind: Ingress +metadata: + name: magento-ingress + namespace: magento + annotations: + kubernetes.io/ingress.class: "nginx" + nginx.ingress.kubernetes.io/rewrite-target: / + nginx.ingress.kubernetes.io/ssl-redirect: "false" + nginx.ingress.kubernetes.io/proxy-buffer-size: "256k" + nginx.org/proxy-buffers: "4 256k" + nginx.ingress.kubernetes.io/proxy-buffers-number: "4" + nginx.ingress.kubernetes.io/proxy-busy-buffers-size: "256k" + nginx.org/proxy-connect-timeout: "60s" + nginx.org/proxy-read-timeout: "60s" + nginx.ingress.kubernetes.io/force-ssl-redirect: "false" +spec: + ingressClassName: nginx + rules: + - http: + paths: + - path: / + pathType: Prefix + backend: + service: + name: __SERVICE_NAME__ + port: + number: __SERVICE_PORT__ diff --git a/Magento2/Kubernetes/magento/configmap.yaml b/Magento2/Kubernetes/magento/configmap.yaml new file mode 100644 index 0000000..66a6d0a --- /dev/null +++ b/Magento2/Kubernetes/magento/configmap.yaml @@ -0,0 +1,75 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: magento-config + namespace: magento +data: + PHP_VERSION: "8.3" + MAGENTO_PORT: "8080" + MAGENTO_DATABASE_NAME: "magento" + MAGENTO_SEARCH_ENGINE: "elasticsearch7" + ELASTICSEARCH_HOST: elasticsearch-service.magento.svc.cluster.local + ELASTICSEARCH_PORT: "9200" + MAGENTO_ADMIN_FIRSTNAME: "Admin" + MAGENTO_ADMIN_LASTNAME: "User" + MAGENTO_ADMIN_FRONTNAME: "admin" + MAGENTO_LANGUAGE: "en_US" + MAGENTO_USE_REWRITES: "1" + SESSION_BACKEND: "redis" + SESSION_REDIS_SERVER_HOST: redis-service.magento.svc.cluster.local + SESSION_REDIS_PORT: "6379" + SESSION_REDIS_DATABASE: "2" + SESSION_REDIS_LOG_LEVEL: "4" + MAGENTO_FORCE_INSTALL: "false" + MAGENTO_DEPLOY_SAMPLE_DATA: "false" + MAGENTO_REMOVE_SAMPLE_DATA: "false" + MAGENTO_DISABLE_2FA: "true" + VARNISH_LISTEN_HOST: "varnish-service.magento.svc.cluster.local" + VARNISH_LISTEN_PORT: "8081" + VARNISH_BACKEND_HOST: magento-service.magento.svc.cluster.local + VARNISH_BACKEND_PORT: "8080" + VARNISH_STORAGE: "malloc,256M" + default.conf: | + # Example configuration: + upstream fastcgi_backend { + # use tcp connection + # server 127.0.0.1:9000; + # or socket + server unix:/run/php/php8.3-fpm.sock; + } + server { + listen 8080; + server_name magento-service.magento.svc.cluster.local; + set $MAGE_ROOT /var/www/html/magento2; + set $MAGE_DEBUG_SHOW_ARGS 0; + + include /usr/local/bin/nginx.conf.sample; + } + + # Optional override of deployment mode. We recommend you use the + # command 'bin/magento deploy:mode:set' to switch modes instead. + # + # set $MAGE_MODE default; # or production or developer + # + # If you set MAGE_MODE in server config, you must pass the variable into the + # PHP entry point blocks, which are indicated below. You can pass + # it in using: + # + # fastcgi_param MAGE_MODE $MAGE_MODE; + # + # In production mode, you should uncomment the 'expires' directive in the /static/ location block + + # Modules can be loaded only at the very beginning of the Nginx config file, please move the line below to the main config file + # load_module /etc/nginx/modules/ngx_http_image_filter_module.so; + +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: magento-cron-config + namespace: magento +data: + CONFIG__DEFAULT__SYSTEM__CRON__INDEX__USE_SEPARATE_PROCESS: "0" + CONFIG__DEFAULT__SYSTEM__CRON__DEFAULT__USE_SEPARATE_PROCESS: "0" + CONFIG__DEFAULT__SYSTEM__CRON__CONSUMERS__USE_SEPARATE_PROCESS: "0" + CONFIG__DEFAULT__SYSTEM__CRON__DDG_AUTOMATION__USE_SEPARATE_PROCESS: "0" diff --git a/Magento2/Kubernetes/magento/cron.yaml b/Magento2/Kubernetes/magento/cron.yaml new file mode 100644 index 0000000..65d7e1f --- /dev/null +++ b/Magento2/Kubernetes/magento/cron.yaml @@ -0,0 +1,46 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: magento-cron + namespace: magento +spec: + replicas: 1 + selector: + matchLabels: + app: magento-cron + template: + metadata: + labels: + app: magento-cron + spec: + containers: + - name: magento-cron + image: aaakarshit/magento-cron:v1.0.0 + envFrom: + - configMapRef: + name: input-config + - configMapRef: + name: magento-config + - configMapRef: + name: magento-cron-config + - secretRef: + name: input-secrets + volumeMounts: + - name: azurefile-magento + mountPath: /var/www/html/mount/static + subPath: static + - name: azurefile-magento + mountPath: /var/www/html/mount/media + subPath: media + readinessProbe: + exec: + command: ["sh", "-c", "test -f /tmp/magento-setup-complete-${HOSTNAME}"] + failureThreshold: 145 # Check till 15 minutes + initialDelaySeconds: 180 # Start checking after 3 minutes + periodSeconds: 5 # Check every 5 seconds + successThreshold: 1 # If the file is present, it's ready + volumes: + - name: azurefile-magento + persistentVolumeClaim: + claimName: magento-pvc + readOnly: false diff --git a/Magento2/Kubernetes/magento/deployment.yaml b/Magento2/Kubernetes/magento/deployment.yaml new file mode 100644 index 0000000..793abcf --- /dev/null +++ b/Magento2/Kubernetes/magento/deployment.yaml @@ -0,0 +1,55 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: magento-server + namespace: magento +spec: + replicas: 1 + selector: + matchLabels: + app: magento-server + template: + metadata: + labels: + app: magento-server + spec: + containers: + - name: magento-server + image: aaakarshit/magento-server:v1.0.0 + ports: + - containerPort: 8080 + envFrom: + - configMapRef: + name: magento-config + - configMapRef: + name: input-config + - secretRef: + name: input-secrets + volumeMounts: + - name: azurefile-magento + mountPath: /var/www/html/mount/static + subPath: static + - name: azurefile-magento + mountPath: /var/www/html/mount/media + subPath: media + - name: magento-config + mountPath: /etc/nginx/conf.d/default.conf + subPath: default.conf + readinessProbe: + exec: + command: ["sh", "-c", "test -f /tmp/magento-setup-complete-${HOSTNAME}"] + failureThreshold: 145 # Check till 15 minutes + initialDelaySeconds: 180 # Start checking after 3 minutes + periodSeconds: 5 # Check every 5 seconds + successThreshold: 1 # If the file is present, it's ready + volumes: + - name: azurefile-magento + persistentVolumeClaim: + claimName: magento-pvc + readOnly: false + - name: magento-config + configMap: + name: magento-config + items: + - key: default.conf + path: default.conf diff --git a/Magento2/Kubernetes/magento/job.yaml b/Magento2/Kubernetes/magento/job.yaml new file mode 100644 index 0000000..d04d7f3 --- /dev/null +++ b/Magento2/Kubernetes/magento/job.yaml @@ -0,0 +1,40 @@ +apiVersion: batch/v1 +kind: Job +metadata: + name: magento-setup-job + namespace: magento +spec: + template: + metadata: + labels: + app: magento-setup-job + spec: + containers: + - name: magento-setup-job + image: aaakarshit/magento-setup-job:v1.0.0 + envFrom: + - configMapRef: + name: magento-config + - configMapRef: + name: input-config + - secretRef: + name: input-secrets + volumeMounts: + - name: azurefile-magento + mountPath: /var/www/html/mount/static + subPath: static + - name: azurefile-magento + mountPath: /var/www/html/mount/media + subPath: media + restartPolicy: Never + volumes: + - name: azurefile-magento + persistentVolumeClaim: + claimName: magento-pvc + readOnly: false + - name: magento-config + configMap: + name: magento-config + items: + - key: default.conf + path: default.conf diff --git a/Magento2/Kubernetes/magento/pv.yaml b/Magento2/Kubernetes/magento/pv.yaml new file mode 100644 index 0000000..89237d6 --- /dev/null +++ b/Magento2/Kubernetes/magento/pv.yaml @@ -0,0 +1,23 @@ +apiVersion: v1 +kind: PersistentVolume +metadata: + name: magento-pv +spec: + capacity: + storage: 20Gi + accessModes: + - ReadWriteMany + azureFile: + secretName: input-secrets + secretNamespace: magento + shareName: magento + readOnly: false + mountOptions: + - dir_mode=0777 + - file_mode=0777 + - mfsymlinks + - uid=33 + - gid=33 + - cache=none + persistentVolumeReclaimPolicy: Retain + storageClassName: azurefile-sc \ No newline at end of file diff --git a/Magento2/Kubernetes/magento/pvc.yaml b/Magento2/Kubernetes/magento/pvc.yaml new file mode 100644 index 0000000..e83733d --- /dev/null +++ b/Magento2/Kubernetes/magento/pvc.yaml @@ -0,0 +1,11 @@ +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: magento-pvc +spec: + accessModes: + - ReadWriteMany + resources: + requests: + storage: 20Gi + storageClassName: azurefile-sc diff --git a/Magento2/Kubernetes/magento/services-external.yaml b/Magento2/Kubernetes/magento/services-external.yaml new file mode 100644 index 0000000..cd2f895 --- /dev/null +++ b/Magento2/Kubernetes/magento/services-external.yaml @@ -0,0 +1,13 @@ +apiVersion: v1 +kind: Service +metadata: + name: magento-service + namespace: magento +spec: + selector: + app: magento-server + type: LoadBalancer + ports: + - protocol: TCP + port: 8080 + targetPort: 8080 diff --git a/Magento2/Kubernetes/magento/services.yaml b/Magento2/Kubernetes/magento/services.yaml new file mode 100644 index 0000000..e7aa67d --- /dev/null +++ b/Magento2/Kubernetes/magento/services.yaml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: Service +metadata: + name: magento-service + namespace: magento +spec: + selector: + app: magento-server + ports: + - protocol: TCP + port: 8080 + targetPort: 8080 diff --git a/Magento2/Kubernetes/namespace.yaml b/Magento2/Kubernetes/namespace.yaml new file mode 100644 index 0000000..c5ff9f3 --- /dev/null +++ b/Magento2/Kubernetes/namespace.yaml @@ -0,0 +1,4 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: magento diff --git a/Magento2/Kubernetes/redis/services.yaml b/Magento2/Kubernetes/redis/services.yaml new file mode 100644 index 0000000..56082f3 --- /dev/null +++ b/Magento2/Kubernetes/redis/services.yaml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: Service +metadata: + name: redis-service + namespace: magento +spec: + selector: + app: redis + ports: + - protocol: TCP + port: 6379 + targetPort: 6379 diff --git a/Magento2/Kubernetes/redis/statefulset.yaml b/Magento2/Kubernetes/redis/statefulset.yaml new file mode 100644 index 0000000..44a4aef --- /dev/null +++ b/Magento2/Kubernetes/redis/statefulset.yaml @@ -0,0 +1,22 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: redis + namespace: magento +spec: + replicas: 1 + selector: + matchLabels: + app: redis + serviceName: redis-service + template: + metadata: + labels: + app: redis + spec: + containers: + - name: redis + image: redis:7.4.1 + ports: + - containerPort: 6379 + name: main diff --git a/Magento2/Kubernetes/tls/cert-pod.yaml b/Magento2/Kubernetes/tls/cert-pod.yaml new file mode 100644 index 0000000..afc6996 --- /dev/null +++ b/Magento2/Kubernetes/tls/cert-pod.yaml @@ -0,0 +1,21 @@ +apiVersion: v1 +kind: Pod +metadata: + name: cert-pod + namespace: magento +spec: + containers: + - name: busybox + image: busybox + command: [ "sh", "-c", "sleep 3600" ] + volumeMounts: + - name: secrets-store + mountPath: "/mnt/secrets-store" + readOnly: true + volumes: + - name: secrets-store + csi: + driver: secrets-store.csi.k8s.io + readOnly: true + volumeAttributes: + secretProviderClass: magento-secret-provider diff --git a/Magento2/Kubernetes/tls/secret-provider.yaml b/Magento2/Kubernetes/tls/secret-provider.yaml new file mode 100644 index 0000000..c680c48 --- /dev/null +++ b/Magento2/Kubernetes/tls/secret-provider.yaml @@ -0,0 +1,27 @@ +apiVersion: secrets-store.csi.x-k8s.io/v1 +kind: SecretProviderClass +metadata: + name: magento-secret-provider + namespace: magento +spec: + provider: azure + secretObjects: + - secretName: magento-secret + type: kubernetes.io/tls + data: + - objectName: __CERTIFICATE_NAME__ + key: tls.crt + - objectName: __CERTIFICATE_NAME__ + key: tls.key + parameters: + usePodIdentity: "false" + useVMManagedIdentity: "true" + userAssignedIdentityID: __USER_ASSIGNED_IDENTITY_ID__ + keyvaultName: __KEYVAULT_NAME__ + objects: | + array: + - | + objectName: __CERTIFICATE_NAME__ + objectType: secret + objectFormat: "pem" + tenantId: __TENANT_ID__ diff --git a/Magento2/Kubernetes/varnish/configmap.yaml b/Magento2/Kubernetes/varnish/configmap.yaml new file mode 100644 index 0000000..9de41ae --- /dev/null +++ b/Magento2/Kubernetes/varnish/configmap.yaml @@ -0,0 +1,279 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: varnish-config + namespace: magento +data: + VARNISH_LISTEN_HOST: varnish-service.magento.svc.cluster.local + VARNISH_LISTEN_PORT: "8081" + VARNISH_BACKEND_HOST: magento-service.magento.svc.cluster.local + VARNISH_BACKEND_PORT: "8080" + VARNISH_STORAGE: "malloc,512M" + default.vcl: | + # VCL version 5.0 is not supported so it should be 4.0 even though actually used Varnish version is 6 + vcl 4.0; + + import std; + # The minimal Varnish version is 6.0 + # For SSL offloading, pass the following header in your proxy server or load balancer: 'X-Forwarded-Proto: https' + + backend default { + .host = "magento-service.magento.svc.cluster.local"; + .port = "8080"; + .first_byte_timeout = 600s; + } + + acl purge { + "varnish-service.magento.svc.cluster.local"; + } + + sub vcl_recv { + if (req.restarts > 0) { + set req.hash_always_miss = true; + } + + if (req.method == "PURGE") { + if (client.ip !~ purge) { + return (synth(405, "Method not allowed")); + } + # To use the X-Pool header for purging varnish during automated deployments, make sure the X-Pool header + # has been added to the response in your backend server config. This is used, for example, by the + # capistrano-magento2 gem for purging old content from varnish during its deploy routine. + if (!req.http.X-Magento-Tags-Pattern && !req.http.X-Pool) { + return (synth(400, "X-Magento-Tags-Pattern or X-Pool header required")); + } + if (req.http.X-Magento-Tags-Pattern) { + ban("obj.http.X-Magento-Tags ~ " + req.http.X-Magento-Tags-Pattern); + } + if (req.http.X-Pool) { + ban("obj.http.X-Pool ~ " + req.http.X-Pool); + } + return (synth(200, "Purged")); + } + + if (req.method != "GET" && + req.method != "HEAD" && + req.method != "PUT" && + req.method != "POST" && + req.method != "TRACE" && + req.method != "OPTIONS" && + req.method != "DELETE") { + /* Non-RFC2616 or CONNECT which is weird. */ + return (pipe); + } + + # We only deal with GET and HEAD by default + if (req.method != "GET" && req.method != "HEAD") { + return (pass); + } + + # Bypass search requests, shopping cart, checkout + if (req.url ~ "/catalogsearch" || req.url ~ "/checkout") { + return (pass); + } + + # Bypass health check requests + if (req.url ~ "^/(pub/)?(health_check.php)$") { + return (pass); + } + + # Set initial grace period usage status + set req.http.grace = "none"; + + # normalize url in case of leading HTTP scheme and domain + set req.url = regsub(req.url, "^http[s]?://", ""); + + # collect all cookies + std.collect(req.http.Cookie); + + # Compression filter. See https://www.varnish-cache.org/trac/wiki/FAQ/Compression + if (req.http.Accept-Encoding) { + if (req.url ~ "\.(jpg|jpeg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|swf|flv|svg)$") { + # No point in compressing these + unset req.http.Accept-Encoding; + } elsif (req.http.Accept-Encoding ~ "gzip") { + set req.http.Accept-Encoding = "gzip"; + } elsif (req.http.Accept-Encoding ~ "deflate" && req.http.user-agent !~ "MSIE") { + set req.http.Accept-Encoding = "deflate"; + } else { + # unknown algorithm + unset req.http.Accept-Encoding; + } + } + + # Remove all marketing get parameters to minimize the cache objects + if (req.url ~ "(\?|&)(gclid|cx|ie|cof|siteurl|zanpid|origin|fbclid|mc_[a-z]+|utm_[a-z]+|_bta_[a-z]+)=") { + set req.url = regsuball(req.url, "(gclid|cx|ie|cof|siteurl|zanpid|origin|fbclid|mc_[a-z]+|utm_[a-z]+|_bta_[a-z]+)=[-_A-z0-9+()%.]+&?", ""); + set req.url = regsub(req.url, "[?|&]+$", ""); + } + + # Static files caching + if (req.url ~ "^/(pub/)?(media|static)/") { + # Static files should not be cached by default + return (pass); + + # But if you use a few locales and dont use CDN you can enable caching static files by commenting previous line (#return (pass);) and uncommenting next 3 lines + #unset req.http.Https; + #unset req.http.X-Forwarded-Proto; + #unset req.http.Cookie; + } + + # Bypass authenticated GraphQL requests without a X-Magento-Cache-Id + if (req.url ~ "/graphql" && !req.http.X-Magento-Cache-Id && req.http.Authorization ~ "^Bearer") { + return (pass); + } + + return (hash); + } + + sub vcl_hash { + if ((req.url !~ "/graphql" || !req.http.X-Magento-Cache-Id) && req.http.cookie ~ "X-Magento-Vary=") { + hash_data(regsub(req.http.cookie, "^.*?X-Magento-Vary=([^;]+);*.*$", "\1")); + } + + # To make sure http users dont see ssl warning + if (req.http.X-Forwarded-Proto) { + hash_data(req.http.X-Forwarded-Proto); + } + + + if (req.url ~ "/graphql") { + call process_graphql_headers; + } + } + + sub process_graphql_headers { + if (req.http.X-Magento-Cache-Id) { + hash_data(req.http.X-Magento-Cache-Id); + + # When the frontend stops sending the auth token, make sure users stop getting results cached for logged-in users + if (req.http.Authorization ~ "^Bearer") { + hash_data("Authorized"); + } + } + + if (req.http.Store) { + hash_data(req.http.Store); + } + + if (req.http.Content-Currency) { + hash_data(req.http.Content-Currency); + } + } + + sub vcl_backend_response { + + set beresp.grace = 3d; + + if (beresp.http.content-type ~ "text") { + # set beresp.do_esi = true; + } + + if (bereq.url ~ "\.js$" || beresp.http.content-type ~ "text") { + set beresp.do_gzip = true; + } + + if (beresp.http.X-Magento-Debug) { + set beresp.http.X-Magento-Cache-Control = beresp.http.Cache-Control; + } + + # cache only successfully responses and 404s + if (beresp.status != 200 && beresp.status != 404) { + set beresp.ttl = 0s; + set beresp.uncacheable = true; + return (deliver); + } elsif (beresp.http.Cache-Control ~ "private") { + set beresp.uncacheable = true; + set beresp.ttl = 86400s; + return (deliver); + } + + # validate if we need to cache it and prevent from setting cookie + if (beresp.ttl > 0s && (bereq.method == "GET" || bereq.method == "HEAD")) { + # Collapse beresp.http.set-cookie in order to merge multiple set-cookie headers + # Although it is not recommended to collapse set-cookie header, + # it is safe to do it here as the set-cookie header is removed below + std.collect(beresp.http.set-cookie); + # Do not cache the response under current cache key (hash), + # if the response has X-Magento-Vary but the request does not. + if ((bereq.url !~ "/graphql" || !bereq.http.X-Magento-Cache-Id) + && bereq.http.cookie !~ "X-Magento-Vary=" + && beresp.http.set-cookie ~ "X-Magento-Vary=") { + set beresp.ttl = 0s; + set beresp.uncacheable = true; + } + unset beresp.http.set-cookie; + } + + # If page is not cacheable then bypass varnish for 2 minutes as Hit-For-Pass + if (beresp.ttl <= 0s || + beresp.http.Surrogate-control ~ "no-store" || + (!beresp.http.Surrogate-Control && + beresp.http.Cache-Control ~ "no-cache|no-store") || + beresp.http.Vary == "*") { + # Mark as Hit-For-Pass for the next 2 minutes + set beresp.ttl = 120s; + set beresp.uncacheable = true; + } + + # If the cache key in the Magento response doesnt match the one that was sent in the request, don't cache under the request's key + if (bereq.url ~ "/graphql" && bereq.http.X-Magento-Cache-Id && bereq.http.X-Magento-Cache-Id != beresp.http.X-Magento-Cache-Id) { + set beresp.ttl = 0s; + set beresp.uncacheable = true; + } + + return (deliver); + } + + sub vcl_deliver { + if (resp.http.X-Magento-Debug) { + if (resp.http.x-varnish ~ " ") { + set resp.http.X-Magento-Cache-Debug = "HIT"; + set resp.http.Grace = req.http.grace; + } else { + set resp.http.X-Magento-Cache-Debug = "MISS"; + } + } else { + unset resp.http.Age; + } + + # Not letting browser to cache non-static files. + if (resp.http.Cache-Control !~ "private" && req.url !~ "^/(pub/)?(media|static)/") { + set resp.http.Pragma = "no-cache"; + set resp.http.Expires = "-1"; + set resp.http.Cache-Control = "no-store, no-cache, must-revalidate, max-age=0"; + } + + if (!resp.http.X-Magento-Debug) { + unset resp.http.Age; + } + + unset resp.http.X-Magento-Debug; + unset resp.http.X-Magento-Tags; + unset resp.http.X-Powered-By; + unset resp.http.Server; + unset resp.http.X-Varnish; + unset resp.http.Via; + unset resp.http.Link; + } + + sub vcl_hit { + if (obj.ttl >= 0s) { + # Hit within TTL period + return (deliver); + } + if (std.healthy(req.backend_hint)) { + if (obj.ttl + 300s > 0s) { + # Hit after TTL expiration, but within grace period + set req.http.grace = "normal (healthy server)"; + return (deliver); + } else { + # Hit after TTL and grace expiration + return (restart); + } + } else { + # server is not healthy, retrieve from cache + set req.http.grace = "unlimited (unhealthy server)"; + return (deliver); + } + } diff --git a/Magento2/Kubernetes/varnish/deployment.yaml b/Magento2/Kubernetes/varnish/deployment.yaml new file mode 100644 index 0000000..07cfa4d --- /dev/null +++ b/Magento2/Kubernetes/varnish/deployment.yaml @@ -0,0 +1,36 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: varnish + namespace: magento +spec: + replicas: 1 + selector: + matchLabels: + app: varnish + template: + metadata: + labels: + app: varnish + spec: + containers: + - name: varnish + image: varnish:6.0.13 + command: ["sh", "-c", "varnishd -F -n /var/lib/varnish -f /etc/varnish/default.vcl -s ${VARNISH_STORAGE} -a :${VARNISH_LISTEN_PORT} & \ + varnishncsa -n /var/lib/varnish -F '%h %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-agent}i\" %{Varnish:handling}x'"] + ports: + - containerPort: 8081 + volumeMounts: + - name: varnish-config + mountPath: /etc/varnish/default.vcl + subPath: default.vcl + envFrom: + - configMapRef: + name: varnish-config + volumes: + - name: varnish-config + configMap: + name: varnish-config + items: + - key: default.vcl + path: default.vcl diff --git a/Magento2/Kubernetes/varnish/services.yaml b/Magento2/Kubernetes/varnish/services.yaml new file mode 100644 index 0000000..7f9f30b --- /dev/null +++ b/Magento2/Kubernetes/varnish/services.yaml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: Service +metadata: + name: varnish-service + namespace: magento +spec: + selector: + app: varnish + ports: + - protocol: TCP + port: 80 + targetPort: 8081 diff --git a/Magento2/LICENSE b/Magento2/LICENSE new file mode 100644 index 0000000..b17b032 --- /dev/null +++ b/Magento2/LICENSE @@ -0,0 +1,17 @@ +The MIT License (MIT) +Copyright (c) Microsoft Corporation + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/Magento2/LICENSE-DOCS b/Magento2/LICENSE-DOCS new file mode 100644 index 0000000..a2c95fc --- /dev/null +++ b/Magento2/LICENSE-DOCS @@ -0,0 +1,395 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. \ No newline at end of file diff --git a/Magento2/README.md b/Magento2/README.md new file mode 100644 index 0000000..630d210 --- /dev/null +++ b/Magento2/README.md @@ -0,0 +1,82 @@ +# One-click ARM template to deploy Magento OSS e-commerce app on Azure + +## Introduction +[Magento Open Source](https://business.adobe.com/products/magento/open-source.html) is a free and flexible e-commerce platform that allows you to create and manage online stores. This Azure Resource Manager JSON template provides a easy one-click method to deploy Magento on Azure using following Azure services to provide an optimal experience of hosting Magento on Azure with tight integrations. + +* [Azure Resource Manager (ARM) templates](https://learn.microsoft.com/en-in/azure/azure-resource-manager/templates/overview) +* [Azure Kubernetes Service (AKS) documentation](https://learn.microsoft.com/en-us/azure/aks/) +* [Azure Container Registry documentation](https://learn.microsoft.com/en-us/azure/container-registry/) +* [Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/identity/) +* [Azure networking](https://learn.microsoft.com/en-us/azure/networking/) +* [Azure Virtual Network](https://learn.microsoft.com/en-us/azure/virtual-network/) +* [Azure DNS](https://learn.microsoft.com/en-us/azure/dns/) +* [Azure Private Link](https://learn.microsoft.com/en-us/azure/private-link/) +* [Azure NetApp Files](https://learn.microsoft.com/en-us/azure/azure-netapp-files/) +* [Azure Virtual Machine Scale Sets](https://learn.microsoft.com/en-us/azure/virtual-machine-scale-sets/) +* [Azure Database for MySQL - Flexible Server](https://learn.microsoft.com/en-us/azure/mysql/) +* [Azure Monitor](https://learn.microsoft.com/en-us/azure/azure-monitor/) + +This solution includes automation to deploy in a single-click all the required AKS infrastructure, database server and deploy Magento and dependent components in AKS. + +The ARM template will create and deploy the following resources in your Azure account: +![Magento2 solution architecture](images/magento2-architecture.png) + +* A virtual network with a subnet and a network security group. +* A public IP address and a load balancer. +* A MySQL server and a database for Magento Open Source. +* A Redis cache for Magento Open-Source session and page caching. +* A storage account for Magento Open-Source media files. +* An application insights instance for Magento Open-Source monitoring and analytics. +* A deployment with a specified number of pods that run Magento Open-Source containers. +* A service that exposes the Magento Open-Source pods to the internet. +* A persistent volume claim and a storage class that provide persistent storage for Magento Open-Source data. +* A secret that stores the Magento Open-Source credentials and encryption keys. +* An Azure Database for MySQL – Flexible Server PaaS database for Magento Open Source, the best place for MySQL on Azure. +* An Elasticsearch subchart that deploys an Elasticsearch cluster for Magento Open-Source search functionality. +* A Redis subchart that deploys a Redis server for Magento Open-Source session and page caching. + +## Deployment Steps +The following pre-requisites need to be configured before deploying the ARM template. +1. Create a Resource group in your Azure Subscription to deploy the Magento solution. Please note that a second resource group is created for AKS specific infrastructure deployment with the resource group name as prefix that you created. +2. Get your authentication keys from [Commerce Marketplace](https://commercemarketplace.adobe.com/). You may need to register and generate the public and private keys. Follow Adobe document: [Get your authentication keys | Adobe Commerce](https://experienceleague.adobe.com/en/docs/commerce-operations/installation-guide/prerequisites/authentication-keys) +3. Run the following commands on Azure CLI to create RBAC Role and assign necessary permissions for running the automated script to configure AKS: + +``` +az login + +az ad sp create-for-rbac --name magento2 --role "Azure Kubernetes Service Contributor Role" --scopes /subscriptions//resourceGroups/ + +az role assignment create --assignee --role "CDN Profile Contributor" --scope /subscriptions//resourceGroups/ + +az role assignment create --assignee --role "Virtual Machine Contributor" --scope /subscriptions//resourceGroups/ +``` + +Save the output from the above command as you need to provide this information to the template when deploying in later steps filling required information in ARM deployment. + +## HTTPS using SSL +If using SSL encryption for users to reach the Magento E-Commerce site via HTTPS: +1. Create key vault in the same resource group created initially. +2. Import your certificates for TLS to the same key vault. + +## Deploy the ARM template +To deploy this ARM template, open the Azure CLI, and then run the following command: +``` +az deployment group create --resource-group --template-file azuredeploy.json +``` +See [this article](https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/common-deployment-errors) for troubleshooting the deployment errors. +Alternatively, the following button will allow you to deploy the APM template from Azure portal: [![Deploy to Azure](https://aka.ms/deploytoazurebutton)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-mysql%2Frefs%2Fheads%2Fmaster%2FMagento2%2Fazuredeploy.json) + +## Cleanup resources +To remove this deployment simply remove the following Resource groups: +1. Resource group created as part of AKS infra whose name starts with resource group created in initial pre-requisite step. +2. Resource group created in initial pre-requisite step. + +#### Code of Conduct +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact opencode@microsoft.com with any additional questions or comments. + +#### Legal Notices +Microsoft and any contributors grant you a license to the Microsoft documentation and other content in this repository under the [Creative Commons Attribution 4.0 International Public License](https://creativecommons.org/licenses/by/4.0/legalcode), see the [LICENSE](https://github.com/Azure/azure-mysql/blob/master/Magento2/LICENSE) file, and grant you a license to any code in the repository under the [MIT License](https://opensource.org/licenses/MIT) file. + +Microsoft, Windows, Microsoft Azure and/or other Microsoft products and services referenced in the documentation may be either trademarks or registered trademarks of Microsoft in the United States and/or other countries. The licenses for this project do not grant you rights to use any Microsoft names, logos, or trademarks. Microsoft's general trademark guidelines can be found at [Microsoft Trademarks](https://github.com/Azure/azure-mysql/blob/master/Magento/LICENSE). + +Privacy information can be found at [Privacy at Microsoft](https://privacy.microsoft.com/). Microsoft and any contributors reserve all others rights, whether under their respective copyrights, patents, or trademarks, whether by implication, estoppel or otherwise. \ No newline at end of file diff --git a/Magento2/azuredeploy.json b/Magento2/azuredeploy.json new file mode 100644 index 0000000..fbc3e08 --- /dev/null +++ b/Magento2/azuredeploy.json @@ -0,0 +1,964 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "servicePrincipalAppID": { + "type": "securestring", + "metadata": { + "description": "Provide the Service Principle App ID from the output of the Azure CLI commands to create the RBAC roles in the earlier steps." + } + }, + "servicePrincipalPassword": { + "type": "securestring", + "metadata": { + "description": "Provide the Service Principle App Password from the output of the Azure CLI commands to create the RBAC roles in the earlier steps." + } + }, + "composerUsername": { + "type": "string", + "metadata": { + "description": "Provide the public key from the authentication access keys generated at Commerce Marketplace." + } + }, + "composerPassword": { + "type": "string", + "metadata": { + "description": "Provide the private key from the authentication access keys generated at Commerce Marketplace." + } + }, + "magentoAdminUsername": { + "type": "string", + "defaultValue": "magentoadmin", + "metadata": { + "description": "Provide the username you want for the Magento administator." + } + }, + "magentoAdminPassword": { + "type": "securestring", + "metadata": { + "description": "Provide the password for the Magento administator." + } + }, + "redisCache": { + "type": "bool", + "defaultValue": true, + "metadata": { + "description": "Set this to true for enabling Redis database caching for the Magento application." + } + }, + "varnishCache": { + "type": "bool", + "defaultValue": true, + "metadata": { + "description": "Set this to true for enabling Varnish HTML content cache for Magento application." + } + }, + "azureCDN": { + "type": "bool", + "defaultValue": false, + "metadata": { + "description": "Set this to true for enabling Azure Content Delivery Network (CDN) for static, CSS and scripts for Magento application. (This requires SSL/TLS enabled.)" + } + }, + "SSLEncryptionTLS": { + "type": "bool", + "defaultValue": false, + "metadata": { + "description": "Enable SSL/TLS encryption for users reaching Magento web application over HTTPS." + } + }, + "resourceNamePrefix": { + "type": "string", + "defaultValue": "magento", + "metadata": { + "description": "Provide a prefix for generating resource names as part of the Magento solution." + } + }, + "keyVaultName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "Provide a keyvault name (created in same resource group as pre-requisite) to access certificate for TLS configuration." + } + }, + "certificateName": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "Provide the respective certificate name in key vault for SSL/TLS configuration." + } + }, + "externalFQDN": { + "type": "string", + "defaultValue": "", + "metadata": { + "description": "Provide the external Fully Qualified DNS Name (FQDN) that you have obtained via any web hosting to map to the Magento site." + } + }, + "MYSQLAdministratorLogin": { + "type": "string", + "defaultValue": "mysqlmagento", + "metadata": { + "description": "Admin username for Azure Database for MySQL Flexible Server." + } + }, + "MYSQLAdministratorPassword": { + "type": "securestring", + "metadata": { + "description": "Admin password for Azure Database for MySQL Flexible Server." + } + }, + "MYSQLDatabaseName": { + "type": "string", + "defaultValue": "magento" + }, + "MYSQLServerEdition": { + "type": "string", + "defaultValue": "GeneralPurpose", + "allowedValues": [ + "Burstable", + "GeneralPurpose", + "MemoryOptimized" + ], + "metadata": { + "description": "Choose the Azure Database for MySQL compute tier. High availability is available only for GeneralPurpose and MemoryOptimized Tiers." + } + }, + "MYSQLVersion": { + "type": "string", + "defaultValue": "8.0.21", + "allowedValues": [ + "5.7", + "8.0.21" + ], + "metadata": { + "description": "Choose the MySQL version to be used in Azure Database for MySQL." + } + }, + "MYSQLAvailabilityZone": { + "type": "string", + "defaultValue": "", + "allowedValues": [ + "1", + "2", + "3", + "" + ], + "metadata": { + "description": "Choose the Azure availability zone for the Azure Database for MySQL server, ensure that the zone exists in respective region. (If you don't have a preference, leave this setting blank.)" + } + }, + "MYSQLHighAvailability": { + "type": "string", + "defaultValue": "Disabled", + "allowedValues": [ + "Disabled", + "SameZone", + "ZoneRedundant" + ], + "metadata": { + "description": "Choose High availability mode for Azure Database for MySQL server: Disabled, SameZone, or ZoneRedundant." + } + }, + "MYSQLStandbyAvailabilityZone": { + "type": "string", + "defaultValue": "", + "allowedValues": [ + "1", + "2", + "3", + "" + ], + "metadata": { + "description": "Availability zone of the High availability standby server, ensure that the zone exists in the respective region. (Leave blank for No Preference). Add this value if HA is enabled." + } + }, + "MYSQLStorageSizeGB": { + "defaultValue": 20, + "minValue": 20, + "maxValue": 16384, + "type": "int", + "metadata": { + "description": "Azure database for MySQL storage size in GiB. Storage is used for the database files, temporary files, transaction logs, and the MySQL server logs. In all compute tiers, the minimum storage supported is 20 GiB and maximum is 16 TiB (16384 GiB)." + } + }, + "MYSQLComputeSKU": { + "type": "string", + "defaultValue": "Standard_D2ads_v5", + "allowedValues": [ + "Standard_B1ms", + "Standard_B2ms", + "Standard_B4ms", + "Standard_B8ms", + "Standard_B12ms", + "Standard_B16ms", + "Standard_B20ms", + "Standard_D2ads_v5", + "Standard_D2ds_v4", + "Standard_D4ads_v5", + "Standard_D4ds_v4", + "Standard_D8ads_v5", + "Standard_D8ds_v4", + "Standard_D16ads_v5", + "Standard_D16ds_v4", + "Standard_D32ads_v5", + "Standard_D32ds_v4", + "Standard_D48ads_v5", + "Standard_D48ds_v4", + "Standard_D64ads_v5", + "Standard_D64ds_v4", + "Standard_E2ds_v4", + "Standard_E2ads_v5", + "Standard_E4ds_v4", + "Standard_E4ads_v5", + "Standard_E8ds_v4", + "Standard_E8ads_v5", + "Standard_E16ds_v4", + "Standard_E16ads_v5", + "Standard_E20ds_v4", + "Standard_E20ads_v5", + "Standard_E32ds_v4", + "Standard_E32ads_v5", + "Standard_E48ds_v4", + "Standard_E48ads_v5", + "Standard_E64ds_v4", + "Standard_E64ads_v5", + "Standard_E80ds_v4", + "Standard_E2ds_v5", + "Standard_E4ds_v5", + "Standard_E8ds_v5", + "Standard_E16ds_v5", + "Standard_E20ds_v5", + "Standard_E32ds_v5", + "Standard_E48ds_v5", + "Standard_E64ds_v5", + "Standard_E96ds_v5" + ], + "metadata": { + "description": "The name of the sku for Azure Database for MySQL Flexible Servers, e.g. Standard_D32ds_v4. Complete list is available here : https://learn.microsoft.com/en-us/azure/mysql/flexible-server/concepts-service-tiers-storage. Ensure the SKU capacity is available in the region before selecting from the MySQL Flexible server create page." + } + }, + "MYSQLBackupRetentionDays": { + "type": "int", + "defaultValue": 7, + "minValue": 1, + "maxValue": 35, + "metadata": { + "description": "By default, backups are retained for 7 days. The minimum retention period is 1 day and the maximum retention period is 35 days." + } + }, + "MYSQLGeoRedundantBackup": { + "type": "string", + "defaultValue": "Disabled", + "allowedValues": [ + "Disabled", + "Enabled" + ], + "metadata": { + "description": "Enable Geo-redundant backups for Azure Database for MySQL Flexible Server." + } + }, + "kubernetesSystemNodePoolCount": { + "defaultValue": 1, + "type": "int", + "minValue": 1, + "maxValue": 1000, + "metadata": { + "description": "Specifies the number of agents (VMs) to host docker containers. Allowed values must be in the range of 1 to 1000 (inclusive). The default value is 1." + } + }, + "kubernetesSystemNodePoolVMSize": { + "defaultValue": "Standard_DS2_v2", + "type": "string", + "metadata": { + "description": "Specifies the vm size of nodes in the node pool." + } + }, + "enableSecretRotation": { + "type": "string", + "defaultValue": "true", + "metadata": { + "description": "Accepts value true/false. If true, periodically updates the pod mount and Kubernetes Secret with the latest content from external secrets store." + } + }, + "rotationPollInterval": { + "type": "string", + "defaultValue": "2m", + "metadata": { + "description": "If enableSecretRotation is true, this setting specifies the secret rotation poll interval duration. This duration can be adjusted based on how frequently the mounted contents for all pods and Kubernetes secrets need to be resynced to the latest." + } + }, + "storageAccountName": { + "type": "string", + "defaultValue": "magentostorage", + "metadata": { + "description": "he unique name for Azure Storage Account to host Magento content." + } + }, + "storageAccountSKU": { + "type": "string", + "defaultValue": "Premium_LRS", + "allowedValues": [ + "Premium_LRS", + "Premium_ZRS", + "Standard_GRS", + "Standard_GZRS", + "Standard_LRS", + "Standard_ZRS" + ], + "metadata": { + "description": "Choose the SKU of the storage account." + } + }, + "magentoFileShareQuotaGB": { + "defaultValue": "100", + "type": "string", + "metadata": { + "description": "Size of the azure file share in GB. This quota is for the Magento media and static files. The minimum share size is 100 GB." + } + }, + "elasticsearchFileShareQuotaGB": { + "defaultValue": "100", + "type": "string", + "metadata": { + "description": "Size of the azure file share in GB. This quota is for the elasticsearch. The minimum share size is 100 GB." + } + }, + "VMSize": { + "type": "string", + "defaultValue": "Standard_DS1_v2", + "metadata": { + "description": "Choose the compute size for virtual machine." + } + }, + "VMAdminUsername": { + "type": "string", + "defaultValue": "magentovmadmin", + "metadata": { + "description": "Admin username for the temporary virtual machine used for AKS setup." + } + }, + "VMAdminPassword": { + "type": "securestring", + "metadata": { + "description": "Admin password for the temporary virtual machine used for AKS setup." + } + }, + "SKUAzureCDN": { + "type": "string", + "defaultValue": "Standard_Microsoft", + "allowedValues": [ + "Standard_Akamai", + "Standard_Microsoft", + "Standard_Verizon", + "Premium_Verizon" + ], + "metadata": { + "description": "Provide the profile SKU for the Azure CDN." + } + }, + "magentoAdminEmail": { + "type": "string", + "metadata": { + "description": "The email address for the Magento admin." + } + } + }, + "variables": { + "azureSubscriptionId": "[subscription().subscriptionId]", + "azureResourceGroup": "[resourceGroup().name]", + "tenentId": "[subscription().tenantId]", + "uniqueSuffix": "[uniqueString(resourceGroup().id)]", + "virtualNetworkName": "[concat(parameters('resourceNamePrefix'), '-vnet')]", + "virtualNetworkAddressPrefix": "10.0.0.0/8", + "mySqlVnetSubnetName": "[concat(parameters('resourceNamePrefix'), '-mysql-subnet')]", + "mySqlVnetSubnetAddressPrefix": "10.1.0.0/16", + "kubernetesVnetSubnetName": "[concat(parameters('resourceNamePrefix'), '-kubernetes-subnet')]", + "kubernetesVnetSubnetAddressPrefix": "10.2.0.0/16", + "privateLinksVnetSubnetName": "[concat(parameters('resourceNamePrefix'), '-private-links-subnet')]", + "privateLinksVnetSubnetAddressPrefix": "10.3.0.0/16", + "mySqlServerName": "[concat(parameters('resourceNamePrefix'), '-mysql-', variables('uniqueSuffix'))]", + "kubernetesClusterName": "[concat(parameters('resourceNamePrefix'), '-aks')]", + "kubernetesClusterDnsPrefix": "[concat(parameters('resourceNamePrefix'), '-aks-dns')]", + "kubernetesClusterRoleAssignmentName": "[guid(subscription().subscriptionId, resourceGroup().name, variables('kubernetesClusterName'), variables('kubernetesVnetSubnetName'))]", + "kubernetesClusterSecretProviderRoleAssignmentName": "[guid(parameters('keyVaultName'), variables('kubernetesClusterName'), 'AzureKeyVaultSecretProvider', uniqueString(deployment().name))]", + "cdnProfileName": "[concat(parameters('resourceNamePrefix'), '-cdn')]", + "fileSharePrivateEndpointName": "[concat(parameters('resourceNamePrefix'), '-fs-pe')]", + "enableVirtualMachinePublicIp": true, + "virtualMachinePublicIpAddressesName": "[concat(parameters('resourceNamePrefix'), '-vm-ip')]", + "virtualMachineNetworkInterfaceName": "[concat(parameters('resourceNamePrefix'), '-vm-nic')]", + "virtualMachineName": "[concat(parameters('resourceNamePrefix'), '-vm')]", + "fileSharePrivateIpDeploymentName": "[concat(parameters('resourceNamePrefix'), '-fs-ip-deployment')]", + "filePrivateDnsZoneName": "privatelink.file.core.windows.net", + "mySqlPrivateDnsZoneName": "[concat(variables('uniqueSuffix'), '-mysql.private.mysql.database.azure.com')]", + "storageAccountFileServicesName": "default", + "magentoFileShareName": "magento", + "elasticsearchFileShareName": "elasticsearch", + "magentoCurrency": "USD", + "magentoTimezone": "UTC" + }, + "resources": [ + { + "type": "Microsoft.Network/virtualNetworks", + "name": "[variables('virtualNetworkName')]", + "location": "[resourceGroup().location]", + "apiVersion": "2023-06-01", + "dependsOn": [], + "tags": { + "displayName": "magento-vnet" + }, + "properties": { + "addressSpace": { + "addressPrefixes": [ + "[variables('virtualNetworkAddressPrefix')]" + ] + }, + "subnets": [ + { + "name": "[variables('mySqlVnetSubnetName')]", + "properties": { + "addressPrefix": "[variables('mySqlVnetSubnetAddressPrefix')]", + "delegations": [ + { + "name": "mysql-flexibleServers-subnet-delegation", + "properties": { + "serviceName": "Microsoft.DBforMySQL/flexibleServers" + } + } + ], + "privateEndpointNetworkPolicies": "Enabled", + "privateLinkServiceNetworkPolicies": "Enabled" + } + }, + { + "name": "[variables('kubernetesVnetSubnetName')]", + "properties": { + "addressPrefix": "[variables('kubernetesVnetSubnetAddressPrefix')]" + } + }, + { + "name": "[variables('privateLinksVnetSubnetName')]", + "properties": { + "addressPrefix": "[variables('privateLinksVnetSubnetAddressPrefix')]", + "serviceEndpoints": [ + { + "service": "Microsoft.Sql", + "locations": [ + "[resourceGroup().location]" + ] + }, + { + "service": "Microsoft.Storage", + "locations": [ + "[resourceGroup().location]" + ] + } + ], + "privateEndpointNetworkPolicies": "Disabled", + "privateLinkServiceNetworkPolicies": "Disabled" + } + } + ] + } + }, + { + "type": "Microsoft.Network/privateDnsZones", + "apiVersion": "2020-06-01", + "name": "[variables('mysqlPrivateDnsZoneName')]", + "location": "global", + "properties": {} + }, + { + "type": "Microsoft.Network/privateDnsZones/virtualNetworkLinks", + "apiVersion": "2020-06-01", + "name": "[concat(variables('mysqlPrivateDnsZoneName'), '/', variables('virtualNetworkName'))]", + "location": "global", + "dependsOn": [ + "[resourceId('Microsoft.Network/virtualNetworks', variables('virtualNetworkName'))]", + "[resourceId('Microsoft.Network/privateDnsZones', variables('mysqlPrivateDnsZoneName'))]" + ], + "properties": { + "registrationEnabled": false, + "virtualNetwork": { + "id": "[resourceId('Microsoft.Network/virtualNetworks', variables('virtualNetworkName'))]" + } + } + }, + { + "type": "Microsoft.DBforMySQL/flexibleServers", + "apiVersion": "2023-06-30", + "name": "[variables('mySqlServerName')]", + "location": "[resourceGroup().location]", + "sku": { + "name": "[parameters('MYSQLComputeSKU')]", + "tier": "[parameters('MYSQLServerEdition')]" + }, + "dependsOn": [ + "[resourceId('Microsoft.Network/privateDnsZones', variables('mysqlPrivateDnsZoneName'))]", + "[resourceId('Microsoft.Network/privateDnsZones/virtualNetworkLinks', variables('mysqlPrivateDnsZoneName'), variables('virtualNetworkName'))]" + ], + "properties": { + "version": "[parameters('MYSQLVersion')]", + "administratorLogin": "[parameters('MYSQLAdministratorLogin')]", + "administratorLoginPassword": "[parameters('MYSQLAdministratorPassword')]", + "availabilityZone": "[parameters('MYSQLAvailabilityZone')]", + "highAvailability": { + "mode": "[parameters('MYSQLHighAvailability')]", + "standbyAvailabilityZone": "[parameters('MYSQLStandbyAvailabilityZone')]" + }, + "storageProfile": { + "storageSizeGB": "[parameters('MYSQLStorageSizeGB')]" + }, + "backup": { + "backupRetentionDays": "[parameters('MYSQLBackupRetentionDays')]", + "geoRedundantBackup": "[parameters('MYSQLGeoRedundantBackup')]" + }, + "createMode": "Default", + "network": { + "delegatedSubnetResourceId": "[format('{0}/subnets/{1}', reference(resourceId('Microsoft.Network/privateDnsZones/virtualNetworkLinks', variables('mysqlPrivateDnsZoneName'), variables('virtualNetworkName'))).virtualNetwork.id, variables('mySqlVnetSubnetName'))]", + "privateDnsZoneResourceId": "[resourceId('Microsoft.Network/privateDnsZones', variables('mysqlPrivateDnsZoneName'))]" + } + }, + "resources": [ + { + "type": "configurations", + "name": "log_bin_trust_function_creators", + "apiVersion": "2023-06-30", + "location": "[resourceGroup().location]", + "properties": { + "value": "ON", + "source": "user-override" + }, + "dependsOn": [ + "[resourceId('Microsoft.DBforMySQL/flexibleServers', variables('mySqlServerName'))]" + ] + }, + { + "type": "configurations", + "name": "require_secure_transport", + "apiVersion": "2023-06-30", + "location": "[resourceGroup().location]", + "properties": { + "value": "OFF", + "source": "user-override" + }, + "dependsOn": [ + "[resourceId('Microsoft.DBforMySQL/flexibleServers', variables('mySqlServerName'))]" + ] + }, + { + "type": "databases", + "apiVersion": "2023-06-30", + "name": "[parameters('MYSQLDatabaseName')]", + "dependsOn": [ + "[resourceId('Microsoft.DBforMySQL/flexibleServers', variables('mySqlServerName'))]" + ], + "properties": { + "charset": "utf8", + "collation": "utf8_general_ci" + } + } + ], + "tags": { + "PackagedApp": "Magento2" + } + }, + { + "type": "Microsoft.ContainerService/managedClusters", + "apiVersion": "2023-07-01", + "name": "[variables('kubernetesClusterName')]", + "location": "[resourceGroup().location]", + "dependsOn": [ + "[resourceId('Microsoft.Network/virtualNetworks', variables('virtualNetworkName'))]" + ], + "identity": { + "type": "SystemAssigned" + }, + "properties": { + "kubernetesVersion": "1.29", + "dnsPrefix": "[variables('kubernetesClusterDnsPrefix')]", + "agentPoolProfiles": [ + { + "name": "agentpool", + "mode": "System", + "count": "[parameters('kubernetesSystemNodePoolCount')]", + "VMSize": "[parameters('kubernetesSystemNodePoolVMSize')]", + "osDiskSizeGB": 0, + "vnetSubnetID": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('virtualNetworkName'), variables('kubernetesVnetSubnetName'))]", + "type": "VirtualMachineScaleSets", + "osType": "Linux", + "storageProfile": "ManagedDisks" + } + ], + "servicePrincipalProfile": { + "clientId": "msi" + }, + "enableRBAC": true, + "networkProfile": { + "networkPlugin": "azure", + "loadBalancerSku": "standard", + "serviceCidr": "10.4.0.0/16", + "dnsServiceIP": "10.4.0.10", + "dockerBridgeCidr": "172.17.0.1/16" + }, + "addonProfiles": { + "azureKeyvaultSecretsProvider": { + "enabled": true, + "config": { + "enableSecretRotation": "[parameters('enableSecretRotation')]", + "rotationPollInterval": "[parameters('rotationPollInterval')]" + } + } + } + }, + "tags": { + "PackagedApp": "Magento2" + } + }, + { + "condition": "[parameters('SSLEncryptionTLS')]", + "type": "Microsoft.KeyVault/vaults/providers/roleAssignments", + "apiVersion": "2020-04-01-preview", + "name": "[concat(if(parameters('SSLEncryptionTLS'), parameters('keyVaultName'), 'no-keyvault'), '/', 'Microsoft.Authorization/', variables('kubernetesClusterSecretProviderRoleAssignmentName'))]", + "dependsOn": [ + "[resourceId('Microsoft.Network/virtualNetworks', variables('virtualNetworkName'))]", + "[resourceId('Microsoft.ContainerService/managedClusters', variables('kubernetesClusterName'))]" + ], + "properties": { + "principalId": "[reference(resourceId('Microsoft.ContainerService/managedClusters', variables('kubernetesClusterName')), '2023-01-01').addonProfiles.azureKeyvaultSecretsProvider.identity.objectId]", + "roleDefinitionId": "[subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '4633458b-17de-408a-b874-0445c86b69e6')]", + "scope": "[resourceId('Microsoft.KeyVault/vaults', parameters('keyVaultName'))]" + } + }, + { + "type": "Microsoft.Network/virtualNetworks/subnets/providers/roleAssignments", + "apiVersion": "2022-04-01", + "name": "[concat(variables('virtualNetworkName'), '/', variables('kubernetesVnetSubnetName'), '/Microsoft.Authorization/', variables('kubernetesClusterRoleAssignmentName'))]", + "dependsOn": [ + "[resourceId('Microsoft.Network/virtualNetworks', variables('virtualNetworkName'))]", + "[resourceId('Microsoft.ContainerService/managedClusters', variables('kubernetesClusterName'))]" + ], + "properties": { + "roleDefinitionId": "[subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '4d97b98b-1d4f-4787-a291-c67834d212e7')]", + "principalId": "[reference(resourceId('Microsoft.ContainerService/managedClusters/', variables('kubernetesClusterName')), '2023-10-01', 'Full').identity.principalId]", + "scope": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('virtualNetworkName'), variables('kubernetesVnetSubnetName'))]" + } + }, + { + "condition": "[parameters('azureCDN')]", + "name": "[variables('cdnProfileName')]", + "type": "Microsoft.Cdn/profiles", + "location": "[resourceGroup().location]", + "apiVersion": "2023-05-01", + "sku": { + "name": "[parameters('SKUAzureCDN')]" + }, + "properties": {} + }, + { + "type": "Microsoft.Storage/storageAccounts", + "apiVersion": "2022-09-01", + "name": "[parameters('storageAccountName')]", + "location": "[resourceGroup().location]", + "sku": { + "name": "[parameters('storageAccountSKU')]" + }, + "kind": "FileStorage", + "properties": { + "minimumTlsVersion": "TLS1_0", + "allowBlobPublicAccess": false, + "largeFileSharesState": "Enabled", + "supportsHttpsTrafficOnly": true + } + }, + { + "type": "Microsoft.Storage/storageAccounts/fileServices", + "apiVersion": "2023-04-01", + "name": "[concat(parameters('storageAccountName'), '/', variables('storageAccountFileServicesName'))]", + "dependsOn": [ + "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))]" + ], + "sku": { + "name": "[parameters('storageAccountSKU')]" + }, + "properties": {} + }, + { + "type": "Microsoft.Storage/storageAccounts/fileServices/shares", + "apiVersion": "2023-04-01", + "name": "[concat(parameters('storageAccountName'), '/', variables('storageAccountFileServicesName'), '/', variables('magentoFileShareName'))]", + "dependsOn": [ + "[resourceId('Microsoft.Storage/storageAccounts/fileServices', parameters('storageAccountName'), variables('storageAccountFileServicesName'))]" + ], + "properties": { + "accessTier": "[if(or(equals(parameters('storageAccountSKU'), 'Premium_LRS'), equals(parameters('storageAccountSKU'), 'Premium_ZRS')), 'Premium', 'TransactionOptimized')]", + "shareQuota": "[parameters('magentoFileShareQuotaGB')]", + "enabledProtocols": "SMB" + } + }, + { + "type": "Microsoft.Storage/storageAccounts/fileServices/shares", + "apiVersion": "2023-04-01", + "name": "[concat(parameters('storageAccountName'), '/', variables('storageAccountFileServicesName'), '/', variables('elasticsearchFileShareName'))]", + "dependsOn": [ + "[resourceId('Microsoft.Storage/storageAccounts/fileServices', parameters('storageAccountName'), variables('storageAccountFileServicesName'))]" + ], + "properties": { + "accessTier": "[if(or(equals(parameters('storageAccountSKU'), 'Premium_LRS'), equals(parameters('storageAccountSKU'), 'Premium_ZRS')), 'Premium', 'TransactionOptimized')]", + "shareQuota": "[parameters('elasticsearchFileShareQuotaGB')]", + "enabledProtocols": "SMB" + } + }, + { + "type": "Microsoft.Network/privateEndpoints", + "apiVersion": "2023-06-01", + "name": "[variables('fileSharePrivateEndpointName')]", + "location": "[resourceGroup().location]", + "dependsOn": [ + "[resourceId('Microsoft.Network/virtualNetworks', variables('virtualNetworkName'))]", + "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))]" + ], + "properties": { + "privateLinkServiceConnections": [ + { + "name": "[concat(parameters('resourceNamePrefix'), '-fs-pe-plsc')]", + "properties": { + "privateLinkServiceId": "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))]", + "groupIds": [ + "file" + ] + } + } + ], + "subnet": { + "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('virtualNetworkName'), variables('privateLinksVnetSubnetName'))]" + } + } + }, + { + "type": "Microsoft.Resources/deployments", + "apiVersion": "2019-10-01", + "name": "[variables('fileSharePrivateIpDeploymentName')]", + "dependsOn": [ + "[resourceId('Microsoft.Network/privateEndpoints', variables('fileSharePrivateEndpointName'))]" + ], + "properties": { + "mode": "Incremental", + "expressionEvaluationOptions": { + "scope": "inner" + }, + "parameters": { + "networkInterfaceId": { + "value": "[reference(resourceId('Microsoft.Network/privateEndpoints', variables('fileSharePrivateEndpointName')), '2020-05-01').networkInterfaces[0].id]" + } + }, + "template": { + "$schema": "https://schema.management.azure.com/schemas/2019-08-01/deploymentTemplate.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "networkInterfaceId": { + "type": "string" + } + }, + "variables": {}, + "resources": [], + "outputs": { + "privateIpAddress": { + "type": "string", + "value": "[reference(parameters('networkInterfaceId'), '2020-05-01').ipConfigurations[0].properties.privateIpAddress]" + } + } + } + } + }, + { + "type": "Microsoft.Network/privateDnsZones", + "apiVersion": "2020-06-01", + "name": "[variables('filePrivateDnsZoneName')]", + "location": "global", + "properties": {} + }, + { + "type": "Microsoft.Network/privateDnsZones/A", + "apiVersion": "2020-06-01", + "name": "[concat(variables('filePrivateDnsZoneName'), '/', parameters('storageAccountName'))]", + "dependsOn": [ + "[resourceId('Microsoft.Network/privateDnsZones', variables('filePrivateDnsZoneName'))]", + "[resourceId('Microsoft.Resources/deployments', variables('fileSharePrivateIpDeploymentName'))]" + ], + "properties": { + "ttl": 3600, + "aRecords": [ + { + "ipv4Address": "[reference(variables('fileSharePrivateIpDeploymentName')).outputs.privateIpAddress.value]" + } + ] + } + }, + { + "type": "Microsoft.Network/privateDnsZones/virtualNetworkLinks", + "apiVersion": "2018-09-01", + "name": "[concat(variables('filePrivateDnsZoneName'), '/', variables('virtualNetworkName'))]", + "location": "global", + "dependsOn": [ + "[resourceId('Microsoft.Network/virtualNetworks', variables('virtualNetworkName'))]", + "[resourceId('Microsoft.Network/privateDnsZones', variables('filePrivateDnsZoneName'))]" + ], + "properties": { + "registrationEnabled": false, + "virtualNetwork": { + "id": "[resourceId('Microsoft.Network/virtualNetworks', variables('virtualNetworkName'))]" + } + } + }, + { + "condition": "[equals(variables('enableVirtualMachinePublicIp'), true())]", + "type": "Microsoft.Network/publicIPAddresses", + "apiVersion": "2023-06-01", + "name": "[variables('virtualMachinePublicIpAddressesName')]", + "location": "[resourceGroup().location]", + "properties": { + "publicIPAllocationMethod": "Dynamic" + } + }, + { + "condition": "[equals(variables('enableVirtualMachinePublicIp'), true())]", + "type": "Microsoft.Network/networkInterfaces", + "apiVersion": "2023-06-01", + "name": "[variables('virtualMachineNetworkInterfaceName')]", + "location": "[resourceGroup().location]", + "dependsOn": [ + "[resourceId('Microsoft.Network/virtualNetworks', variables('virtualNetworkName'))]", + "[resourceId('Microsoft.Network/publicIPAddresses', variables('virtualMachinePublicIpAddressesName'))]" + ], + "properties": { + "ipConfigurations": [ + { + "name": "ipconfig1", + "properties": { + "subnet": { + "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('virtualNetworkName'), variables('kubernetesVnetSubnetName'))]" + }, + "privateIPAllocationMethod": "Dynamic", + "publicIPAddress": { + "id": "[resourceId('Microsoft.Network/publicIPAddresses', variables('virtualMachinePublicIpAddressesName'))]" + } + } + } + ] + } + }, + { + "condition": "[equals(variables('enableVirtualMachinePublicIp'), false())]", + "type": "Microsoft.Network/networkInterfaces", + "apiVersion": "2023-06-01", + "name": "[variables('virtualMachineNetworkInterfaceName')]", + "location": "[resourceGroup().location]", + "dependsOn": [ + "[resourceId('Microsoft.Network/virtualNetworks', variables('virtualNetworkName'))]", + "[resourceId('Microsoft.Network/publicIPAddresses', variables('virtualMachinePublicIpAddressesName'))]" + ], + "properties": { + "ipConfigurations": [ + { + "name": "ipconfig1", + "properties": { + "subnet": { + "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('virtualNetworkName'), variables('kubernetesVnetSubnetName'))]" + }, + "privateIPAllocationMethod": "Dynamic" + } + } + ] + } + }, + { + "type": "Microsoft.Compute/virtualMachines", + "apiVersion": "2023-03-01", + "name": "[variables('virtualMachineName')]", + "location": "[resourceGroup().location]", + "dependsOn": [ + "[resourceId('Microsoft.Network/networkInterfaces', variables('virtualMachineNetworkInterfaceName'))]" + ], + "properties": { + "hardwareProfile": { + "VMSize": "[parameters('VMSize')]" + }, + "osProfile": { + "computerName": "[variables('virtualMachineName')]", + "adminUsername": "[parameters('VMAdminUsername')]", + "adminPassword": "[parameters('VMAdminPassword')]" + }, + "storageProfile": { + "imageReference": { + "publisher": "Canonical", + "offer": "UbuntuServer", + "sku": "18.04-LTS", + "version": "latest" + }, + "osDisk": { + "name": "[concat(parameters('resourceNamePrefix'), '-vm-osdisk')]", + "createOption": "FromImage", + "deleteOption": "Delete" + } + }, + "networkProfile": { + "networkInterfaces": [ + { + "id": "[resourceId('Microsoft.Network/networkInterfaces', variables('virtualMachineNetworkInterfaceName'))]", + "properties": { + "primary": true, + "deleteOption": "Delete" + } + } + ] + } + } + }, + { + "type": "Microsoft.Compute/virtualMachines/extensions", + "apiVersion": "2023-03-01", + "name": "[concat(variables('virtualMachineName'), '/CustomScriptExtension')]", + "location": "[resourceGroup().location]", + "dependsOn": [ + "[resourceId('Microsoft.Network/publicIPAddresses', variables('virtualMachinePublicIpAddressesName'))]", + "[resourceId('Microsoft.Compute/virtualMachines', variables('virtualMachineName'))]", + "[resourceId('Microsoft.DBforMySQL/flexibleServers', variables('mySqlServerName'))]", + "[resourceId('Microsoft.Cdn/profiles', variables('cdnProfileName'))]", + "[resourceId('Microsoft.ContainerService/managedClusters', variables('kubernetesClusterName'))]", + "[resourceId('Microsoft.Network/virtualNetworks/subnets/providers/roleAssignments', variables('virtualNetworkName'), variables('kubernetesVnetSubnetName'), 'Microsoft.Authorization', variables('kubernetesClusterRoleAssignmentName'))]", + "[resourceId('Microsoft.Storage/storageAccounts/fileServices/shares', parameters('storageAccountName'), variables('storageAccountFileServicesName'), variables('magentoFileShareName'))]", + "[resourceId('Microsoft.Network/privateDnsZones/A', variables('filePrivateDnsZoneName'), parameters('storageAccountName'))]", + "[resourceId('Microsoft.Network/privateDnsZones/virtualNetworkLinks', variables('filePrivateDnsZoneName'), variables('virtualNetworkName'))]" + ], + "properties": { + "publisher": "Microsoft.Azure.Extensions", + "type": "CustomScript", + "typeHandlerVersion": "2.1", + "autoUpgradeMinorVersion": true, + "ForceUpdateTag": "1.0", + "protectedSettings": { + "fileUris": [ + "https://raw.githubusercontent.com/aakagarwal/azure-mysql/refs/heads/master/Magento2/deploy-aks.sh" + ], + "commandToExecute": "[concat('bash deploy-aks.sh ', variables('azureSubscriptionId'), ' ', variables('azureResourceGroup'), ' ', parameters('servicePrincipalAppId'), ' ', parameters('servicePrincipalPassword'), ' ', variables('tenentId'), ' ', parameters('composerUsername'), ' ', parameters('composerPassword'), ' ', concat(variables('mySqlServerName'), '.', variables('mySqlPrivateDnsZoneName')), ' ', parameters('MYSQLAdministratorLogin'), ' ', parameters('MYSQLAdministratorPassword'), ' ', variables('kubernetesClusterName'), ' ', parameters('storageAccountName'), ' ', listKeys(resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName')), '2022-09-01').keys[0].value, ' ', parameters('magentoAdminUsername'), ' ', parameters('magentoAdminPassword'), ' ', variables('virtualMachineName'), ' ', if(not(empty(parameters('externalFQDN'))), parameters('externalFQDN'), 'EXTERNAL_FQDN'), ' ', variables('cdnProfileName'), ' ', parameters('redisCache'), ' ', parameters('varnishCache'), ' ', parameters('azureCDN'), ' ', parameters('SSLEncryptionTLS'), ' ', reference(resourceId('Microsoft.ContainerService/managedClusters', variables('kubernetesClusterName')), '2023-01-01').addonProfiles.azureKeyvaultSecretsProvider.identity.clientId, ' ', if(parameters('SSLEncryptionTLS'), parameters('keyVaultName'), 'KEYVAULT_NAME'), ' ', if(parameters('SSLEncryptionTLS'), parameters('certificateName'), 'CERTIFICATE_NAME'), ' ', parameters('magentoAdminEmail'), ' ', variables('magentoCurrency'), ' ', variables('magentoTimezone'))]" + }, + "settings": {} + } + } + ], + "outputs": { + "mySqlServerHostName": { + "type": "string", + "value": "[concat(variables('mySqlServerName'), '.', variables('mySqlPrivateDnsZoneName'))]" + }, + "kubernetesClusterName": { + "type": "string", + "value": "[variables('kubernetesClusterName')]" + }, + "storageAccountName": { + "type": "string", + "value": "[parameters('storageAccountName')]" + } + } +} \ No newline at end of file diff --git a/Magento2/deploy-aks.sh b/Magento2/deploy-aks.sh new file mode 100644 index 0000000..05a0aed --- /dev/null +++ b/Magento2/deploy-aks.sh @@ -0,0 +1,425 @@ +#!/bin/bash + +# Exit immediately if a command exits with a non-zero status +set -e + +# Log file +LOG_FILE="deploy-aks.log" + +# Redirect stdout and stderr to log file +exec > >(tee -a $LOG_FILE) 2>&1 + +waitAndGetExternalIpForService() { + local service_name=$1 + local namespace=$2 + local external_ip="" + while [ -z "$external_ip" ]; do + echo "Waiting for external IP..." >&2 + external_ip=$(sudo kubectl get service $service_name -n $namespace --output jsonpath='{.status.loadBalancer.ingress[0].ip}') + if [ -z "$external_ip" ]; then + sleep 10 + fi + done + echo $external_ip +} + +# Parameters +AZURE_SUBSCRIPTION_ID=$1 +AZURE_RESOURCE_GROUP=$2 +SERVICE_PRINCIPAL_APP_ID=$3 +SERVICE_PRINCIPAL_PASSWORD=$4 +TENANT_ID=$5 +COMPOSER_USERNAME=$6 +COMPOSER_PASSWORD=$7 +MY_SQL_SERVER_HOST_NAME=$8 +MY_SQL_SERVER_ADMIN_LOGIN=$9 +MY_SQL_SERVER_ADMIN_PASSWORD=${10} +AKS_CLUSTER_NAME=${11} +STORAGE_ACCOUNT_ACCESS_NAME=${12} +STORAGE_ACCOUNT_ACCESS_KEY=${13} +MAGENTO_ADMIN_USERNAME=${14} +MAGENTO_ADMIN_PASSWORD=${15} +VIRTUAL_MACHINE_NAME=${16} +EXTERNAL_FQDN=${17} +CDN_PROFILE_NAME=${18} +REDIS_CACHE_SWITCH=${19} +VARNISH_CACHE_SWITCH=${20} +CDN_SWITCH=${21} +TLS_SWITCH=${22} +AKS_SECRET_PROVIDER_CLIENT_ID=${23} +KEYVAULT_NAME=${24} +CERTIFICATE_NAME=${25} +MAGENTO_ADMIN_EMAIL=${26} +MAGENTO_CURRENCY=${27} +MAGENTO_TIMEZONE=${28} + +# Printing all parameters +echo "AZURE_SUBSCRIPTION_ID: $AZURE_SUBSCRIPTION_ID" +echo "AZURE_RESOURCE_GROUP: $AZURE_RESOURCE_GROUP" +echo "SERVICE_PRINCIPAL_APP_ID: $SERVICE_PRINCIPAL_APP_ID" +echo "SERVICE_PRINCIPAL_PASSWORD: $SERVICE_PRINCIPAL_PASSWORD" +echo "TENANT_ID: $TENANT_ID" +echo "COMPOSER_USERNAME: $COMPOSER_USERNAME" +echo "COMPOSER_PASSWORD: $COMPOSER_PASSWORD" +echo "MY_SQL_SERVER_HOST_NAME: $MY_SQL_SERVER_HOST_NAME" +echo "MY_SQL_SERVER_ADMIN_LOGIN: $MY_SQL_SERVER_ADMIN_LOGIN" +echo "MY_SQL_SERVER_ADMIN_PASSWORD: $MY_SQL_SERVER_ADMIN_PASSWORD" +echo "AKS_CLUSTER_NAME: $AKS_CLUSTER_NAME" +echo "STORAGE_ACCOUNT_ACCESS_NAME: $STORAGE_ACCOUNT_ACCESS_NAME" +echo "STORAGE_ACCOUNT_ACCESS_KEY: $STORAGE_ACCOUNT_ACCESS_KEY" +echo "MAGENTO_ADMIN_USERNAME: $MAGENTO_ADMIN_USERNAME" +echo "MAGENTO_ADMIN_PASSWORD: $MAGENTO_ADMIN_PASSWORD" +echo "VIRTUAL_MACHINE_NAME: $VIRTUAL_MACHINE_NAME" +echo "EXTERNAL_FQDN: $EXTERNAL_FQDN" +echo "CDN_PROFILE_NAME: $CDN_PROFILE_NAME" +echo "REDIS_CACHE_SWITCH: $REDIS_CACHE_SWITCH" +echo "VARNISH_CACHE_SWITCH: $VARNISH_CACHE_SWITCH" +echo "CDN_SWITCH: $CDN_SWITCH" +echo "TLS_SWITCH: $TLS_SWITCH" +echo "AKS_SECRET_PROVIDER_CLIENT_ID: $AKS_SECRET_PROVIDER_CLIENT_ID" +echo "KEYVAULT_NAME: $KEYVAULT_NAME" +echo "CERTIFICATE_NAME: $CERTIFICATE_NAME" +echo "MAGENTO_ADMIN_EMAIL: $MAGENTO_ADMIN_EMAIL" +echo "MAGENTO_CURRENCY: $MAGENTO_CURRENCY" +echo "MAGENTO_TIMEZONE: $MAGENTO_TIMEZONE" + +echo "External FQDN: $EXTERNAL_FQDN" +# Mocking External FQDN (if not provided) +if [ "${EXTERNAL_FQDN}" = "EXTERNAL_FQDN" ]; then + EXTERNAL_FQDN='' +fi +echo "Final External FQDN: $EXTERNAL_FQDN" + +echo "KeyVault Name: $KEYVAULT_NAME" +# Mocking KeyVault Name (if not provided) +if [ "${KEYVAULT_NAME}" = "KEYVAULT_NAME" ]; then + KEYVAULT_NAME='' +fi +echo "Final KeyVault Name: $KEYVAULT_NAME" + +echo "Certificate Name: $CERTIFICATE_NAME" +# Mocking Certificate Name (if not provided) +if [ "${CERTIFICATE_NAME}" = "CERTIFICATE_NAME" ]; then + CERTIFICATE_NAME='' +fi +echo "Final Certificate Name: $CERTIFICATE_NAME" + + +# Variables +aks_namespace="magento" + +# Install Azure CLI +echo "Installing Azure CLI..." +curl -sL https://aka.ms/InstallAzureCLIDeb | bash + +# Install kubectl +echo "Installing kubectl..." +sudo az aks install-cli + +# Install Helm +echo "Installing Helm..." +curl https://baltocdn.com/helm/signing.asc | gpg --dearmor | sudo tee /usr/share/keyrings/helm.gpg > /dev/null +sudo apt-get install apt-transport-https --yes +echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/helm.gpg] https://baltocdn.com/helm/stable/debian/ all main" | sudo tee /etc/apt/sources.list.d/helm-stable-debian.list +sudo apt-get update +sudo apt-get install helm + +# Login to Azure using Service Principal +echo "Logging into Azure..." +sudo az login --service-principal --username "$SERVICE_PRINCIPAL_APP_ID" --password "$SERVICE_PRINCIPAL_PASSWORD" --tenant "$TENANT_ID" + +# Set the Azure subscription +echo "Setting the Azure subscription..." +sudo az account set --subscription "$AZURE_SUBSCRIPTION_ID" + +# Get AKS credentials +echo "Getting AKS credentials..." +while [[ $(sudo az aks show -g "$AZURE_RESOURCE_GROUP" -n "$AKS_CLUSTER_NAME" --query "provisioningState" -o tsv) != "Succeeded" ]]; do + echo "Waiting for AKS cluster "$AKS_CLUSTER_NAME" in resource group "$AZURE_RESOURCE_GROUP" to be provisioned..." + sleep 10s +done +sudo az aks get-credentials --resource-group "$AZURE_RESOURCE_GROUP" --name "$AKS_CLUSTER_NAME" + +# Test sudo kubectl access +echo "Testing sudo kubectl access..." +sudo kubectl get nodes + +# Start deploying to ASK Cluster +echo "Deploying to AKS Cluster..." + +# Defining deployment file URLs +echo "Deploying YAML configurations..." +file_base_url="https://raw.githubusercontent.com/aakagarwal/azure-mysql/refs/heads/master/Magento2/Kubernetes" + +# Create the namespace +echo "Creating namespace..." +curl -s "$file_base_url/namespace.yaml" | sudo kubectl apply -f - + +# Applying the secret(s) according to Infra deployment +echo "Applying secrets..." +sudo kubectl create secret generic input-secrets -n $aks_namespace \ + --from-literal=MAGENTO_DATABASE_USER=$MY_SQL_SERVER_ADMIN_LOGIN \ + --from-literal=MAGENTO_DATABASE_PASSWORD=$MY_SQL_SERVER_ADMIN_PASSWORD \ + --from-literal=MAGENTO_ADMIN_USER=$MAGENTO_ADMIN_USERNAME \ + --from-literal=MAGENTO_ADMIN_PASSWORD=$MAGENTO_ADMIN_PASSWORD \ + --from-literal=COMPOSER_USERNAME=$COMPOSER_USERNAME \ + --from-literal=COMPOSER_PASSWORD=$COMPOSER_PASSWORD \ + --from-literal=azurestorageaccountname=$STORAGE_ACCOUNT_ACCESS_NAME \ + --from-literal=azurestorageaccountkey=$STORAGE_ACCOUNT_ACCESS_KEY \ + --dry-run=client -o yaml | sudo kubectl apply -f - + +# Add the ingress-nginx repository +echo "Adding ingress-nginx repository..." +sudo helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx +sudo helm repo update + +# Install nginx-ingress controller +echo "Installing nginx-ingress controller..." +sudo helm upgrade --install ingress-nginx ingress-nginx/ingress-nginx \ + --namespace $aks_namespace \ + --set controller.replicaCount=1 \ + --set controller.nodeSelector."kubernetes\.io/os"=linux \ + --set defaultBackend.nodeSelector."beta\.kubernetes\.io/os"=linux \ + --set controller.service.externalTrafficPolicy=Local + +# Get the external IP of the Ingress Controller +echo "Getting external IP of the Ingress Controller..." +external_ip_service_name="ingress-nginx-controller" +external_ip_address=$(waitAndGetExternalIpForService $external_ip_service_name $aks_namespace) +echo "External IP Address: $external_ip_address" + +# Applying the input configmap according to Infra deployment +echo "Applying configmaps..." +magento_base_url="" +magento_base_url_secure="" +cdn_origin="" +if [ -n "$EXTERNAL_FQDN" ]; then + magento_base_url="http://$EXTERNAL_FQDN:80/" + magento_base_url_secure="https://$EXTERNAL_FQDN:443/" + cdn_origin=$EXTERNAL_FQDN +else + magento_base_url="http://$external_ip_address:80/" + magento_base_url_secure="https://$external_ip_address:443/" + cdn_origin=$external_ip_address +fi + +echo "Magento Base URL: $magento_base_url" +echo "Magento Base URL Secure: $magento_base_url_secure" +echo "CDN Origin: $cdn_origin" + +CDN_STATIC_ENDPOINT_HOST="" +CDN_MEDIA_ENDPOINT_HOST="" +if [ "${CDN_SWITCH}" = "true" ] || [ "${CDN_SWITCH}" = "True" ]; then + # Create CDN Endpoint for static + echo "Creating CDN Endpoint for static..." + sudo az cdn endpoint create \ + --endpoint-name magento-static \ + --profile-name $CDN_PROFILE_NAME \ + --resource-group $AZURE_RESOURCE_GROUP \ + --origin-host-header $cdn_origin \ + --origin $cdn_origin + + # Create CDN Endpoint rule for static + echo "Creating CDN Endpoint rule for static..." + sudo az cdn endpoint rule add \ + --profile-name $CDN_PROFILE_NAME \ + --resource-group $AZURE_RESOURCE_GROUP \ + --name magento-static \ + --rule-name Global \ + --order 0 \ + --action-name ModifyResponseHeader \ + --header-action Overwrite \ + --header-name Access-Control-Allow-Origin \ + --header-value "*" + + # Get CDN URL for static + echo "Getting CDN URL for static..." + CDN_STATIC_ENDPOINT_HOST=$(sudo az cdn endpoint show \ + --endpoint-name magento-static \ + --profile-name $CDN_PROFILE_NAME \ + --resource-group $AZURE_RESOURCE_GROUP \ + --query "hostName" \ + --output tsv) + + # Create CDN Endpoint for media + echo "Creating CDN Endpoint for media..." + sudo az cdn endpoint create \ + --endpoint-name magento-media \ + --profile-name $CDN_PROFILE_NAME \ + --resource-group $AZURE_RESOURCE_GROUP \ + --origin-host-header $cdn_origin \ + --origin $cdn_origin + + # Create CDN Endpoint rule for media + echo "Creating CDN Endpoint rule for media..." + sudo az cdn endpoint rule add \ + --profile-name $CDN_PROFILE_NAME \ + --resource-group $AZURE_RESOURCE_GROUP \ + --name magento-media \ + --rule-name Global \ + --order 0 \ + --action-name ModifyResponseHeader \ + --header-action Overwrite \ + --header-name Access-Control-Allow-Origin \ + --header-value "*" + + # Get CDN URL for media + echo "Getting CDN URL for media..." + CDN_MEDIA_ENDPOINT_HOST=$(sudo az cdn endpoint show \ + --endpoint-name magento-media \ + --profile-name $CDN_PROFILE_NAME \ + --resource-group $AZURE_RESOURCE_GROUP \ + --query "hostName" \ + --output tsv) +else + CDN_STATIC_ENDPOINT_HOST=$cdn_origin + CDN_MEDIA_ENDPOINT_HOST=$cdn_origin +fi +echo "CDN Static Endpoint Host: $CDN_STATIC_ENDPOINT_HOST" +echo "CDN Media Endpoint Host: $CDN_MEDIA_ENDPOINT_HOST" + + +CDN_STATIC_URL="http://$CDN_STATIC_ENDPOINT_HOST/static/" +CDN_MEDIA_URL="http://$CDN_MEDIA_ENDPOINT_HOST/media/" + +# Using HTTP for CDN URLs if TLS is not enabled because of self-signed certificate error at CDN +if [ "${TLS_SWITCH}" = "true" ] || [ "${TLS_SWITCH}" = "True" ]; then + CDN_STATIC_URL_SECURE="https://$CDN_STATIC_ENDPOINT_HOST/static/" + CDN_MEDIA_URL_SECURE="https://$CDN_MEDIA_ENDPOINT_HOST/media/" +else + CDN_STATIC_URL_SECURE="http://$CDN_STATIC_ENDPOINT_HOST/static/" + CDN_MEDIA_URL_SECURE="http://$CDN_MEDIA_ENDPOINT_HOST/media/" +fi + +echo "CDN Static URL: $CDN_STATIC_URL" +echo "CDN Media URL: $CDN_MEDIA_URL" +echo "CDN Static URL Secure: $CDN_STATIC_URL_SECURE" +echo "CDN Media URL Secure: $CDN_MEDIA_URL_SECURE" + +# Apply Input Configmap +echo "Applying Input Configmap..." +sudo kubectl create configmap input-config -n $aks_namespace \ + --from-literal=MAGENTO_BASE_URL=$magento_base_url \ + --from-literal=MAGENTO_BASE_URL_SECURE=$magento_base_url_secure \ + --from-literal=MAGENTO_ADMIN_EMAIL=$MAGENTO_ADMIN_EMAIL \ + --from-literal=MAGENTO_CURRENCY=$MAGENTO_CURRENCY \ + --from-literal=MAGENTO_TIMEZONE=$MAGENTO_TIMEZONE \ + --from-literal=DATABASE_HOST=$MY_SQL_SERVER_HOST_NAME \ + --from-literal=MAGENTO_BASE_URL_STATIC=$CDN_STATIC_URL \ + --from-literal=MAGENTO_BASE_URL_MEDIA=$CDN_MEDIA_URL \ + --from-literal=MAGENTO_BASE_URL_STATIC_SECURE=$CDN_STATIC_URL_SECURE \ + --from-literal=MAGENTO_BASE_URL_MEDIA_SECURE=$CDN_MEDIA_URL_SECURE \ + --from-literal=REDIS_CACHE_SWITCH=$REDIS_CACHE_SWITCH \ + --from-literal=VARNISH_CACHE_SWITCH=$VARNISH_CACHE_SWITCH \ + --from-literal=CDN_SWITCH=$CDN_SWITCH \ + --dry-run=client -o yaml | sudo kubectl apply -f - + +# Apply Storage Class +echo "Applying Storage Class..." +curl -s "$file_base_url/azurefile/sc.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - + + +# Deploy Elasticsearch +# Apply Elasticsearch PV & PVC +echo "Applying Elasticsearch PV & PVC..." +curl -s "$file_base_url/elasticsearch/pv.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - +curl -s "$file_base_url/elasticsearch/pvc.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - +# Apply Elasticserach Service +echo "Applying Elasticsearch service..." +curl -s "$file_base_url/elasticsearch/services.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - +# Apply Elasticsearch StatefulSet +echo "Applying Elasticsearch StatefulSet..." +curl -s "$file_base_url/elasticsearch/statefulset.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - + +# Deploy Redis (if required) +if [ "${REDIS_CACHE_SWITCH}" = "true" ] || [ "${REDIS_CACHE_SWITCH}" = "True" ]; then + # Apply Redis Service + echo "Applying Redis Service..." + curl -s "$file_base_url/redis/services.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - + # Apply Redis StatefulSet + echo "Applying Redis StatefulSet..." + curl -s "$file_base_url/redis/statefulset.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - +fi + +# Deploy Magento +# Apply Magento Configmap +echo "Applying Magento Configmap..." +curl -s "$file_base_url/magento/configmap.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - +# Apply Magento PV & PVC +echo "Applying Magento PV & PVC..." +curl -s "$file_base_url/magento/pv.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - +curl -s "$file_base_url/magento/pvc.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - +# Apply Magento Services +echo "Applying Magento Services..." +curl -s "$file_base_url/magento/services.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - +# Apply Magento Job Deployment +echo "Applying Magento job Deployment..." +curl -s "$file_base_url/magento/job.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - +# Wait for the job to complete (timeout 30 minutes) +echo "Waiting for the job to complete..." +sudo kubectl wait --for=condition=complete --timeout=1800s job/magento-setup-job -n $aks_namespace +# Apply Magento server Deployment +echo "Applying Magento server Deployment..." +curl -s "$file_base_url/magento/deployment.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - +# Apply Magento Cron Deployment +echo "Applying Magento cron Deployment..." +curl -s "$file_base_url/magento/cron.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - + +# Deeploy Varnish (if required) +backend_service="" +backend_service_port="" +if [ "${VARNISH_CACHE_SWITCH}" = "true" ] || [ "${VARNISH_CACHE_SWITCH}" = "True" ]; then + # Apply Varnish Configmap + echo "Applying Varnish Configmap..." + curl -s "$file_base_url/varnish/configmap.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - + # Apply Varnish Services + echo "Applying Varnish Services..." + curl -s "$file_base_url/varnish/services.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - + # Apply Varnish Deployment + echo "Applying Varnish Deployment..." + curl -s "$file_base_url/varnish/deployment.yaml?$sas_token" | sudo kubectl apply -n $aks_namespace -f - + backend_service="varnish-service" + backend_service_port="80" +else + backend_service="magento-service" + backend_service_port="8080" +fi + +# Deploy tls (if required) and ingress +if [ "${TLS_SWITCH}" = "true" ] || [ "${TLS_SWITCH}" = "True" ]; then + # Apply TLS Secret Provider + echo "Applying TLS Secret Provider..." + curl -s "$file_base_url/tls/secret-provider.yaml?$sas_token" | \ + sed -e "s/__USER_ASSIGNED_IDENTITY_ID__/${AKS_SECRET_PROVIDER_CLIENT_ID}/g" \ + -e "s/__KEYVAULT_NAME__/${KEYVAULT_NAME}/g" \ + -e "s/__CERTIFICATE_NAME__/${CERTIFICATE_NAME}/g" \ + -e "s/__TENANT_ID__/${TENANT_ID}/g" | \ + sudo kubectl apply -n "$aks_namespace" -f - + + # Certing TLS Cert Pod + echo "Certing TLS Cert Pod..." + curl -s "$file_base_url/tls/cert-pod.yaml?$sas_token" | sudo kubectl apply -n "$aks_namespace" -f - + + # Apply nginx Ingress with TLS + echo "Applying nginx Ingress with TLS..." + curl -s "$file_base_url/ingress/ingress-tls.yaml?$sas_token" | \ + sed -e "s/__FQDN__/${EXTERNAL_FQDN}/g" \ + -e "s/__SERVICE_NAME__/${backend_service}/g" \ + -e "s/__SERVICE_PORT__/${backend_service_port}/g" | \ + sudo kubectl apply -n "$aks_namespace" -f - +else + # Apply nginx Ingress without TLS + echo "Applying nginx Ingress without TLS..." + curl -s "$file_base_url/ingress/ingress.yaml?$sas_token" | \ + sed -e "s/__SERVICE_NAME__/${backend_service}/g" \ + -e "s/__SERVICE_PORT__/${backend_service_port}/g" | \ + sudo kubectl apply -n "$aks_namespace" -f - +fi + +# Ensure the log file is accessible +chmod 644 $LOG_FILE +echo "Log file can be found at: $LOG_FILE" + +# Schedule VM deletion in 10 seconds +echo "Scheduled VM deletion in 10 seconds..." +nohup bash -c "sleep 10 && sudo az vm delete --resource-group $AZURE_RESOURCE_GROUP --name $VIRTUAL_MACHINE_NAME --yes --no-wait" > deploy-aks.log 2>&1 & diff --git a/Magento2/images/magento2-architecture.png b/Magento2/images/magento2-architecture.png new file mode 100644 index 0000000..35e9c0b Binary files /dev/null and b/Magento2/images/magento2-architecture.png differ