# Automated Agent Installation

To simplify the initial Agent deployment, upload the Agent packages to the Avantra Server as described in Preparing the Avantra Agent Deployment.

| You can also download the agent packages directly from our central download repository. Open https://downloads.avantra.com and proceed to the section in question. Push the Direct Link button and copy the Download URL. You may use this value in the examples below, but keep in mind that the link is only valid for 12 hours.

You can use tools like `curl` or `wget` (or even a browser) to download the agent packages over the very same network connection that will later be used by the Agent itself.

The standard installation as described in Installing the Avantra Agent involves logging into each server remotely and performing the installation. This manual method may not scale very well. There are other options to install Avantra Agent on Linux and on Windows remotely.

| The procedure here describes the initial Agent deployment. For all subsequent updates, Avantra features an automatic Agent update, please see Upgrading Avantra Agents Automatically.

## Deploy Avantra Agents to Linux Remotely

You can deploy the Avantra Agent remotely to Linux servers using SSH, given you can remote access the server, the OS user you use is the same you run the Avantra Agent with, and this user can run passwordless `sudo` commands.

You may use the following small script as a template or check for the latest version in our Bitbucket Repository.

    #!/bin/sh -xe
    # -----------------------------------------------------------
    # Change the following variables according to your needs
    #
    # AVANTRA_HOST  is the Avantra server's dns name or IP address
    # AGENT_VERSION is the version of an Avantra Agent uploaded
    #               to the UI
    # JAVA_INSTALL  is the command to install Java 8. Adapt to
    #               your distro
    # AGENT_USER    is the OS user on the target system that runs
    #               the Avantra agent, is accessible by SSH, and
    #               can run sudo without a password.
    # DISTDIR       is the directory the agent is going to be
    #               installed to
    # SERVICE_NAME  is the name of the service in systemd
    #
    # Run as:
    # ssh <AGENT_USER>@<TARGET> 'sh -s' < deploy-avantra-agent.sh
    # -----------------------------------------------------------
    AVANTRA_HOST=
    AGENT_VERSION=
    JAVA_INSTALL="yum install -y java-1.8.0-openjdk" # Red Hat, CentOS, Fedora
    # JAVA_INSTALL="zypper install -y java-1_8_0-openjdk" # SUSE
    AGENT_USER=
    DISTDIR=/opt/avantra
    SERVICE_NAME=avantra-agent
    ## -- install java
    sudo $JAVA_INSTALL
    ## -- install agent --
    sudo mkdir -p "$DISTDIR" \
        && sudo chown -R $AGENT_USER: "$DISTDIR" \
        && cd "$DISTDIR" \
        && sudo -u $AGENT_USER curl -s http://$AVANTRA_HOST:9050/AgentUpdate/agent-$AGENT_VERSION.bin -o agent-$AGENT_VERSION.bin \
        && sudo -u $AGENT_USER chmod 755 ./agent-$AGENT_VERSION.bin \
        && sudo -u $AGENT_USER ./agent-$AGENT_VERSION.bin -- --silent --start=no
    ## -- create service file for systemd --
    sudo cat <<ENDSVCFILE | sudo tee "/etc/systemd/system/$SERVICE_NAME.service" > /dev/null
    [Unit]
    Description=Avantra Agent $AGENT_VERSION
    After=network.target

    [Service]
    ExecStart=$DISTDIR/agent/rc.agent start
    ExecStop=$DISTDIR/agent/rc.agent stop
    User=$AGENT_USER
    KillMode=process
    Type=forking
    PIDFile=$DISTDIR/agent/log/agent.pid

    [Install]
    WantedBy=multi-user.target
    ENDSVCFILE
    ## -- allow $AGENT_USER to sudo systemctl --
    sudo cat <<ENDSUDOERSFILE | sudo tee "/etc/sudoers.d/$AGENT_USER" > /dev/null
    $AGENT_USER ALL=NOPASSWD: /usr/bin/systemctl start $SERVICE_NAME
    $AGENT_USER ALL=NOPASSWD: /usr/bin/systemctl stop $SERVICE_NAME
    $AGENT_USER ALL=NOPASSWD: /usr/bin/systemctl restart $SERVICE_NAME
    ENDSUDOERSFILE
    sudo visudo -cf "/etc/sudoers.d/$AGENT_USER"
    ## -- enable service --
    sudo systemctl enable "/etc/systemd/system/$SERVICE_NAME.service" \
        && sudo systemctl start $SERVICE_NAME

Adapt the following variables:

`AVANTRA_HOST`

  The DNS name or IP address of the Avantra Server

`AGENT_VERSION`

  The version (e.g. 20.5.1) of the Avantra Agent you have uploaded to the Avantra Server.

`AGENT_USER`

  The OS user to run the Avantra Agent with. `<sid>adm` may be a good choice for servers hosting SAP application servers. Otherwise, choose an existing OS user.

`JAVA_INSTALL`

  The OS command to install the Java Runtime Environment 8 on your Linux host.

Afterwards, use the following command to install the Avantra Agent remotely:

    ssh <AGENT_USER>@<TARGET> 'sh -s' < avantra-agent-deploy.sh

## Deploy Avantra Agents to Windows Remotely

You can deploy the Avantra Agent remotely to Windows servers using Powershell Remoting.

| Powershell Remoting works easiest in an Active Directory environment. If you do not have setup Powershell Remoting already, the setup of Powershell Remoting may require more effort than you can potentially with the Agent deployment. Your mileage may vary.

| You need to set the Execution Policy on the computer you intend to run the script appropriately: Check if your security policies allow such a change. You probably want to consider the value `RemoteSigned`.

You may use the following small script as a template or check for the latest version in our Bitbucket Repository.

    # - Upload the Avantra Agent installer as a package to the Agent Update rpository
    # - Adapt these variable according to your needs
    # - Modify the execution policy to allow running powershell scripts
    [string]$user = '<DOMAIN\user>'          # Access to the remote system
    [string]$target = '<target-host>'        # The remote system
    [string]$avantrahost = '<avantra-server>' # The FQDN of the Avantra Sever
    [string]$agentversion = '23.2.0'         # The agent version (uploaded to the repository)
    [string]$javapath = 'C:\Program Files\Java'
    # Adapt this to the latest version: Make your choice on https://adoptium.net/en-GB/temurin/releases/?version=8, get the full download link
    [uri]$javaurl = 'https://objects.githubusercontent.com/github-production-release-asset-2e65be/.......filename%3DOpenJDK8U-jdk_x64_windows_hotspot_8u372b07.zip&response-content-type=application%2Foctet-stream'

    # There should be no need to change anything below this line

    [uri]$agenturl = 'http://' + $avantrahost + ':9050/AgentUpdate/agent-' + $agentversion + '-setup.exe'

    # Self-elevate the script if required
    if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
        if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
            $CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
            Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
        Exit
        }
    }

    $session = New-PSSession -ComputerName $target -Credential $user

    Invoke-Command -Session $session -ScriptBlock {
        param($javaurl, $agenturl, $javapath)
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        Invoke-WebRequest `
            -Uri $javaurl `
            -OutFile 'C:\Windows\Temp\java-installer.msi'
        Invoke-WebRequest `
            -Uri $agenturl `
            -OutFile 'C:\Windows\Temp\agent-installer.exe'
        msiexec /i C:\Windows\Temp\java-installer.msi /quiet `
            ADDLOCAL="FeatureMain,FeatureEnvironment,FeatureJarFileRunWith,FeatureJavaHome,FeatureOracleJavaSoft" `
            INSTALLDIR=`"$javapath`"
        C:\Windows\Temp\agent-installer.exe /S /JAVA_PATH=`"$javapath`" /START_SERVICE=1 /PORT=9051 /D=C:\Program Files\avantra
    } -ArgumentList $javaurl,$agenturl,$javapath
        Remove-Item -path 'C:\Windows\Temp\java-installer.msi'
        Remove-Item -path 'C:\Windows\Temp\agent-installer.exe'
    Remove-PSSession $session

Adapt the following variables:

`$user`

  Use this (Domain) user to access the remote system

`$target`

  The name of the remote system

`$avantrahost`

  The DNS name or IP address of the Avantra Server

`$agentversion`

  The version (e.g., 24.0.0) of the Avantra Agent you have uploaded to the Avantra Server.

`$javaurl`

  The URL of the `.msi` of the Java 17 Runtime Environment you want to install. Go to AdoptOpenJDK Latest release, choose OpenJDK 8 (LTS) with the Hotpsot JVM. Select Windows for the operating system and x64 for the architecture. Right-click on the .msi button next to JRE in order to retrieve the direct link.

Finally run

    PS> .\deploy-avantra-agent.ps1

in an elevated Powershell.

## Agent Mass Deployments

There is an option to perform large-scale deployments using Ansible. We provide an example playbook for the remote deployment of Avantra Agents to Linux and Windows servers.

| This is an example Ansible playbook demonstrating how to install Java and the Avantra Agent on Linux and Windows. The purpose is to illustrate the tasks all in one file. It is by no means a good way to design an Ansible playbook.

Please adapt at least the variables `master_host` and `agent_version`. You may also check for the latest version in our Bitbucket Repository.

    # NOTE:
    # This is an example ansible playbook demonstrating how to install Java
    # and the Avantra Agent on Linux and Windows. The purpose ist to illustrate
    # the tasks all in one file. It is by no means a good way to design an
    # ansible playbook.
    #
    - name: Install Java 8 JRE and Avantra Agent
      hosts: all
      vars:
        # Adapt this value to your Avantra Server, if you have uploaded the agent
        # packages. Or see the comments below how to use direct download links.
        - avantra_host: your.avantra.server
        # Adapt to the agent version
        - agent_version: 23.2.0
        - agent_dir: /opt/avantra
        - agent_win_dir: ansible_env['ProgramFiles']\avantra
        - agent_user: avantra
        - create_user: true
        - agent_service: avantra-agent

      tasks:
      - name: Install Java 8 on SUSE
        become: true
        package: >
          name=java-1_8_0-openjdk
          state=latest
        when: ansible_os_family == 'SUSE'

      - name: Install Java 8 on RedHat
        become: true
        package: >
          name=java-1.8.0-openjdk
          state=latest
        when: ansible_os_family == 'RedHat'

      - name: Install AdoptOpenJdk Java 8 on Windows
        when: ansible_os_family == 'Windows'
        block:
          - name: Get AdoptOpenJDK release info
            win_uri:
              url: "https://api.adoptopenjdk.net/v2/info/releases/openjdk8\
                ?openjdk_impl=hotspot&os=windows&arch=x64&release=latest\
                &type=jre&heap_size=normal"
              return_content: true
              follow_redirects: all
            register: release_info
          - name: Find installer url
            set_fact:
              release_url: >-
                {{
                  (release_info.content | from_json).binaries | map(attribute='installer_link') | list +
                  (release_info.content | from_json).binaries | map(attribute='installer_name') | list
                }}
          - name: 'Download artifact {{ release_url[1] }}'
            win_get_url:
              url: '{{ release_url[0] }}'
              dest: '%TEMP%'
              force: true
            register: file_downloaded
            retries: 20
            delay: 5
            until: file_downloaded is succeeded
          - name: Install from remote
            win_package:
              path: '{{ file_downloaded.dest }}'
              state: present

      - name: Create user and directory on Linux
        when: ansible_system == 'Linux'
        block:
        - name: Create User
          become: true
          when: create_user
          user:
            name: "{{ agent_user }}"
            state: present
        - name: Create directory
          become: true
          file:
            path: "{{ agent_dir }}"
            state: directory
            owner: "{{ agent_user }}"
            group: "{{ agent_user }}"
            mode: 0755

      - name: Download and Install Avantra Agent on Linux
        when: ansible_system == 'Linux'
        block:
        - name: Download Agent
          get_url:
            # NOTE: You can also head to downloads.avantra.com, generate a direct
            # download link, and use it here. Keep in mind that these generated
            # links expire after 12 hours.
            url: http://{{ avantra_host }}:9050/AgentUpdate/agent-{{ agent_version }}.bin
            dest: /tmp
            mode: '0755'
        - name: Install Agent
          command: /tmp/agent-{{ agent_version }}.bin -- --silent --start=no
          become: true
          become_user: "{{ agent_user }}"
          args:
            chdir: "{{ agent_dir }}"
        - name: Create Systemd Service file
          become: true
          copy:
            dest: /etc/systemd/system/{{ agent_service }}.service
            content: |
              [Unit]
              Description=Avantra Agent
              After=network.target

              [Service]
              ExecStart={{ agent_dir }}/agent/rc.agent start
              ExecStop={{ agent_dir }}/agent/rc.agent stop
              User={{ agent_user }}
              Type=forking
              KillMode=process
              PIDFile={{ agent_dir }}/agent/log/agent.pid

              [Install]
              WantedBy=multi-user.target
        - name: Enable Agent service
          become: true
          service:
            daemon_reload: yes
            name: "{{ agent_service }}"
            enabled: yes
            state: started
        - name: Enable agent_user to run systemctl
          become: true
          copy:
            dest: /etc/sudoers.d/{{ agent_user }}
            content: |
              {{ agent_user }} ALL=NOPASSWD: /usr/bin/systemctl start {{ agent_service }}
              {{ agent_user }} ALL=NOPASSWD: /usr/bin/systemctl stop {{ agent_service }}
              {{ agent_user }} ALL=NOPASSWD: /usr/bin/systemctl restart {{ agent_service }}
            validate: 'visudo -cf %s'

      - name: Install Avantra Agent on Windows
        win_package:
          # NOTE: You can also head to downloads.avantra.com, generate a direct
          # download link, and use it here. Keep in mind that these generated
          # links expire after 12 hours.
          path: http://{{ avantra_host }}:9050/AgentUpdate/agent-{{ agent_version }}-setup.exe
          creates_path: '{{ agent_win_dir }}'
          arguments:
            - /S
            - /START_SERVICE=1
            - /PORT=9051
            - /D={{ agent_win_dir }}
          state: present
        when: ansible_os_family == 'Windows'

## Post-installation Setup

After you have deployed the Avantra Agents, please follow the steps described in section Preparing the Installation of the Product Guide.

| There is nothing wrong if you do this after the agent deployment although the Product Guide says Preparing.

The transport request mentioned there is already available at `/opt/avantra/AgentUpdate` on the Avantra Server. It can be accessed in the same way (via http) as described in the Product Guide (and as described in the deployment steps above).

| Please also consider steps 3 to 6 of Installing the Agent on Unix. Replace the OS user `xandria` referenced there with whatever you have chosen for `AGENT_USER` above.