

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Connect flotte gestite dai servizi a un server di licenze personalizzato
<a name="smf-byol"></a>

Puoi portare il tuo server di licenza da utilizzare con una flotta gestita dai servizi Deadline Cloud. Per portare la tua licenza, puoi configurare un server di licenze utilizzando un ambiente di coda nella tua farm. Per configurare il server di licenza, è necessario disporre già di una farm e di una coda.

La modalità di connessione a un server di licenze software dipende dalla configurazione del parco macchine e dai requisiti del fornitore del software. In genere, si accede al server in due modi:
+ Direttamente al server delle licenze. I tuoi dipendenti ottengono una licenza dal server di licenza del fornitore del software tramite Internet. Tutti i dipendenti devono essere in grado di connettersi al server.
+ Tramite un proxy di licenza. I dipendenti si connettono a un server proxy nella rete locale. Solo il server proxy può connettersi al server di licenza del fornitore tramite Internet.

Con le istruzioni riportate di seguito, usi Amazon EC2 Systems Manager (SSM) per inoltrare le porte da un'istanza di lavoro al server di licenza o all'istanza proxy. Nell'esempio seguente, se il server di licenza non è in grado di fornire una licenza, verranno utilizzate le licenze basate sull'utilizzo di Deadline Cloud. Rimuovi le sezioni che non si applicano alla tua pipeline o ai prodotti per i quali non desideri utilizzare licenze basate sull'utilizzo dopo aver esaurito le licenze.

**Topics**
+ [Fase 1: Configurare l'ambiente di coda](#configure-queue-environment)
+ [Fase 2: (Facoltativo) Configurazione dell'istanza del proxy di licenza](#license-proxy)
+ [CloudFormation Fase 3: configurazione del modello](#byol-cfn-template)

## Fase 1: Configurare l'ambiente di coda
<a name="configure-queue-environment"></a>



Puoi configurare un ambiente di coda nella tua coda per accedere al tuo server di licenza. Innanzitutto, assicurati di avere un' AWS istanza configurata con l'accesso al server di licenza utilizzando uno dei seguenti metodi:
+ Server di licenza: l'istanza ospita direttamente i server di licenza.
+ Proxy di licenza: l'istanza ha accesso di rete al server delle licenze e inoltra le porte del server di licenza al server delle licenze. Per i dettagli su come configurare un'istanza del proxy di licenza, consulta[Fase 2: (Facoltativo) Configurazione dell'istanza del proxy di licenza](#license-proxy).

Per informazioni sulla configurazione delle variabili di ambiente di licenza, vedere[Fase 3: Connettere un'applicazione di rendering a un endpoint](cmf-ubl.md). Per una configurazione personalizzata del server di licenza, l'indirizzo del server di licenza rimane localhost anziché l'endpoint Amazon VPC.

**Per aggiungere le autorizzazioni necessarie al ruolo di coda**

1. Dalla [console Deadline Cloud](https://console.aws.amazon.com/deadlinecloud/home), scegli **Vai alla** dashboard.

1. Dalla dashboard, seleziona la farm, quindi la coda che desideri configurare.

1. Da Queue details > service role, seleziona il ruolo.

1. Scegli **Aggiungi autorizzazione**, quindi scegli **Crea politica in linea**.

1. Seleziona l'editor di policy JSON, quindi copia e incolla il seguente testo nell'editor.

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Sid": "",
               "Effect": "Allow",
               "Action": [
                   "ssm:StartSession"
               ],
               "Resource": [
                   "arn:aws:ssm:us-east-1::document/AWS-StartPortForwardingSession",
                   "arn:aws:ec2:us-east-1:111122223333:instance/instance_id"
               ]
           }
       ]
   }
   ```

------

1. Prima di salvare la nuova policy, sostituisci i seguenti valori nel testo della policy:
   + Sostituisci `region` con la AWS regione in cui si trova la tua azienda
   + Sostituiscilo `instance_id` con l'ID dell'istanza del server di licenza o dell'istanza proxy che stai utilizzando
   + `account_id`Sostituiscilo con il numero di AWS conto contenente la tua fattoria

1. Scegli **Next (Successivo)**.

1. Per il nome della politica, inserisci**LicenseForwarding**.

1. Scegli **Crea politica** per salvare le modifiche e creare la politica con le autorizzazioni richieste.

**Per aggiungere un nuovo ambiente di coda alla coda**

1. Dalla [console Deadline Cloud](https://console.aws.amazon.com/deadlinecloud/home), scegli **Vai alla dashboard** se non l'hai già fatto.

1. Dalla dashboard, seleziona la farm, quindi la coda che desideri configurare.

1. Scegli **Ambienti di coda** > **Azioni** > **Crea nuovo con** YAML.

1. Copia e incolla il seguente testo nell'editor di script YAML.

------
#### [ Windows ]

   ```
   specificationVersion: "environment-2023-09"
   parameterDefinitions:
    - name: LicenseInstanceId
      type: STRING
      description: >
       The Instance ID of the license server/proxy instance
      default: ""
    - name: LicenseInstanceRegion
      type: STRING
      description: >
       The region containing this farm
      default: ""
    - name: LicensePorts
      type: STRING
      description: >
       Comma-separated list of ports to be forwarded to the license server/proxy
       instance. Example: "2701,2702,7075,2703,6101,1715,1716,1717,7054,7055,30304"
      default: "2701,2702,7075,2703,6101,1715,1716,1717,7054,7055,30304"
   environment:
    name: BYOL License Forwarding
    variables:
     example_LICENSE: 2701@localhost
    script:
     actions:
      onEnter:
       command: bash
       args: [ "{{Env.File.Enter}}" ]
      onExit:
       command: bash
       args: [ "{{Env.File.Exit}}" ]
     embeddedFiles:
      - name: Enter
        type: TEXT
        runnable: True
        data: |
         curl "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/windows/SessionManagerPlugin.zip" -o "{{Session.WorkingDirectory}}/ssm-plugin.zip"
         powershell -Command "Expand-Archive -Path '{{Session.WorkingDirectory}}/ssm-plugin.zip' -DestinationPath '{{Session.WorkingDirectory}}/ssm-plugin' -Force; Expand-Archive -Path '{{Session.WorkingDirectory}}/ssm-plugin/package.zip' -DestinationPath '{{Session.WorkingDirectory}}/ssm-plugin/package' -Force"
         conda activate
         python "{{Env.File.StartSession}}" "{{Session.WorkingDirectory}}/ssm-plugin/package/bin/session-manager-plugin.exe"
      - name: Exit
        type: TEXT
        runnable: True
        data: |
         echo Killing SSM Manager Plugin PIDs: $BYOL_SSM_PIDS
         for pid in ${BYOL_SSM_PIDS//,/ }; do kill $pid; done
      - name: StartSession
        type: TEXT
        data: |
         import boto3
         import json
         import subprocess
         import sys
         import os
         import tempfile
   
         instance_id = "{{Param.LicenseInstanceId}}"
         region = "{{Param.LicenseInstanceRegion}}"
         license_ports_list = "{{Param.LicensePorts}}".split(",")
   
         ssm_client = boto3.client("ssm", region_name=region)
         pids = []
   
         for port in license_ports_list:
           session_response = ssm_client.start_session(
             Target=instance_id,
             DocumentName="AWS-StartPortForwardingSession",
             Parameters={"portNumber": [port], "localPortNumber": [port]}
           )
   
           cmd = [
             sys.argv[1],
             json.dumps(session_response),
             region,
             "StartSession",
             "",
             json.dumps({"Target": instance_id}),
             f"https://ssm.{region}.amazonaws.com"
           ]
   
           process = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
           pids.append(process.pid)
           print(f"SSM Port Forwarding Session started for port {port}")
   
         print(f"openjd_env: BYOL_SSM_PIDS={','.join(str(pid) for pid in pids)}")
   
         # Enabling UBL after the BYOL has run out requires prepending the BYOL configuration to the existing license setup
         # Remove the sections that do not apply to your pipeline, or you do not want to use UBL after exhausting the BYOL licenses.
         # The port numbers used may not match what your license server is serving.
   
         # Arnold
         os.environ["ADSKFLEX_LICENSE_FILE"] = f"2701@localhost;{os.environ.get('ADSKFLEX_LICENSE_FILE', '')}"
         print(f"openjd_env: ADSKFLEX_LICENSE_FILE={os.environ['ADSKFLEX_LICENSE_FILE']}")
   
         # Cinema4D
         os.environ["g_licenseServerRLM"] = f"localhost:7057;{os.environ.get('g_licenseServerRLM', '')}"
         print(f"openjd_env: g_licenseServerRLM={os.environ['g_licenseServerRLM']}")
   
         # Nuke
         os.environ["foundry_LICENSE"] = f"6101@localhost;{os.environ.get('foundry_LICENSE', '')}"
         print(f"openjd_env: foundry_LICENSE={os.environ['foundry_LICENSE']}")
   
         # SideFX
         os.environ["SESI_LMHOST"] = f"localhost:1715;{os.environ.get('SESI_LMHOST', '')}"
         print(f"openjd_env: SESI_LMHOST={os.environ['SESI_LMHOST']}")
   
         # Redshift and Red Giant
         os.environ["redshift_LICENSE"] = f"7054@localhost;7055@localhost;{os.environ.get('redshift_LICENSE', '')}"
         print(f"openjd_env: redshift_LICENSE={os.environ['redshift_LICENSE']}")
   
         # V-Ray doesn't support multiple license servers in a single environment variable
         # See https://documentation.chaos.com/space/LIC5/125050770/Sharing+a+License+Configuration+in+a+Network
         vray_license = os.environ.get('VRAY_AUTH_CLIENT_SETTINGS', '')
         xml_content = """<VRLClient>
           <LicServer>
             <Host>localhost</Host>
             <Port>30304</Port>"""
   
         if vray_license and vray_license.startswith('licset://'):
             server_parts = vray_license.removeprefix('licset://').split(':')
             if len(server_parts) >= 2:
                 xml_content += f"""
             <Host1>{server_parts[0]}</Host1>
             <Port1>{server_parts[1]}</Port1>"""
   
         xml_content += """
             <User></User>
             <Pass></Pass>
           </LicServer>
         </VRLClient>"""
   
         temp_dir = tempfile.gettempdir()
         xml_path = os.path.join(temp_dir, 'vrlclient.xml')
         
         with open(xml_path, 'w') as f:
             f.write(xml_content)
   
         os.environ["VRAY_AUTH_CLIENT_FILE_PATH"] = temp_dir
         print(f"openjd_env: VRAY_AUTH_CLIENT_FILE_PATH={os.environ['VRAY_AUTH_CLIENT_FILE_PATH']}")
   
         # Clear the existing VRAY_AUTH_CLIENT_SETTINGS so only the vrlclient.xml file is used.
         os.environ["VRAY_AUTH_CLIENT_SETTINGS"] = ''
         print(f"openjd_env: VRAY_AUTH_CLIENT_SETTINGS={os.environ['VRAY_AUTH_CLIENT_SETTINGS']}")
   
         # Print out the created xml file's contents
         print(f"V-Ray configuration file: {xml_path}")
         with open(xml_path, 'r') as f:
             print(f"{f.read()}")
   ```

------
#### [ Linux ]

   ```
   specificationVersion: "environment-2023-09"
   parameterDefinitions:
    - name: LicenseInstanceId
      type: STRING
      description: >
       The Instance ID of the license server/proxy instance
      default: ""
    - name: LicenseInstanceRegion
      type: STRING
      description: >
       The region containing this farm
      default: ""
    - name: LicensePorts
      type: STRING
      description: >
       Comma-separated list of ports to be forwarded to the license server/proxy
       instance. Example: "2701,2702,7075,2703,6101,1715,1716,1717,7054,7055,30304"
      default: "2701,2702,7075,2703,6101,1715,1716,1717,7054,7055,30304"
   environment:
    name: BYOL License Forwarding
    variables:
     example_LICENSE: 2701@localhost
    script:
     actions:
      onEnter:
       command: bash
       args: [ "{{Env.File.Enter}}" ]
      onExit:
       command: bash
       args: [ "{{Env.File.Exit}}" ]
     embeddedFiles:
      - name: Enter
        type: TEXT
        runnable: True
        data: |
         curl https://s3.amazonaws.com/session-manager-downloads/plugin/latest/linux_64bit/session-manager-plugin.rpm -Ls | rpm2cpio - | cpio -iv --to-stdout ./usr/local/sessionmanagerplugin/bin/session-manager-plugin > {{Session.WorkingDirectory}}/session-manager-plugin
         chmod +x {{Session.WorkingDirectory}}/session-manager-plugin
         conda activate
         python {{Env.File.StartSession}} {{Session.WorkingDirectory}}/session-manager-plugin
      - name: Exit
        type: TEXT
        runnable: True
        data: |
         echo Killing SSM Manager Plugin PIDs: $BYOL_SSM_PIDS
         for pid in ${BYOL_SSM_PIDS//,/ }; do kill $pid; done
      - name: StartSession
        type: TEXT
        data: |
         import boto3
         import json
         import subprocess
         import sys
         import os
         import tempfile
   
         instance_id = "{{Param.LicenseInstanceId}}"
         region = "{{Param.LicenseInstanceRegion}}"
         license_ports_list = "{{Param.LicensePorts}}".split(",")
   
         ssm_client = boto3.client("ssm", region_name=region)
         pids = []
   
         for port in license_ports_list:
           session_response = ssm_client.start_session(
             Target=instance_id,
             DocumentName="AWS-StartPortForwardingSession",
             Parameters={"portNumber": [port], "localPortNumber": [port]}
           )
   
           cmd = [
             sys.argv[1],
             json.dumps(session_response),
             region,
             "StartSession",
             "",
             json.dumps({"Target": instance_id}),
             f"https://ssm.{region}.amazonaws.com"
           ]
   
           process = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
           pids.append(process.pid)
           print(f"SSM Port Forwarding Session started for port {port}")
   
         print(f"openjd_env: BYOL_SSM_PIDS={','.join(str(pid) for pid in pids)}")
   
         # Enabling UBL after the BYOL has run out requires prepending the BYOL configuration to the existing license setup
         # Remove the sections that do not apply to your pipeline, or you do not want to use UBL after exhausting the BYOL licenses.
         # The port numbers used may not match what your license server is serving.
   
         # Arnold
         os.environ["ADSKFLEX_LICENSE_FILE"] = f"2701@localhost:{os.environ.get('ADSKFLEX_LICENSE_FILE', '')}"
         print(f"openjd_env: ADSKFLEX_LICENSE_FILE={os.environ['ADSKFLEX_LICENSE_FILE']}")
   
         # Nuke
         os.environ["foundry_LICENSE"] = f"6101@localhost:{os.environ.get('foundry_LICENSE', '')}"
         print(f"openjd_env: foundry_LICENSE={os.environ['foundry_LICENSE']}")
   
         # SideFX
         os.environ["SESI_LMHOST"] = f"localhost:1715;{os.environ.get('SESI_LMHOST', '')}"
         print(f"openjd_env: SESI_LMHOST={os.environ['SESI_LMHOST']}")
   
         # Redshift and Red Giant
         os.environ["redshift_LICENSE"] = f"7054@localhost:7055@localhost:{os.environ.get('redshift_LICENSE', '')}"
         print(f"openjd_env: redshift_LICENSE={os.environ['redshift_LICENSE']}")
   
         # V-Ray doesn't support multiple license servers in a single environment variable
         # See https://documentation.chaos.com/space/LIC5/125050770/Sharing+a+License+Configuration+in+a+Network
         vray_license = os.environ.get('VRAY_AUTH_CLIENT_SETTINGS', '')
         xml_content = """<VRLClient>
           <LicServer>
             <Host>localhost</Host>
             <Port>30304</Port>"""
   
         if vray_license and vray_license.startswith('licset://'):
             server_parts = vray_license.removeprefix('licset://').split(':')
             if len(server_parts) >= 2:
                 xml_content += f"""
             <Host1>{server_parts[0]}</Host1>
             <Port1>{server_parts[1]}</Port1>"""
   
         xml_content += """
             <User></User>
             <Pass></Pass>
           </LicServer>
         </VRLClient>"""
   
         temp_dir = tempfile.gettempdir()
         xml_path = os.path.join(temp_dir, 'vrlclient.xml')
         
         with open(xml_path, 'w') as f:
             f.write(xml_content)
   
         os.environ["VRAY_AUTH_CLIENT_FILE_PATH"] = temp_dir
         print(f"openjd_env: VRAY_AUTH_CLIENT_FILE_PATH={os.environ['VRAY_AUTH_CLIENT_FILE_PATH']}")
   
         # Clear the existing VRAY_AUTH_CLIENT_SETTINGS so only the vrlclient.xml file is used.
         os.environ["VRAY_AUTH_CLIENT_SETTINGS"] = ''
         print(f"openjd_env: VRAY_AUTH_CLIENT_SETTINGS={os.environ['VRAY_AUTH_CLIENT_SETTINGS']}")
   
         # Print out the created xml file's contents
         print(f"V-Ray configuration file: {xml_path}")
         with open(xml_path, 'r') as f:
             print(f"{f.read()}")
   ```

------

1. Prima di salvare l'ambiente della coda, apportate le seguenti modifiche al testo dell'ambiente, se necessario:
   + Aggiorna i valori predefiniti per i seguenti parametri in modo che rispecchino il tuo ambiente:
     + **LicenseInstanceID**: l'ID dell'istanza Amazon EC2 del server di licenza o dell'istanza proxy
     + **LicenseInstanceRegion**— La AWS regione in cui si trova la tua fattoria
     + **LicensePorts**— Un elenco di porte separate da virgole da inoltrare al server di licenza o all'istanza proxy (ad esempio 2700,2701)
   + Se desideri utilizzare le licenze basate sull'utilizzo (UBL) dopo aver esaurito la licenza Bring your own license (BYOL), assicurati che la porta sia corretta per il tuo server di licenze. Se non desiderate utilizzare UBL dopo aver esaurito il BYOL, aggiungete le variabili di ambiente di licenza necessarie alla sezione variabili.

      Queste variabili dovrebbero DCCs indirizzarlo a localhost sulla porta del server di licenza. Ad esempio, se il server di licenza Foundry è in ascolto sulla porta 6101, dovresti aggiungere la variabile come. **foundry\$1LICENSE: 6101@localhost**

1. (Facoltativo) È possibile lasciare **la priorità** impostata su **0** oppure modificarla per ordinare la priorità in modo diverso tra più ambienti di coda.

1. Scegli **Crea ambiente di coda** per salvare il nuovo ambiente.

   Con l'ambiente di coda impostato, i lavori inviati a questa coda recupereranno le licenze dal server di licenza configurato.

## Fase 2: (Facoltativo) Configurazione dell'istanza del proxy di licenza
<a name="license-proxy"></a>

In alternativa all'utilizzo di un server di licenza, puoi utilizzare un proxy di licenza. Per creare un proxy di licenza, crea una nuova istanza Amazon Linux 2023 con accesso di rete al server delle licenze. Se necessario, puoi configurare questo accesso utilizzando una connessione VPN. Per ulteriori informazioni, consulta le [connessioni VPN](https://docs.aws.amazon.com/vpc/latest/userguide/vpn-connections.html) nella *Amazon VPC User* Guide.

Per configurare un'istanza proxy di licenza per Deadline Cloud, segui i passaggi di questa procedura. Esegui i seguenti passaggi di configurazione su questa nuova istanza per consentire l'inoltro del traffico delle licenze al tuo server di licenza

1. Per installare il HAProxy pacchetto, inserisci

   ```
   sudo yum install haproxy
   ```

1. Aggiorna la sezione listen license-server del file di configurazione **etc/haproxy/haproxy/.cfg** con quanto segue:

   1. Sostituisci **LicensePort1** e **LicensePort2** con i numeri di porta da inoltrare al server delle licenze. Aggiungi o rimuovi valori separati da virgole per soddisfare il numero di porte richiesto.

   1. Sostituire **LicenseServerHost**con il nome host o l'indirizzo IP del server di licenza.

   ```
   lobal
       log         127.0.0.1 local2
       chroot      /var/lib/haproxy
       user        haproxy
       group       haproxy
       daemon
   
   defaults
       timeout queue           1m
       timeout connect         10s
       timeout client          1m
       timeout server          1m
       timeout http-keep-alive 10s
       timeout check           10s
   
   listen license-server
        bind *:LicensePort1,*:LicensePort2
        server license-server LicenseServerHost
   ```

1. Per abilitare e avviare il HAProxy servizio, esegui i seguenti comandi:

   ```
   sudo systemctl enable haproxy
   sudo service haproxy start
   ```

Dopo aver completato i passaggi, le richieste di licenza inviate a localhost dall'ambiente della coda di inoltro devono essere inoltrate al server di licenza specificato.

## CloudFormation Fase 3: configurazione del modello
<a name="byol-cfn-template"></a>

Puoi utilizzare un CloudFormation modello per configurare un'intera farm in modo che utilizzi le tue licenze.

1. **Modifica il modello fornito nel passaggio successivo per aggiungere eventuali variabili di ambiente di licenza richieste alla sezione **BYOLQueuevariabili** in Ambiente.**

1. Utilizza il seguente CloudFormation modello.

   ```
   AWSTemplateFormatVersion: 2010-09-09
   Description: "Create &ADC; resources for BYOL"
   
   Parameters:
     LicenseInstanceId:
       Type: AWS::EC2::Instance::Id
       Description: Instance ID for the license server/proxy instance
     LicensePorts:
       Type: String
       Description: Comma-separated list of ports to forward to the license instance
   
   Resources:
     JobAttachmentBucket:
       Type: AWS::S3::Bucket
       Properties:
         BucketName: !Sub byol-example-ja-bucket-${AWS::AccountId}-${AWS::Region}
         BucketEncryption:
           ServerSideEncryptionConfiguration:
             - ServerSideEncryptionByDefault:
                 SSEAlgorithm: AES256
   
     Farm:
       Type: AWS::Deadline::Farm
       Properties:
         DisplayName: BYOLFarm
   
     QueuePolicy:
       Type: AWS::IAM::ManagedPolicy
       Properties:
         ManagedPolicyName: BYOLQueuePolicy
         PolicyDocument:
           Version: 2012-10-17
           Statement:
             - Effect: Allow
               Action:
                 - s3:GetObject
                 - s3:PutObject
                 - s3:ListBucket
                 - s3:GetBucketLocation
               Resource:
                 - !Sub ${JobAttachmentBucket.Arn}
                 - !Sub ${JobAttachmentBucket.Arn}/job-attachments/*
               Condition:
                 StringEquals:
                   aws:ResourceAccount: !Sub ${AWS::AccountId}
             - Effect: Allow
               Action: logs:GetLogEvents
               Resource: !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/deadline/${Farm.FarmId}/*
             - Effect: Allow
               Action:
                 - s3:ListBucket
                 - s3:GetObject
               Resource:
                 - "*"
               Condition:
                 ArnLike:
                   s3:DataAccessPointArn:
                     - arn:aws:s3:*:*:accesspoint/deadline-software-*
                 StringEquals:
                   s3:AccessPointNetworkOrigin: VPC
     
     BYOLSSMPolicy:
       Type: AWS::IAM::ManagedPolicy
       Properties:
         ManagedPolicyName: BYOLSSMPolicy
         PolicyDocument:
           Version: 2012-10-17
           Statement:
             - Effect: Allow
               Action:
                 - ssm:StartSession
               Resource:
                 - !Sub arn:aws:ssm:${AWS::Region}::document/AWS-StartPortForwardingSession
                 - !Sub arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:instance/${LicenseInstanceId}
   
   
     WorkerPolicy:
       Type: AWS::IAM::ManagedPolicy
       Properties:
         ManagedPolicyName: BYOLWorkerPolicy
         PolicyDocument:
           Version: 2012-10-17
           Statement:
             - Effect: Allow
               Action:
                 - logs:CreateLogStream
               Resource: !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/deadline/${Farm.FarmId}/*
               Condition:
                 ForAnyValue:StringEquals:
                   aws:CalledVia:
                     - deadline.amazonaws.com
             - Effect: Allow
               Action:
                 - logs:PutLogEvents
                 - logs:GetLogEvents
               Resource: !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/deadline/${Farm.FarmId}/*
               
   
     QueueRole:
       Type: AWS::IAM::Role
       Properties:
         RoleName: BYOLQueueRole
         ManagedPolicyArns:
           - !Ref QueuePolicy
           - !Ref BYOLSSMPolicy
         AssumeRolePolicyDocument:
           Version: 2012-10-17
           Statement:
             - Effect: Allow
               Action:
                 - sts:AssumeRole
               Principal:
                 Service:
                   - credentials.deadline.amazonaws.com
                   - deadline.amazonaws.com
               Condition:
                 StringEquals:
                   aws:SourceAccount: !Sub ${AWS::AccountId}
                 ArnEquals:
                   aws:SourceArn: !Ref Farm
   
     WorkerRole:
       Type: AWS::IAM::Role
       Properties:
         RoleName: BYOLWorkerRole
         ManagedPolicyArns:
           - arn:aws:iam::aws:policy/AWSDeadlineCloud-FleetWorker
           - !Ref WorkerPolicy
         AssumeRolePolicyDocument:
           Version: 2012-10-17
           Statement:
             - Effect: Allow
               Action:
                 - sts:AssumeRole
               Principal:
                 Service: credentials.deadline.amazonaws.com
   
   
     Queue:
       Type: AWS::Deadline::Queue
       Properties:
         DisplayName: BYOLQueue
         FarmId: !GetAtt Farm.FarmId
         RoleArn: !GetAtt QueueRole.Arn
         JobRunAsUser:
           Posix:
             Group: ""
             User: ""
           RunAs: WORKER_AGENT_USER
         JobAttachmentSettings:
           RootPrefix: job-attachments
           S3BucketName: !Ref JobAttachmentBucket
     
     Fleet:
       Type: AWS::Deadline::Fleet
       Properties:
         DisplayName: BYOLFleet
         FarmId: !GetAtt Farm.FarmId
         MinWorkerCount: 1
         MaxWorkerCount: 2
         Configuration:
           ServiceManagedEc2:
             InstanceCapabilities:
               VCpuCount:
                 Min: 4
                 Max: 16
               MemoryMiB:
                 Min: 4096
                 Max: 16384
               OsFamily: LINUX
               CpuArchitectureType: x86_64
             InstanceMarketOptions:
               Type: on-demand
         RoleArn: !GetAtt WorkerRole.Arn
   
     QFA:
       Type: AWS::Deadline::QueueFleetAssociation
       Properties:
         FarmId: !GetAtt Farm.FarmId
         FleetId: !GetAtt Fleet.FleetId
         QueueId: !GetAtt Queue.QueueId
     
     CondaQueueEnvironment:
       Type: AWS::Deadline::QueueEnvironment
       Properties:
         FarmId: !GetAtt Farm.FarmId
         Priority: 5
         QueueId: !GetAtt Queue.QueueId
         TemplateType: YAML
         Template: |
           specificationVersion: 'environment-2023-09'
           parameterDefinitions:
           - name: CondaPackages
             type: STRING
             description: >
               This is a space-separated list of conda package match specifications to install for the job.
               E.g. "blender=3.6" for a job that renders frames in Blender 3.6.
   
               See https://docs.conda.io/projects/conda/en/latest/user-guide/concepts/pkg-specs.html#package-match-specifications
             default: ""
             userInterface:
               control: LINE_EDIT
               label: Conda Packages
           - name: CondaChannels
             type: STRING
             description: >
               This is a space-separated list of conda channels from which to install packages. &ADC; SMF packages are
               installed from the "deadline-cloud" channel that is configured by &ADC;.
   
               Add "conda-forge" to get packages from the https://conda-forge.org/ community, and "defaults" to get packages
               from Anaconda Inc (make sure your usage complies with https://www.anaconda.com/terms-of-use).
             default: "deadline-cloud"
             userInterface:
               control: LINE_EDIT
               label: Conda Channels
           environment:
             name: Conda
             script:
               actions:
                 onEnter:
                   command: "conda-queue-env-enter"
                   args: ["{{Session.WorkingDirectory}}/.env", "--packages", "{{Param.CondaPackages}}", "--channels", "{{Param.CondaChannels}}"]
                 onExit:
                   command: "conda-queue-env-exit"
     
     BYOLQueueEnvironment:
       Type: AWS::Deadline::QueueEnvironment
       Properties:
         FarmId: !GetAtt Farm.FarmId
         Priority: 10
         QueueId: !GetAtt Queue.QueueId
         TemplateType: YAML
         Template: !Sub |
           specificationVersion: "environment-2023-09"
           parameterDefinitions:
           - name: LicenseInstanceId
             type: STRING
             description: >
               The Instance ID of the license server/proxy instance
             default: ""
           - name: LicenseInstanceRegion
             type: STRING
             description: >
               The region containing this farm
             default: ""
           - name: LicensePorts
             type: STRING
             description: >
               Comma-separated list of ports to be forwarded to the license server/proxy
               instance. Example: "2701,2702,7075,2703,6101,1715,1716,1717,7054,7055,30304"
             default: "2701,2702,7075,2703,6101,1715,1716,1717,7054,7055,30304"
           environment:
           name: BYOL License Forwarding
           variables:
             example_LICENSE: 2701@localhost
           script:
             actions:
             onEnter:
               command: bash
               args: [ "{{Env.File.Enter}}" ]
             onExit:
               command: bash
               args: [ "{{Env.File.Exit}}" ]
             embeddedFiles:
             - name: Enter
               type: TEXT
               runnable: True
               data: |
                 curl https://s3.amazonaws.com/session-manager-downloads/plugin/latest/linux_64bit/session-manager-plugin.rpm -Ls | rpm2cpio - | cpio -iv --to-stdout ./usr/local/sessionmanagerplugin/bin/session-manager-plugin > {{Session.WorkingDirectory}}/session-manager-plugin
                 chmod +x {{Session.WorkingDirectory}}/session-manager-plugin
                 conda activate
                 python {{Env.File.StartSession}} {{Session.WorkingDirectory}}/session-manager-plugin
             - name: Exit
               type: TEXT
               runnable: True
               data: |
                 echo Killing SSM Manager Plugin PIDs: $BYOL_SSM_PIDS
                 for pid in ${BYOL_SSM_PIDS//,/ }; do kill $pid; done
             - name: StartSession
               type: TEXT
               data: |
                 import boto3
                 import json
                 import subprocess
                 import sys
                 import os
                 import tempfile
   
                 instance_id = "{{Param.LicenseInstanceId}}"
                 region = "{{Param.LicenseInstanceRegion}}"
                 license_ports_list = "{{Param.LicensePorts}}".split(",")
   
                 ssm_client = boto3.client("ssm", region_name=region)
                 pids = []
   
                 for port in license_ports_list:
                   session_response = ssm_client.start_session(
                     Target=instance_id,
                     DocumentName="AWS-StartPortForwardingSession",
                     Parameters={"portNumber": [port], "localPortNumber": [port]}
                   )
   
                   cmd = [
                     sys.argv[1],
                     json.dumps(session_response),
                     region,
                     "StartSession",
                     "",
                     json.dumps({"Target": instance_id}),
                     f"https://ssm.{region}.amazonaws.com"
                   ]
   
                   process = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                   pids.append(process.pid)
                   print(f"SSM Port Forwarding Session started for port {port}")
   
                 print(f"openjd_env: BYOL_SSM_PIDS={','.join(str(pid) for pid in pids)}")
   
                 # Enabling UBL after the "bring your own license" (BYOL) has run out requires prepending the BYOL configuration to the existing license setup
                 # Remove the sections that do not apply to your pipeline, or you do not want to use UBL after exhausting the BYOL licenses.
                 # The port numbers used may not match what your license server is serving.
   
                 # Arnold
                 os.environ["ADSKFLEX_LICENSE_FILE"] = f"2701@localhost:{os.environ.get('ADSKFLEX_LICENSE_FILE', '')}"
                 print(f"openjd_env: ADSKFLEX_LICENSE_FILE={os.environ['ADSKFLEX_LICENSE_FILE']}")
   
                 # Nuke
                 os.environ["foundry_LICENSE"] = f"6101@localhost:{os.environ.get('foundry_LICENSE', '')}"
                 print(f"openjd_env: foundry_LICENSE={os.environ['foundry_LICENSE']}")
   
                 # SideFX
                 os.environ["SESI_LMHOST"] = f"localhost:1715;{os.environ.get('SESI_LMHOST', '')}"
                 print(f"openjd_env: SESI_LMHOST={os.environ['SESI_LMHOST']}")
   
                 # Redshift and Red Giant
                 os.environ["redshift_LICENSE"] = f"7054@localhost:7055@localhost:{os.environ.get('redshift_LICENSE', '')}"
                 print(f"openjd_env: redshift_LICENSE={os.environ['redshift_LICENSE']}")
   
                 # V-Ray doesn't support multiple license servers in a single environment variable
                 # See https://documentation.chaos.com/space/LIC5/125050770/Sharing+a+License+Configuration+in+a+Network
                 vray_license = os.environ.get('VRAY_AUTH_CLIENT_SETTINGS', '')
                 xml_content = """<VRLClient>
                   <LicServer>
                     <Host>localhost</Host>
                     <Port>30304</Port>"""
   
                 if vray_license and vray_license.startswith('licset://'):
                     server_parts = vray_license.removeprefix('licset://').split(':')
                     if len(server_parts) >= 2:
                         xml_content += f"""
                     <Host1>{server_parts[0]}</Host1>
                     <Port1>{server_parts[1]}</Port1>"""
   
                 xml_content += """
                     <User></User>
                     <Pass></Pass>
                   </LicServer>
                 </VRLClient>"""
   
                 temp_dir = tempfile.gettempdir()
                 xml_path = os.path.join(temp_dir, 'vrlclient.xml')
                 
                 with open(xml_path, 'w') as f:
                     f.write(xml_content)
   
                 os.environ["VRAY_AUTH_CLIENT_FILE_PATH"] = temp_dir
                 print(f"openjd_env: VRAY_AUTH_CLIENT_FILE_PATH={os.environ['VRAY_AUTH_CLIENT_FILE_PATH']}")
   
                 # Clear the existing VRAY_AUTH_CLIENT_SETTINGS so only the vrlclient.xml file is used.
                 os.environ["VRAY_AUTH_CLIENT_SETTINGS"] = ''
                 print(f"openjd_env: VRAY_AUTH_CLIENT_SETTINGS={os.environ['VRAY_AUTH_CLIENT_SETTINGS']}")
   
                 # Print out the created xml file's contents
                 print(f"V-Ray configuration file: {xml_path}")
                 with open(xml_path, 'r') as f:
                     print(f"{f.read()}")
   ```

1. Quando distribuisci il CloudFormation modello, fornisci i seguenti parametri:
   + Aggiorna l'**LicenseInstanceID** con l'ID dell'istanza Amazon EC2 del server di licenza o dell'istanza proxy
   + Aggiorna il file **LicensePorts**con un elenco di porte separate da virgole da inoltrare al server di licenza o all'istanza proxy (ad esempio 2700,2701)
   + Aggiungi le variabili di ambiente di licenza sostituendole nel modello **example\$1LICENSE: 2700@localhost**

1. Implementa il modello per configurare la tua farm con funzionalità Bring Your Own License.