Clone an Environment Using the Latest Environment Backup

Use these scripts to keep the Oracle Fusion Cloud Enterprise Performance Management standby environment up to date by cloning the primary environment to it from the primary environment’s latest environment backup.

This script clones the latest environment backup from one Cloud EPM environement to another. If you want the cloning to occur every day, you can schedule this script to run on a daily basis using Windows scheduler or Linux crontab.

Windows Script

Create Clone-LatestEnvironmentBackup.ps1 by copying the following PowerShell script.
#requires -Version 5.1
<#
Logs into SourceUrl, selects the latest archived Environment_Backup, and
clones it to TargetUrl. Edit the settings below, then run without arguments.
Credential files must be created with EPM Automate encrypt.
#>
# BEGIN SETTINGS - replace these example values before running.
# Every successful run clones to the target, replacing its application content.
$SourceUrl = 'SOURCE_URL'
$SourceUser = 'SOURCE_SERVICE_ADMIN'
$SourcePasswordFile = 'SOURCE_ENCRYPTED_PWD_FILE'
$TargetUrl = 'TARGET_URL'
$TargetUser = 'TARGET_SERVICE_ADMIN'
$TargetPasswordFile = 'TARGET_ENCRYPTED_PWD_FILE'
$EpmAutomate = 'PATH_EPM_AUTOMATE_EXECUTABLE'
# Optional source override: leave BOTH blank to select the latest Environment_Backup.
# Set only one. SnapshotName must already exist in the source environment.
$SnapshotName = ''
$EnvironmentBackup = ''
# Use 'true', 'false', or '' to omit the option and use Oracle's default.
$UsersAndApplicationRoles = ''  # Default false; true requires target Identity Domain Administrator.
$DataManagement = ''           # Default true.
$AppAudit = ''                 # Default true.
$JobConsole = ''               # Default true.
$StoredSnapshotsAndFiles = ''  # Default false.
$DailyMaintenanceStartTime = '' # Default true.
$ApplicationProperties = ''    # Default true; Account Reconciliation only.
# Each run creates a unique directory here with run.log and output.log.
# Relative paths are resolved against this script's directory. Restrict log access.
$LogDirectory = 'logs'
# END SETTINGS
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
# Native exit codes are checked explicitly, including in PowerShell 7.
$PSNativeCommandUseErrorActionPreference = $false
$loggedIn = $false
$pushed = $false
$status = 1
$runLog = $null

function Write-RunLog([string]$Message) {
    $line = '[{0}] {1}' -f [datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ'), $Message
    Write-Host $line
    if ($script:runLog) { Add-Content -LiteralPath $script:runLog -Value $line -Encoding UTF8 }
}

function Invoke-Epm([string[]]$Arguments) {
    $command = $Arguments[0]
    Write-RunLog "Starting $command"
    Add-Content -LiteralPath $script:outputLog -Value ("`n[{0}] BEGIN {1}" -f [datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ'), $command) -Encoding UTF8
    # Windows PowerShell wraps native stderr as ErrorRecords. A warning on
    # stderr must not bypass the native exit-code check.
    $savedPreference = $ErrorActionPreference
    try {
        $ErrorActionPreference = 'Continue'
        $output = @(& $script:launcher @Arguments 2>&1)
        $code = $LASTEXITCODE
    } finally { $ErrorActionPreference = $savedPreference }
    ($output -join "`n") | Add-Content -LiteralPath $script:outputLog -Encoding UTF8
    Add-Content -LiteralPath $script:outputLog -Value ("[{0}] END {1}; exit code: {2}" -f [datetime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ'), $command, $code) -Encoding UTF8
    Write-RunLog "$command exit code: $code; output: $script:outputLog"
    if ($code -ne 0) {
        # Do not echo arbitrary CLI output: it may contain account details.
        throw "EPM Automate $($Arguments[0]) failed (exit $code). Check the EPM logs in $script:runDirectory."
    }
    return ($output -join "`n")
}
function Normalize-Url([string]$Value) {
    $uri = $null
    if (-not [Uri]::TryCreate($Value, [UriKind]::Absolute, [ref]$uri) -or
        $uri.Scheme -ne 'https' -or $uri.UserInfo -or $uri.Query -or $uri.Fragment) {
        throw 'Use an HTTPS environment base URL without credentials, query, or fragment.'
    }
    return $uri.AbsoluteUri.TrimEnd('/')
}

try {
    if ([string]::IsNullOrWhiteSpace($LogDirectory)) { throw 'LogDirectory must not be empty.' }
    if (-not [IO.Path]::IsPathRooted($LogDirectory)) { $LogDirectory = Join-Path $PSScriptRoot $LogDirectory }
    $runDirectory = Join-Path $LogDirectory ('epm-clone-' + [datetime]::UtcNow.ToString('yyyyMMddTHHmmssZ') + '-' + [guid]::NewGuid().ToString('N'))
    $null = New-Item -ItemType Directory -Path $runDirectory -Force
    $runDirectory = (Resolve-Path -LiteralPath $runDirectory).ProviderPath
    $runLog = Join-Path $runDirectory 'run.log'
    $outputLog = Join-Path $runDirectory 'output.log'
    $null = New-Item -ItemType File -Path $outputLog
    Write-RunLog "Run started; logs: $runDirectory"
    if ($args.Count -ne 0) { throw 'This script takes no arguments. Edit the SETTINGS block in the script.' }
    $SnapshotName = $SnapshotName.Trim()
    $EnvironmentBackup = $EnvironmentBackup.Trim()
    if ($SnapshotName -and $EnvironmentBackup) { throw 'Set only one of SnapshotName and EnvironmentBackup.' }
    $options = [ordered]@{
        UsersAndApplicationRoles = $UsersAndApplicationRoles
        DataManagement = $DataManagement
        appAudit = $AppAudit
        jobConsole = $JobConsole
        storedSnapshotsAndFiles = $StoredSnapshotsAndFiles
        DailyMaintenanceStartTime = $DailyMaintenanceStartTime
        ApplicationProperties = $ApplicationProperties
    }
    $cloneOptions = @()
    foreach ($entry in $options.GetEnumerator()) {
        $value = ([string]$entry.Value).Trim().ToLowerInvariant()
        if ($value) {
            if ($value -notin @('true', 'false')) { throw "$($entry.Key) must be 'true', 'false', or empty." }
            $cloneOptions += "$($entry.Key)=$value"
        }
    }
    $SourceUrl = Normalize-Url $SourceUrl
    $TargetUrl = Normalize-Url $TargetUrl
    if ($SourceUrl -ieq $TargetUrl) { throw 'Source and target must be different environments.' }
    if ([string]::IsNullOrWhiteSpace($SourceUser) -or [string]::IsNullOrWhiteSpace($TargetUser)) {
        throw 'Both user names are required.'
    }
    foreach ($path in @($SourcePasswordFile, $TargetPasswordFile)) {
        if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "Credential file not found: $path" }
    }
    $SourcePasswordFile = (Resolve-Path -LiteralPath $SourcePasswordFile).ProviderPath
    $TargetPasswordFile = (Resolve-Path -LiteralPath $TargetPasswordFile).ProviderPath
    $launcher = (Get-Command $EpmAutomate -CommandType Application,ExternalScript -ErrorAction Stop).Source
    # Isolate EPM session files in this run's log directory.
    Push-Location -LiteralPath $runDirectory
    $pushed = $true
    Write-RunLog "Source: $SourceUrl; target: $TargetUrl"
    $null = Invoke-Epm @('login', $SourceUser, $SourcePasswordFile, $SourceUrl)
    $loggedIn = $true
    if ($SnapshotName) {
        $backupOption = "SnapshotName=$SnapshotName"
    } elseif ($EnvironmentBackup) {
        $backupOption = "environmentBackup=$EnvironmentBackup"
    } else {
        $listing = Invoke-Epm @('listBackups')
        # Delimiters prevent matching prefixed paths or Environment_Backup.zip.
        $pattern = '(?<![^\s"''|,])(?<backup>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/Environment_Backup)(?=$|[\s"''|,])'
        $latest = $null
        foreach ($match in [regex]::Matches($listing, $pattern)) {
            $candidate = $match.Groups['backup'].Value
            $parsed = [datetime]::MinValue
            if (-not [datetime]::TryParseExact($candidate.Substring(0,19), 'yyyy-MM-ddTHH:mm:ss',
                [Globalization.CultureInfo]::InvariantCulture, [Globalization.DateTimeStyles]::None, [ref]$parsed)) {
                throw 'Invalid Environment_Backup timestamp in listBackups output; refusing to select a backup.'
            }
            if ($null -eq $latest -or [string]::CompareOrdinal($candidate, $latest) -gt 0) { $latest = $candidate }
        }
        if ($null -eq $latest) { throw 'No supported Environment_Backup entry found; clone was not started.' }
        $backupOption = "environmentBackup=$latest"
    }
    Write-RunLog "Selected source: $backupOption"
    Write-RunLog "Clone options: $($cloneOptions -join ' ')"
    $null = Invoke-Epm (@('cloneEnvironment', $TargetUser, $TargetPasswordFile, $TargetUrl, $backupOption) + $cloneOptions)
    Write-RunLog 'cloneEnvironment completed successfully. Verify the target application and migration status.'
    $status = 0
} catch {
    [Console]::Error.WriteLine($_.Exception.Message)
    try { Write-RunLog "ERROR: $($_.Exception.Message)" } catch { [Console]::Error.WriteLine('Unable to write error to run log.') }
} finally {
    if ($loggedIn) {
        try { $null = Invoke-Epm @('logout') }
        catch {
            [Console]::Error.WriteLine($_.Exception.Message)
            if ($status -eq 0) { $status = 2 }
            try { Write-RunLog "ERROR during logout: $($_.Exception.Message)" } catch { [Console]::Error.WriteLine('Unable to log logout failure.') }
        }
    }
    if ($pushed) { Pop-Location }
    try { Write-RunLog "Run finished; exit code: $status" }
    catch { [Console]::Error.WriteLine('Unable to write final run log.'); if ($status -eq 0) { $status = 1 } }
}
exit $status

Linux (Bash) Script

Create clone-latest-environment-backup.sh by copying the following script.

#!/usr/bin/env bash
# Bash 4+ and GNU coreutils. Edit the settings, then run without arguments.
# BEGIN SETTINGS - replace these example values before running.
# Every successful run clones to the target, replacing its application content.
source_url='SOURCE_URL'
source_user='SOURCE_SERVICE_ADMIN'
source_epw='SOURCE_ENCRYPTED_PWD_FILE'
target_url='TARGET_URL'
target_user='TARGET_SERVICE_ADMIN'
target_epw='TARGET_ENCRYPTED_PWD_FILE'
EPM_AUTOMATE='PATH_EPM_AUTOMATE_EXECUTABLE'
# Optional source override: leave BOTH blank to select the latest Environment_Backup.
# Set only one. SnapshotName must already exist in the source environment.
SnapshotName=''
EnvironmentBackup=''
# Use 'true', 'false', or '' to omit the option and use Oracle's default.
UsersAndApplicationRoles=''   # Default false; true requires target Identity Domain Administrator.
DataManagement=''            # Default true.
AppAudit=''                  # Default true.
JobConsole=''                # Default true.
StoredSnapshotsAndFiles=''   # Default false.
DailyMaintenanceStartTime='' # Default true.
ApplicationProperties=''    # Default true; Account Reconciliation only.
# Each run creates a unique directory here with run.log and output.log.
# Relative paths are resolved against this script's directory. Restrict log access.
LogDirectory='logs'
# END SETTINGS
set -euo pipefail
export LC_ALL=C
umask 077

script_directory=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
[[ -n $LogDirectory ]] || { echo 'LogDirectory must not be empty.' >&2; exit 1; }
if [[ $LogDirectory != /* ]]; then LogDirectory="$script_directory/$LogDirectory"; fi
mkdir -p -- "$LogDirectory"
run_directory=$(mktemp -d "$LogDirectory/epm-clone.$(date -u +%Y%m%dT%H%M%SZ).XXXXXXXX")
run_log="$run_directory/run.log"
output_log="$run_directory/output.log"
: >"$output_log"
logged_in=false
log() { printf '[%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" | tee -a "$run_log"; }
fail() { log "ERROR: $*" >&2; exit 1; }
cleanup() {
    local status=$? logout_status
    trap - EXIT
    if $logged_in; then
        log 'Starting logout' || true
        printf '\n[%s] BEGIN logout\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >>"$output_log" || true
        logout_status=0
        "$launcher" logout >>"$output_log" 2>&1 || logout_status=$?
        printf '\n[%s] END logout; exit code: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$logout_status" >>"$output_log" || true
        log "logout exit code: $logout_status; output: $output_log" || true
        if (( logout_status != 0 && status == 0 )); then status=2; fi
    fi
    if ! log "Run finished; exit code: $status"; then
        if (( status == 0 )); then status=1; fi
    fi
    exit "$status"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
log "Run started; logs: $run_directory"
(( $# == 0 )) || fail 'This script takes no arguments. Edit the SETTINGS block in the script.'
[[ -z $SnapshotName || -z $EnvironmentBackup ]] || fail 'Set only one of SnapshotName and EnvironmentBackup.'
clone_options=()
option_names=(UsersAndApplicationRoles DataManagement appAudit jobConsole storedSnapshotsAndFiles DailyMaintenanceStartTime ApplicationProperties)
option_values=("$UsersAndApplicationRoles" "$DataManagement" "$AppAudit" "$JobConsole" "$StoredSnapshotsAndFiles" "$DailyMaintenanceStartTime" "$ApplicationProperties")
for i in "${!option_names[@]}"; do
    value=${option_values[$i],,}
    if [[ -n $value ]]; then
        [[ $value == true || $value == false ]] || fail "${option_names[$i]} must be 'true', 'false', or empty."
        clone_options+=("${option_names[$i]}=$value")
    fi
done
source_url=${source_url%/}
target_url=${target_url%/}
for url in "$source_url" "$target_url"; do
    [[ $url =~ ^https://[a-zA-Z0-9.-]+(:[0-9]+)?(/[^[:space:]\?\#]*)?$ ]] || fail 'Use an HTTPS environment base URL without credentials, query, or fragment.'
done
[[ ${source_url,,} != "${target_url,,}" ]] || fail 'Source and target must be different environments.'
[[ -n $source_user && -n $target_user ]] || fail 'Both user names are required.'
[[ -f $source_epw && -r $source_epw && -f $target_epw && -r $target_epw ]] || fail 'Both encrypted credential files must exist and be readable.'
source_epw=$(realpath -- "$source_epw")
target_epw=$(realpath -- "$target_epw")
launcher=$(command -v -- "$EPM_AUTOMATE") || fail 'EPM Automate launcher not found. Set EPM_AUTOMATE in the script.'
launcher=$(realpath -- "$launcher")
[[ -x $launcher ]] || fail 'EPM Automate launcher is not executable.'
cd -- "$run_directory"
log "Source: $source_url; target: $target_url"
run_epm() {
    local command=$1 code
    log "Starting $command"
    printf '\n[%s] BEGIN %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$command" >>"$output_log"
    code=0
    if [[ $command == listBackups ]]; then
        # Keep only this command's output in memory for selection, with no extra log file.
        listing=$("$launcher" "$@" 2>&1) || code=$?
        printf '%s\n' "$listing" >>"$output_log"
    else
        "$launcher" "$@" >>"$output_log" 2>&1 || code=$?
    fi
    printf '\n[%s] END %s; exit code: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$command" "$code" >>"$output_log"
    log "$command exit code: $code; output: $output_log"
    (( code == 0 )) || fail "EPM Automate $command failed (exit $code). Check $output_log"
}
run_epm login "$source_user" "$source_epw" "$source_url"
logged_in=true
if [[ -n $SnapshotName ]]; then
    backup_option="SnapshotName=$SnapshotName"
elif [[ -n $EnvironmentBackup ]]; then
    backup_option="environmentBackup=$EnvironmentBackup"
else
    run_epm listBackups
    
    # Scan every entry, regardless of order. Fixed-width UTC timestamps sort chronologically.
    pattern="(^|[[:space:]\"'|,])([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}/Environment_Backup)($|[[:space:]\"'|,])"
    latest=''
    while IFS= read -r line || [[ -n $line ]]; do
        while [[ $line =~ $pattern ]]; do
            whole=${BASH_REMATCH[0]}
            candidate=${BASH_REMATCH[2]}
            timestamp=${candidate:0:19}
            normalized=$(date -u -d "$timestamp UTC" '+%Y-%m-%dT%H:%M:%S' 2>/dev/null) || fail 'Invalid Environment_Backup timestamp; refusing to select a backup.'
            [[ $timestamp == "$normalized" ]] || fail 'Invalid Environment_Backup timestamp; refusing to select a backup.'
            if [[ -z $latest || $candidate > $latest ]]; then latest=$candidate; fi
            # Keep the closing delimiter so adjacent entries remain recognizable.
            suffix=${BASH_REMATCH[3]}
            line="$suffix${line#*"$whole"}"
        done
    done <<< "$listing"
    [[ -n $latest ]] || fail 'No supported Environment_Backup entry found; clone was not started.'
    backup_option="environmentBackup=$latest"
fi
log "Selected source: $backup_option"
log "Clone options: ${clone_options[*]}"
run_epm cloneEnvironment "$target_user" "$target_epw" "$target_url" "$backup_option" "${clone_options[@]}"
log 'cloneEnvironment completed successfully. Verify the target application and migration status.'

Running the Script

  1. Create Clone-LatestEnvironmentBackup.ps1 or clone-latest-environment-backup.sh script by copying a script from one of the preceding sections and save it to a directory where you have read and write access.
  2. Edit Clone-LatestEnvironmentBackup.ps1 or clone-latest-environment-backup.sh script to specify runtime parameters. See Table 3-7 for explanation of the parameters.
  3. Run Clone-LatestEnvironmentBackup.ps1 or clone-latest-environment-backup.sh:

    Windows

    1. In a Power Shell Console, navigate to the folder where Clone-LatestEnvironmentBackup.ps1 is stored.
    2. Execute a command such as the following:
       .\Clone-LatestEnvironmentBackup.ps1
    Linux/UNIX
    1. In a UNIX or Linux shell, navigate to the directory where clone-latest-environment-backup.sh is stored.
    2. Execute the command: ./clone-latest-environment-backup.sh.

Update these example values used in the sample scripts. Note that the parameter names in the Windows script differ from those in the Linux script.

Table 3-7 Description of Parameters

Parameter Description
SOURCE_URL The URL of the primary environment that you want to clone.

Examples:

Windows: $SourceUrl = 'https://example.oraclecloud.com'

Linux/UNIX: source_url='https://example.oraclecloud.com'

SOURCE_SERVICE_ADMIN User name of a Service Administrator in the source environment. This user must have the Identity Domain Administrator role to clone users and application roles.

Examples:

Windows: $SourceUser = 'john.doe@example.com'

Linux/UNIX: source_user='john.doe@example.com'

SOURCE_ENCRYPTED_PWD_FILE The absolute path, including the file name, to the encrypted password file (.epw) of the Service Administrator specified as the SOURCE_SERVICE_ADMIN.

Examples:

Windows: $SourcePasswordFile = 'C:\secureDir\jdoepwd.epw'

Linux/UNIX: source_epw='/secure/source.epw'

.
TARGET_URL The URL of the target environment.

Examples:

Windows: $TargetUrl = 'https:///example1.oraclecloud.com'

Linux/UNIX: target_url='https:///example1.oraclecloud.com'

TARGET_SERVICE_ADMIN The user name of a Service Administrator in the target environment. This user must have the Identity Domain Administrator role to clone users and application roles.

Examples:

Windows: $TargetUser = 'john.doe@example.com'

Linux/UNIX: target_user='john.doe@example.com'

TARGET_ENCRYPTED_PWD_FILE The absolute path, including the file name, to the encrypted password file (.epw) of the Service Administrator specified as the TARGET_SERVICE_ADMIN.

Examples:

Windows: $TargetPasswordFile = 'C:\secureDir\jdoepwd.epw'

Linux/UNIX: target_epw='/secure/source.epw'

PATH_EPM_AUTOMATE_EXECUTABLE The path to the location where EPM Automate is installed.

Examples:

Windows: $EpmAutomate='C:\Program Files\Oracle\EPM Automate\bin\epmautomate.bat'

Linux/UNIX: EPM_AUTOMATE='/opt/epmautomate/bin/epmautomate.sh'

SNAPSHOT_NAME Optionally, the name of the snapshot to use for cloning. Do not specify this value if you are cloning using environment backup.

Examples:

Windows: $SnapshotName='2026-11-02T12:04:16/Artifact_Snapshot.zip'

Linux/UNIX: SnapshotName='2026-11-02T12:04:16/Artifact_Snapshot.zip'

ENVIRONMENT_BACKUP Name of the specific environment backup to use for cloning. Do not specify this value if you are cloning using environment backup.

Examples:

Windows: $EnvironmentBackup='2026-11-02T12:00:29/Environment_Backup'

Linux/UNIX: EnvironmentBackup='2026-11-02T12:00:29/Environment_Backup'

Reset the value of the following parameters if you do not want to use the default values.
UsersAndApplicationRoles Set to true to clone users and their roles. You must be an Identity Domain Administrator role in both the source and target environments to clone application role assignments. Default is false

Examples:

Windows: $UsersAndApplicationRoles = 'true'

Linux/UNIX: UsersAndApplicationRoles = 'true'

DataManagement For environments other than Oracle Fusion Cloud Enterprise Data Management and Narrative Reporting only: Whether to clone Data Management artifacts. Default is true.

Examples:

Windows: $DataManagement = 'false'

Linux/UNIX: DataManagement = 'false'

AppAudit For Planning, Planning Modules, FreeForm, and Enterprise Profitability and Cost Management only: Whether to clone audit records. Default is true.

Examples:

Windows: $AppAudit = 'false'

Linux/UNIX: AppAudit = 'false'

JobConsole For Planning, Planning Modules, FreeForm, Financial Consolidation and Close, Tax Reporting, and Enterprise Profitability and Cost Management only:: Whether to clone job console records. Default is true.

Examples:

Windows: $JobConsole = 'false'

Linux/UNIX: JobConsole = 'false'

StoredSnapshotsAndFiles Whether to clone the contents of inbox and outbox, and stored snapshots. This process may take a long time depending on the number and size of stored snapshots and files in inbox and outbox. Default is false.

Examples:

Windows: $StoredSnapshotsAndFiles = 'true'

Linux/UNIX: StoredSnapshotsAndFiles = 'true'

DailyMaintenanceStartTime Whether to keep the maintenance start time of the target environment. Default is true.

Examples:

Windows: $DailyMaintenanceStartTime = 'false'

Linux/UNIX: DailyMaintenanceStartTime = 'false'

ApplicationProperties For Account Reconciliation only: whether to clone the application settings (Email notification on/off setting, Redwood Experience theme, business process name, logo image, and background image). Default is true.

Examples:

Windows: $ApplicationProperties = 'false'

Linux/UNIX: ApplicationProperties = 'false'

LogDirectory

Location of a directory where run.log and output.log are to be stored. Relative path, if any, is resolved against the directory where the script is located.

Examples:

Windows: $LogDirectory = 'C:\epm_log_files'

Linux/UNIX: LogDirectory = '/opt/epm_log_files'