Overview

This is the second blog in the series on running Oracle Dynamic Scaling utility (ODyS) with OCI Workload Identity Federation. The first blog introduces the use case and multicloud architecture. Refer to it for that background before proceeding with this implementation.

This blog focuses on Oracle Database@AWS and walks through running ODyS on an Amazon EC2 instance using an IAM role delivered through an instance profile. The workload obtains an AWS-signed JWT from AWS Security Token Service (STS), exchanges it for an OCI Resource Principal Session Token (RPST), and uses OCI CLI resource principal authentication to perform database scaling operations.

The walkthrough covers AWS outbound identity federation, the EC2 role and instance profile, OCI identity domain trust and IAM permissions, and ODyS configuration. It also includes token renewal and database workload telemetry so the utility can operate unattended without storing a long-lived OCI user API signing key on the EC2 host.

Federation across the clouds

The architectural pattern is the same across application clouds: start with the workload’s native identity, obtain a signed identity token from its issuer, and configure OCI to trust only the intended workload. Azure managed identity and Google Cloud workload or service account identity require their own token acquisition and claim validation steps. The AWS STS commands below apply specifically to AWS.

For this blog, we will implement the setup and architecture for DB@AWS. EC2 uses instance-profile credentials to sign a request to regional AWS STS. STS issues a JWT. OCI validates the JWT against the account-specific AWS issuer and public signing keys, checks the allowed audience and role, and issues an RPST bound to a public key supplied by the EC2 workload. OCI API requests then use that RPST and signatures made with the corresponding private key.


The request flow diagram for end to end access is as below.

The federation path uses HTTPS to AWS STS, AWS Secrets Manager, the OCI identity domain, and the OCI Database API. OCI must be able to retrieve the public AWS JWKS. An STS interface endpoint can keep token acquisition private within AWS; it does not supply connectivity to the OCI endpoints. Configure DNS, outbound TCP 443, proxy settings where required, and working certificate trust. AWS distinguishes the STS API endpoint from its OIDC discovery endpoints in its networking documentation.

The private path from EC2 to the DB@AWS guest VMs carries telemetry in this example. Configure the ODB network connection or peering, routes, DNS, and security rules for the chosen EC2 VPC. This walkthrough uses SSH on TCP 22 with a restricted telemetry account. The customer’s broader application SQL/TCPS connectivity is separate from ODyS authentication. An RPST used for scaling is not a database login token.

Workload Identity Federation

I have talked about Workload Identity Federation before so I will not repeat myself. However, refer to some of those blogs before reading next section to better understand the concept and implementation.

  1. Learn about Workload Identity Federation (WIF).
  2. I talk about Identity Propagation Trust configuration in the blog along with OAuth clients creation in Identity Domain. Those steps are relevant for AWS→OCI Workload Identity Federation setup as well.
  3. I followed up on WIF blog with WIF using RPST (Resource Principal Session Token). We will leverage that instead of using UPST for the setup.
  4. One of my colleagues wrote about Github Actions and OCI using WIF. That is also useful pre-read. In this case EC2 requests its JWT from AWS STS instead of Github Actions.

The selected runtime authentication method still uses an OCI OAuth client secret to authenticate the exchange request. Store it in AWS Secrets Manager and retrieve it using the EC2 role.

Implementation

Prepare the environment and values

Use an AWS administrator for account enablement, IAM role/profile creation, secret creation, and EC2 configuration. The administrator needs permission to pass the selected role to EC2. Use an OCI identity domain administrator for application and trust creation, and an OCI tenancy or compartment administrator for the database policies. Those administration permissions are not assigned to the runtime workload.

Record the following values before starting. Replace every example value consistently.

ValueMeaning
AWS_REGIONAWS region of EC2, STS, and the Secrets Manager secret, for example us-east-1.
AWS_ACCOUNT_IDAWS account containing the role.
EC2_IDEC2 instance that will run ODyS.
AWS_ROLE_ARNIAM role ARN, for example arn:aws:iam::123456789012:role/OdysOciScaler.
AWS_ISSUERExact IssuerIdentifier returned by AWS account enablement.
DOMAIN_URLOCI identity domain HTTPS URL, without a trailing slash.
AUDIENCEA dedicated logical audience, here https://odys.example.com/oci/prod. It need not host a website.
OCI_REGIONRegion of the OCI Database API managing the DB@AWS cluster; confirm it from that resource rather than deriving it from the AWS region name.
CLUSTER_OCIDOCI Cloud VM Cluster OCID, not an AWS resource identifier.
INFRA_COMPARTMENT and DB_COMPARTMENTOCI compartments holding the Exadata infrastructure and Cloud VM Cluster. They can be the same.
SECRET_ARNARN of the Secrets Manager secret created below.
DB node addressesEvery guest VM in the target cluster, reachable privately from EC2.

Keep host clocks synchronized. Use a current AWS CLI v2 and Boto3 release that expose GetWebIdentityToken. Check aws sts get-web-identity-token help; upgrade the CLI if the command is missing. Installation commands below use Python 3.11 and a virtual environment for OCI CLI and the helper programs.

Step 1 Enable AWS outbound identity federation

On the AWS administration workstation, enable the account capability once:

aws iam enable-outbound-web-identity-federation
aws iam get-outbound-web-identity-federation-info

If the first call reports that the feature is already enabled, retrieve the configuration with the second call. Confirm JwtVendingEnabled is true and save IssuerIdentifier exactly as returned. The issuer is account-specific; it is not the regional STS API URL. See AWS account enablement and the configuration response.

export AWS_REGION='us-east-1'
export AWS_ACCOUNT_ID='123456789012'
export EC2_ID='i-REPLACE_ME'
export AUDIENCE='https://odys.example.com/oci/prod'
export AWS_ROLE_ARN="arn:aws:iam::${AWS_ACCOUNT_ID}:role/OdysOciScaler"
export AWS_ISSUER="$(aws iam get-outbound-web-identity-federation-info \
  --query IssuerIdentifier --output text)"

curl --fail --silent --show-error \
  "$AWS_ISSUER/.well-known/openid-configuration" | jq .
curl --fail --silent --show-error \
  "$AWS_ISSUER/.well-known/jwks.json" | jq .

These are public verification keys, not private credentials. OCI will use the JWKS URL in its trust configuration.

Step 2 Create the EC2 role and instance profile

For a new dedicated scaler role, save the following as ec2-trust.json:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Service": "ec2.amazonaws.com"},
    "Action": "sts:AssumeRole"
  }]
}

Save the JWT permission as mint-jwt.json. This example permits a single audience, RS256 signing, and at most a five-minute AWS JWT:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "sts:GetWebIdentityToken",
    "Resource": "*",
    "Condition": {
      "ForAllValues:StringEquals": {
        "sts:IdentityTokenAudience": ["https://odys.example.com/oci/prod"]
      },
      "StringEquals": {"sts:SigningAlgorithm": "RS256"},
      "NumericLessThanEquals": {"sts:DurationSeconds": 300}
    }
  }]
}

The Resource wildcard applies to this STS token issuance operation. Audience, lifetime, algorithm, and attachment to the dedicated role constrain its use. AWS documents these controls in outbound federation IAM policies.

aws iam create-role --role-name OdysOciScaler \
  --assume-role-policy-document file://ec2-trust.json
aws iam put-role-policy --role-name OdysOciScaler \
  --policy-name MintOciAudienceJwt --policy-document file://mint-jwt.json
aws iam create-instance-profile --instance-profile-name OdysOciScaler
aws iam add-role-to-instance-profile --instance-profile-name OdysOciScaler \
  --role-name OdysOciScaler
aws ec2 associate-iam-instance-profile --region "$AWS_REGION" \
  --instance-id "$EC2_ID" --iam-instance-profile Name=OdysOciScaler
aws ec2 modify-instance-metadata-options --region "$AWS_REGION" \
  --instance-id "$EC2_ID" --http-endpoint enabled --http-tokens required

Allow IAM changes to propagate. If EC2 already has a profile, use the documented replacement procedure instead of trying to associate a second profile. AWS permits one attached role per instance; preserve any required existing permissions when designing that role. See attaching and replacing an EC2 IAM role.

On EC2, run as the operating-system account that will run ODyS, with no static AWS credentials or selected developer profile:

aws sts get-caller-identity --region us-east-1

The returned ARN should identify an assumed session of OdysOciScaler. The JWT subject is the IAM role ARN, which differs from this STS assumed-role session ARN. AWS documents that distinction in token claims.

Step 3 Create the OCI OAuth applications

In the OCI Console, select Identity & Security → Domains → your domain → Integrated applications → Add application → Confidential Application → Launch workflow. Create these two applications:

  1. OdysTrustAdmin: configure it as an OAuth client, allow Client credentials, and add the Identity Domain Administrator application role. This application is used only for setup.
  2. OdysTokenExchange: configure it as an OAuth client and allow Client credentials. Assign no administrator application role. This is the runtime exchange caller.

For each application, finish the workflow, record its Client ID and Client secret, and Activate it. No interactive redirect-based login is needed for this flow. These steps correspond to Create OAuth Client in my original WIF article; Oracle’s confidential application instructions describe the console fields.

On the secure OCI administration workstation, obtain the administrator access token. The following commands use Bash; enter secrets interactively rather than saving them in shell history:

export DOMAIN_URL='https://idcs-REPLACE_ME.identity.oraclecloud.com'
read -r -p 'Admin OAuth client ID: ' ADMIN_CLIENT_ID
read -r -s -p 'Admin OAuth client secret: ' ADMIN_CLIENT_SECRET; echo
export ADMIN_OAUTH_TOKEN="$(curl --fail --silent --show-error \
  --user "$ADMIN_CLIENT_ID:$ADMIN_CLIENT_SECRET" \
  --data-urlencode 'grant_type=client_credentials' \
  --data-urlencode 'scope=urn:opc:idm:__myscopes__' \
  "$DOMAIN_URL/oauth2/v1/token" | jq -er '.access_token')"
unset ADMIN_CLIENT_SECRET
read -r -p 'Runtime OAuth client ID: ' EXCHANGE_CLIENT_ID

Use the scope granted to the administrator application; urn:opc:idm:__myscopes__ requests its assigned grants. See OAuth access to identity domain APIs.

Step 4 Configure the AWS to OCI resource trust

On the same administration workstation, set AWS_ISSUER, AWS_ROLE_ARN, and AUDIENCE to the values from Steps 1–2. Create the trust payload:

jq -n \
  --arg issuer "$AWS_ISSUER" \
  --arg role "$AWS_ROLE_ARN" \
  --arg audience "$AUDIENCE" \
  --arg client "$EXCHANGE_CLIENT_ID" \
  '{
    schemas: ["urn:ietf:params:scim:schemas:oracle:idcs:IdentityPropagationTrust"],
    name: "ODyS AWS production RPST",
    active: true,
    type: "JWT",
    subjectType: "Resource",
    allowImpersonation: true,
    issuer: $issuer,
    publicKeyEndpoint: ($issuer + "/.well-known/jwks.json"),
    oauthClients: [$client],
    clientClaimName: "aud",
    clientClaimValues: [$audience],
    claimValidations: [{name: "sub", value: $role}],
    impersonatingResource: "odys_aws",
    claimPropagations: ["ext_sub", "ext_iss"]
  }' > odys-trust.json

curl --fail --silent --show-error \
  --header "Authorization: Bearer $ADMIN_OAUTH_TOKEN" \
  --header 'Content-Type: application/json' \
  --data-binary @odys-trust.json \
  "$DOMAIN_URL/admin/v1/IdentityPropagationTrusts" > created-trust.json
jq '{id,name,active,issuer,subjectType}' created-trust.json

Record the trust ID. Read it back to verify the saved configuration:

TRUST_ID="$(jq -er '.id' created-trust.json)"
curl --fail --silent --show-error \
  --header "Authorization: Bearer $ADMIN_OAUTH_TOKEN" \
  "$DOMAIN_URL/admin/v1/IdentityPropagationTrusts/$TRUST_ID" | jq .
unset ADMIN_OAUTH_TOKEN

The audience uses the trust’s clientClaimName and clientClaimValues fields, whose purpose is described in the IdentityPropagationTrust model. The role is also checked as an exact JWT sub value. Do not substitute the instance profile ARN or an STS session ARN.

This is the Resource trust from Step 1 – Identity Propagation Trust Configuration in my RPST article, adapted to AWS. It requires no OCI service user or group membership. Selected source claims become RPST attributes such as var_ext_sub; IAM references them as request.principal.ext_sub. res_type must match odys_aws at exchange time. Oracle’s current RPST exchange documentation describes claim validation, propagation, request authentication, and the resource type check.

Step 5 Authorize the federated workload to scale the database

Create an OCI IAM policy in a location that governs the target compartments, using the Console’s manual policy editor. Replace the role, issuer, and compartment names below. Use the exact issuer from Step 1 in every condition.

Allow any-user to read cloud-vmclusters in compartment DB_COMPARTMENT where all {
  request.principal.type = 'identityfederateddomainapp',
  request.principal.ext_sub = 'arn:aws:iam::123456789012:role/OdysOciScaler',
  request.principal.ext_iss = 'https://REPLACE_ME.tokens.sts.global.api.aws'
}

Allow any-user to use cloud-vmclusters in compartment DB_COMPARTMENT where all {
  request.principal.type = 'identityfederateddomainapp',
  request.principal.ext_sub = 'arn:aws:iam::123456789012:role/OdysOciScaler',
  request.principal.ext_iss = 'https://REPLACE_ME.tokens.sts.global.api.aws',
  request.permission = 'CLOUD_VM_CLUSTER_UPDATE_CPU'
}

Allow any-user to use cloud-exadata-infrastructures in compartment INFRA_COMPARTMENT where all {
  request.principal.type = 'identityfederateddomainapp',
  request.principal.ext_sub = 'arn:aws:iam::123456789012:role/OdysOciScaler',
  request.principal.ext_iss = 'https://REPLACE_ME.tokens.sts.global.api.aws'
}

The infrastructure permission follows the ODyS KB’s ExaDB-D prerequisites. The VM cluster statements separate read access from CPU updates; Oracle documents CLOUD_VM_CLUSTER_UPDATE_CPU in Exadata IAM permissions. A dedicated compartment containing the intended scaling target gives this example a clear resource boundary. If the compartment contains other clusters, this policy covers them too; scope the deployment’s policy further using supported resource conditions or compartment isolation before production use.

any-user is combined with conditions restricting the principal type and propagated AWS identity. A matching token still needs the relevant OCI permission for each API request. An EC2 IAM role by itself grants no OCI database permissions.

Step 6 Store the runtime OAuth credential in AWS Secrets Manager

In the AWS Secrets Manager console, choose Store a new secret → Other type of secret. Add two string keys, client_id and client_secret, with the OdysTokenExchange values. Use the AWS managed Secrets Manager encryption key for this example, name the secret odys/oci/token-exchange, and save it. Record its full ARN. Keep the administrator application secret off EC2.

On the AWS administration workstation, save this as read-exchange-secret.json, replacing the ARN with the actual secret ARN, including its generated suffix:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": "secretsmanager:GetSecretValue",
    "Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:odys/oci/token-exchange-REPLACE_ME"
  }]
}
aws iam put-role-policy --role-name OdysOciScaler \
  --policy-name ReadOciExchangeCredential \
  --policy-document file://read-exchange-secret.json

If using a customer-managed KMS key instead, authorize the role for the required decrypt operation in both IAM and the KMS key policy. See Secrets Manager credential retrieval permissions.

Step 7 Install ODyS and its runtime on EC2

On the Oracle Linux 9 EC2 host, install prerequisites and create a dedicated service account:

sudo dnf install -y python3.11 python3.11-pip openssl jq unzip openssh-clients
sudo useradd --system --create-home --home-dir /var/lib/odys --shell /bin/bash odys
sudo install -d -o root -g odys -m 0750 /etc/odys-wif
sudo install -d -o root -g root -m 0755 /opt/odys-wif
sudo python3.11 -m venv /opt/odys-wif/venv
sudo /opt/odys-wif/venv/bin/pip install --upgrade pip
sudo /opt/odys-wif/venv/bin/pip install oci-cli boto3 requests cryptography

Download the Oracle Linux 9 ODyS distribution from KB38275 using your Oracle Support access. Extract the ZIP and install the RPM it contains. Replace the paths with the downloaded files:

unzip /path/to/p39231705_dynamicscaling-220_Linux-x86-64.zip -d /tmp/odys-package
sudo rpm -ivh /path/to/extracted/Dynamicscaling-2.2.0-2.el9.x86_64.rpm
sudo install -d -o odys -g odys -m 0750 /var/lib/odys/log
sudo /opt/odys-wif/venv/bin/oci --version
sudo /opt/odys-wif/venv/bin/pip freeze

The ODyS binary is /opt/dynamicscaling/dynamicscaling.bin. Use the exact RPM filename in the downloaded distribution if it differs. Record the RPM version and the virtual environment package versions for repeatable deployment.

Create /etc/tmpfiles.d/odys-wif.conf as root:

d /run/odys-wif 0700 odys odys -
sudo systemd-tmpfiles --create /etc/tmpfiles.d/odys-wif.conf

The RPST and its private key will be stored in this restricted, volatile directory. It is recreated after reboot.

Step 8 Obtain an AWS JWT and exchange it for RPST

First, test JWT issuance on EC2 as odys, using the current AWS CLI v2 installed on the host:

sudo -u odys bash
umask 077
aws sts get-web-identity-token \
  --region us-east-1 --endpoint-url https://sts.us-east-1.amazonaws.com \
  --audience https://odys.example.com/oci/prod \
  --signing-algorithm RS256 --duration-seconds 300 \
  --query WebIdentityToken --output text > /run/odys-wif/aws.jwt

This is GetWebIdentityToken, an outbound AWS identity operation. It is distinct from AssumeRoleWithWebIdentity, which accepts an external token to assume an AWS role. The AWS JWT here is signed by STS and includes the workload identity; the instance-profile session token is not itself the JWT to send to OCI. The STS API reference specifies the parameters, WebIdentityToken response field, short lifetime, and regional endpoint requirement.

Inspect only the needed claims locally; do not paste a live token into a public decoder:

/opt/odys-wif/venv/bin/python - <<'PY'
import base64, json
from pathlib import Path
s = Path('/run/odys-wif/aws.jwt').read_text().strip().split('.')[1]
p = json.loads(base64.urlsafe_b64decode(s + '=' * (-len(s) % 4)))
print(json.dumps({k:p.get(k) for k in ('iss','sub','aud','iat','exp')}, indent=2))
PY

Confirm the issuer, IAM role ARN, and audience match the OCI trust. Decoding is inspection, not signature verification. OCI performs the actual issuer, signature, expiry, and trust checks.

Create the proof-of-possession key and perform the first exchange. Retrieve the runtime client credential without printing it:

openssl genrsa -out /run/odys-wif/private.pem 2048
openssl rsa -in /run/odys-wif/private.pem -pubout -out /run/odys-wif/public.pem
export DOMAIN_URL='https://idcs-REPLACE_ME.identity.oraclecloud.com'
export SECRET_ARN='arn:aws:secretsmanager:us-east-1:123456789012:secret:odys/oci/token-exchange-REPLACE_ME'
aws secretsmanager get-secret-value --region us-east-1 \
  --secret-id "$SECRET_ARN" --query SecretString --output text \
  > /run/odys-wif/client.json

Use Python so the client secret and live JWT are not passed as curl command-line arguments:

/opt/odys-wif/venv/bin/python - <<'PY'
import json, os
from pathlib import Path
import requests
p = Path('/run/odys-wif')
c = json.loads((p/'client.json').read_text())
r = requests.post(os.environ['DOMAIN_URL'] + '/oauth2/v1/token',
    auth=(c['client_id'], c['client_secret']), data={
        'grant_type':'urn:ietf:params:oauth:grant-type:token-exchange',
        'requested_token_type':'urn:oci:token-type:oci-rpst',
        'subject_token_type':'jwt',
        'subject_token':(p/'aws.jwt').read_text().strip(),
        'public_key':(p/'public.pem').read_text(),
        'res_type':'odys_aws', 'rpst_exp':'60'
    }, timeout=(10,30))
r.raise_for_status()
(p/'rpst').write_text(r.json()['token'])
print('RPST saved')
PY
rm /run/odys-wif/aws.jwt /run/odys-wif/client.json

This applies Steps 3–5 of my RPST article: request urn:oci:token-type:oci-rpst, supply the public key, match res_type, and retain the private key for signed requests. The official exchange response contains token; it is not the administrator OAuth response’s access_token field. rpst_exp=60 requests 60 minutes. Renewal below uses the actual returned expiry rather than assuming the requested duration was granted.

Keep TLS verification enabled. The public key sent to OCI belongs to the workload, while the AWS JWKS belongs to the token issuer. They serve different purposes.

Step 9 Make OCI CLI use the RPST

Still as odys, set these variables, using the actual OCI API region:

export OCI_RESOURCE_PRINCIPAL_VERSION='2.2'
export OCI_RESOURCE_PRINCIPAL_RPST='/run/odys-wif/rpst'
export OCI_RESOURCE_PRINCIPAL_PRIVATE_PEM='/run/odys-wif/private.pem'
export OCI_RESOURCE_PRINCIPAL_REGION='REPLACE_OCI_REGION'
export OCI_CLI_AUTH='resource_principal'
export CLUSTER_OCID='ocid1.cloudvmcluster.REPLACE_ME'

/opt/odys-wif/venv/bin/oci db cloud-vm-cluster get \
  --cloud-vm-cluster-id "$CLUSTER_OCID" \
  --region "$OCI_RESOURCE_PRINCIPAL_REGION" --auth resource_principal

The version 2.2 resource principal signer accepts absolute paths for the RPST and PEM key. Each ODyS CLI invocation can read the current token file; no OCI user OCID, API key fingerprint, or user API key registration is needed. Oracle’s CLI authentication implementation and ephemeral resource principal signer document these environment variables and file-based credentials.

Inspect the RPST locally using the same decoding method from Step 8, changing the input filename to rpst. Check exp and propagated attributes var_ext_sub and var_ext_iss. Never print the complete token in logs. If exchange succeeds but the database request fails, check OCI policy conditions and resource region/compartment independently of the trust.

Step 10 Renew the RPST for unattended operation

A running ODyS daemon outlives a short-lived token. An expired credential file does not renew itself. Install the accompanying refresh_rpst.py as /opt/odys-wif/refresh_rpst.py, owned by root and readable/executable by the service account. Its complete source is included in the appendix.

Create /etc/odys-wif/config.json with the actual environment values:

{
  "aws_region": "us-east-1",
  "sts_endpoint": "https://sts.us-east-1.amazonaws.com",
  "aws_issuer": "https://REPLACE_ME.tokens.sts.global.api.aws",
  "aws_role_arn": "arn:aws:iam::123456789012:role/OdysOciScaler",
  "audience": "https://odys.example.com/oci/prod",
  "domain_url": "https://idcs-REPLACE_ME.identity.oraclecloud.com",
  "secret_arn": "arn:aws:secretsmanager:us-east-1:123456789012:secret:odys/oci/token-exchange-REPLACE_ME"
}

Set root ownership and group odys with mode 0640. The file contains identifiers, not the OAuth client secret. The helper obtains that secret from Secrets Manager using the instance role. It generates the proof-of-possession key if absent, retains it for the current boot, requests a fresh AWS JWT, exchanges it, and atomically replaces only the RPST file. Keeping the key stable avoids a race between a new token and a different private key. The helper leaves the existing RPST untouched when refresh fails.

Create /etc/systemd/system/odys-rpst.service:

[Unit]
Description=Refresh ODyS federated OCI resource principal token
Wants=network-online.target
After=network-online.target systemd-tmpfiles-setup.service

[Service]
Type=oneshot
User=odys
Group=odys
UMask=0077
ExecStart=/opt/odys-wif/venv/bin/python /opt/odys-wif/refresh_rpst.py
TimeoutStartSec=180

Create /etc/systemd/system/odys-rpst.timer:

[Unit]
Description=Refresh ODyS OCI token every five minutes

[Timer]
OnBootSec=30s
OnUnitActiveSec=5min
Unit=odys-rpst.service

[Install]
WantedBy=timers.target

Then, from an administrative shell on EC2:

sudo systemctl daemon-reload
sudo systemctl start odys-rpst.service
sudo systemctl enable --now odys-rpst.timer
sudo systemctl status odys-rpst.service odys-rpst.timer
sudo journalctl -u odys-rpst.service --no-pager -n 20

Monitor refresh failures and remaining RPST lifetime. If renewal is unavailable long enough for the current RPST to expire, OCI rejects further calls and scaling automation is unavailable until renewal recovers. Existing database capacity is unchanged by token expiry. Rotate the OAuth secret through your credential-management process and update its Secrets Manager value; the next refresh retrieves it.

Step 11 Supply database load to the external scaler

This example uses a small read-only collector on each database guest VM and a restricted SSH key. The collector returns one-minute load average and online CPU count. The EC2 plugin normalizes each sample to a 0–100 integer and returns the maximum across nodes. Load average is a runnable/blocked workload indicator, not a direct CPU utilization percentage; validate its behavior against your database workload and tune thresholds accordingly.

Install the appendix’s db-load.sh as root-owned /usr/local/bin/odys-db-load with mode 0755 on every database guest VM. Create an unprivileged odysmon account with no sudo rights. The collector needs only read access to /proc/loadavg and getconf. On each guest VM, using its normal administrative account, run:

sudo useradd --create-home --shell /bin/bash odysmon
sudo install -o root -g root -m 0755 db-load.sh /usr/local/bin/odys-db-load
sudo install -d -o odysmon -g odysmon -m 0700 /home/odysmon/.ssh
sudo install -o odysmon -g odysmon -m 0600 /dev/null /home/odysmon/.ssh/authorized_keys

Use a newly created account for this example; do not overwrite an existing account’s keys. On SELinux-enabled hosts, restore the account directory’s security labels after installing its SSH files using sudo restorecon -RF /home/odysmon/.ssh.

On EC2, generate a dedicated telemetry key:

sudo -u odys mkdir -p /var/lib/odys/.ssh
sudo chmod 0700 /var/lib/odys/.ssh
sudo -u odys ssh-keygen -t ed25519 -N '' \
  -f /var/lib/odys/.ssh/telemetry

Using the normal database host administration connection, create /home/odysmon/.ssh with mode 0700 and an authorized_keys file with mode 0600, both owned by odysmon. Add the public key from EC2 with this prefix on the same line:

restrict,command="/usr/local/bin/odys-db-load" ssh-ed25519 REPLACE_WITH_EC2_TELEMETRY_PUBLIC_KEY

The forced command permits only the collector and disables forwarding and interactive features. Allow SSH to these guest VMs only from the designated scaler security boundary. Record each DB host’s SSH public host key through a trusted administration channel, verify its fingerprint on the guest VM, and add entries for the exact private DNS names used below to /etc/odys-wif/known_hosts. Give that file root ownership, group odys, and mode 0640. Do not disable host-key checking or treat an unverified ssh-keyscan result as trusted.

Create /etc/odys-wif/db-nodes.json, root-owned with group odys and mode 0640:

["dbnode1.private.example.com", "dbnode2.private.example.com"]

List every node and update the file when cluster membership changes. Install the appendix’s cluster_load.py as /opt/odys-wif/cluster_load.py, root-owned, mode 0755. Test it as the service user:

sudo -u odys /opt/odys-wif/cluster_load.py

The only standard output must be one integer from 0 to 100. An unreachable or invalid node causes the example to return 70, inside the configured 60–80 neutral band, and emit an error on standard error. This avoids interpreting missing telemetry as an idle database. Alert on that condition. If thresholds change, change the neutral fallback too. Do not combine this plugin with ODyS --acfs; the KB documents them as alternative load sources.

Step 12 Configure and validate ODyS

Create /etc/odys-wif/runtime.env with the actual OCI region:

OCI_RESOURCE_PRINCIPAL_VERSION=2.2
OCI_RESOURCE_PRINCIPAL_RPST=/run/odys-wif/rpst
OCI_RESOURCE_PRINCIPAL_PRIVATE_PEM=/run/odys-wif/private.pem
OCI_RESOURCE_PRINCIPAL_REGION=REPLACE_OCI_REGION
OCI_CLI_AUTH=resource_principal
ODYS_HOME=/var/lib/odys
PATH=/opt/odys-wif/venv/bin:/usr/local/bin:/usr/bin:/bin

Record the cluster shape from the successful OCI CLI get response (data.shape) and use that exact value in the configuration. This supplies the shape explicitly for remote execution. Create /etc/odys-wif/dynamicscaling.conf:

ocicli
auth = resource_principal
cloud-vm-cluster-id = ocid1.cloudvmcluster.REPLACE_ME
ociregion = REPLACE_OCI_REGION
shape = REPLACE_WITH_DATA_SHAPE
maxocpu = 96
minocpu = 8
ocpu = 4
maxthreshold = 80
minthreshold = 60
interval = 300
plugin = /opt/odys-wif/cluster_load.py
logfile = /var/lib/odys/log/dynamicscaling.log
nodaemon

These capacity values illustrate the configuration. Replace them with valid cluster totals and increments agreed with the database team. Confirm that minimum, maximum, available capacity, quotas, and the target shape permit the planned changes. For an ECPU-based Cloud VM Cluster, retain its cloud-vm-cluster-id, replace the three OCPU settings with maxecpu, minecpu, and ecpu, and use getecpu/setecpu. For example, maxecpu=192, minecpu=16, and ecpu=8 are illustrative values to validate for that deployment. The resource option is selected by service resource type, not by CPU unit alone.

Set both configuration files to root ownership, group odys, mode 0640. Open a shell as odys and load the environment:

sudo -u odys bash
set -a
source /etc/odys-wif/runtime.env
set +a

/opt/dynamicscaling/dynamicscaling.bin \
  --config /etc/odys-wif/dynamicscaling.conf check
/opt/dynamicscaling/dynamicscaling.bin \
  --config /etc/odys-wif/dynamicscaling.conf getocpu
/opt/dynamicscaling/dynamicscaling.bin \
  --config /etc/odys-wif/dynamicscaling.conf --dryrun

Run the dry run in the foreground and review its load samples and proposed changes. Stop it with Ctrl-C. Confirm the effective command includes --ocicli and resource_principal; ODyS’s direct REST/API-key authentication path is not the path used here.

During a planned nonproduction test, with the automatic scaler stopped, perform one authorized scale-up and scale-down to valid, agreed totals:

/opt/dynamicscaling/dynamicscaling.bin \
  --config /etc/odys-wif/dynamicscaling.conf setocpu --ocpu 16
# Wait for the cluster operation to complete and verify its lifecycle state.
/opt/dynamicscaling/dynamicscaling.bin \
  --config /etc/odys-wif/dynamicscaling.conf getocpu
/opt/dynamicscaling/dynamicscaling.bin \
  --config /etc/odys-wif/dynamicscaling.conf setocpu --ocpu 8

For ECPU, use setecpu --ecpu <agreed-total> and getecpu. Do not start overlapping scaling operations. Verify both ODyS logs and the resulting OCI resource state. The KB notes that scale operations can take several minutes, so choose monitoring intervals and scaling increments accordingly.

Step 13 Start the unattended service

Create /etc/systemd/system/odys.service:

[Unit]
Description=ODyS for Oracle Database at AWS using federated RPST
Wants=network-online.target odys-rpst.timer
After=network-online.target systemd-tmpfiles-setup.service

[Service]
Type=simple
User=odys
Group=odys
UMask=0077
EnvironmentFile=/etc/odys-wif/runtime.env
ExecStartPre=/opt/odys-wif/venv/bin/python /opt/odys-wif/refresh_rpst.py
ExecStart=/opt/dynamicscaling/dynamicscaling.bin --config /etc/odys-wif/dynamicscaling.conf
Restart=on-failure
RestartSec=15
TimeoutStartSec=180
KillSignal=SIGINT
TimeoutStopSec=60

[Install]
WantedBy=multi-user.target

ExecStartPre obtains a valid RPST before each ODyS start. nodaemon in the ODyS configuration keeps the process in the foreground so systemd can supervise it. Exit the service-user shell and enable the service as an administrator:

sudo systemctl daemon-reload
sudo systemctl enable --now odys.service
sudo systemctl status odys.service odys-rpst.timer
sudo journalctl -u odys.service -u odys-rpst.service --since '15 minutes ago'

Keep only one active scaler for this target unless you implement a supported coordination design. A second independent EC2 scaler can issue competing decisions. Stop the service during patching or other conflicting database lifecycle operations.

Validate Identity restrictions and renewal

Before production, exercise the intended failure cases as well as a successful scaling cycle:

  • Request a different audience. The AWS role policy should deny minting it; an independently obtained mismatched token must also fail the OCI audience check.
  • Test a token from a different AWS role. The OCI trust must reject its subject.
  • Test a mismatched res_type or unauthorized OAuth client. OCI must reject the exchange.
  • Confirm that a federated read succeeds and that only the intended CPU update permissions are available.
  • Allow the initially issued RPST to reach its original expiry while the timer continues refreshing. Verify that new OCI CLI calls still succeed and that refresh logs show a later expiry.
  • Interrupt telemetry and verify the neutral-band result, logging, and alerts. Restore it before testing load-driven changes.
  • Reboot EC2 and confirm the runtime directory, new key pair, token refresh, timer, and ODyS service all recover.

Correlate AWS CloudTrail events for STS and secret retrieval with OCI Audit records for database API calls and ODyS scaling logs. Validate the identity fields actually emitted in your environment rather than assuming every external claim appears in every audit record.

Closing perspective

For DB@Multicloud customers, database operations can follow the application team’s cloud operating model while OCI retains control-plane authorization. In DB@AWS, an EC2 instance profile provides the starting identity, AWS STS turns it into a verifiable JWT, and OCI WIF exchanges that identity for an RPST with narrowly assigned database permissions.

The complete operating design includes both identity and lifecycle: trust validation, proof of possession, appropriate IAM policy, fresh database telemetry, and token renewal. Together, these allow ODyS to run from AWS without provisioning a long-lived OCI user API signing key on the scaler.

PS: I am helping one other customer implement the same for database@Azure. Steps to implement the same for Azure will be published early next year.

Resources

Appendix Complete helper programs

The following programs are integration examples for this walkthrough. They complement ODyS; they are not part of its distributed RPM. Install them at the paths specified above and validate them with the target ODyS release and DB@AWS environment.

RPST renewal helper

Save as /opt/odys-wif/refresh_rpst.py, root-owned, mode 0755.

#!/opt/odys-wif/venv/bin/python
"""Refresh externally federated RPST files for the OCI CLI resource principal signer."""
import base64
import datetime
import fcntl
import json
import os
from pathlib import Path
import tempfile
import time

import boto3
from botocore.config import Config
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
import requests


def claims(token):
    # Inspection only. OCI validates the AWS JWT; these values do not authorize access.
    payload = token.split('.')[1]
    return json.loads(base64.urlsafe_b64decode(payload + '=' * (-len(payload) % 4)))


def atomic_write(path, content):
    fd, temporary = tempfile.mkstemp(dir=path.parent)
    try:
        with os.fdopen(fd, 'w') as stream:
            stream.write(content)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temporary, path)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)


def main():
    os.umask(0o077)
    cfg = json.loads(Path('/etc/odys-wif/config.json').read_text())
    state = Path('/run/odys-wif')
    with (state / 'refresh.lock').open('w') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        key_path = state / 'private.pem'
        if key_path.exists():
            key = serialization.load_pem_private_key(key_path.read_bytes(), password=None)
        else:
            key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
            atomic_write(key_path, key.private_bytes(
                serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
                serialization.NoEncryption()).decode())
        public_key = key.public_key().public_bytes(
            serialization.Encoding.PEM,
            serialization.PublicFormat.SubjectPublicKeyInfo).decode()
        session = boto3.Session(region_name=cfg['aws_region'])
        options = Config(connect_timeout=10, read_timeout=30,
                         retries={'mode': 'standard', 'max_attempts': 3})
        sts = session.client('sts', endpoint_url=cfg['sts_endpoint'], config=options)
        jwt = sts.get_web_identity_token(
            Audience=[cfg['audience']], SigningAlgorithm='RS256',
            DurationSeconds=300)['WebIdentityToken']
        source = claims(jwt)
        if source['iss'] != cfg['aws_issuer'] or source['sub'] != cfg['aws_role_arn']:
            raise RuntimeError('Unexpected AWS workload identity')
        credentials = json.loads(session.client('secretsmanager', config=options)
            .get_secret_value(SecretId=cfg['secret_arn'])['SecretString'])
        response = requests.post(
            cfg['domain_url'].rstrip('/') + '/oauth2/v1/token',
            auth=(credentials['client_id'], credentials['client_secret']),
            data={
                'grant_type': 'urn:ietf:params:oauth:grant-type:token-exchange',
                'requested_token_type': 'urn:oci:token-type:oci-rpst',
                'subject_token_type': 'jwt', 'subject_token': jwt,
                'public_key': public_key, 'res_type': 'odys_aws', 'rpst_exp': '60'
            }, timeout=(10, 30))
        response.raise_for_status()
        token = response.json()['token']
        expiration = int(claims(token)['exp'])
        if expiration < time.time() + 600:
            raise RuntimeError('RPST has insufficient remaining lifetime')
        atomic_write(state / 'rpst', token)
        print('RPST refreshed; expires ' + datetime.datetime.fromtimestamp(
            expiration, datetime.timezone.utc).isoformat())


if __name__ == '__main__':
    main()

Database guest VM collector

Save as /usr/local/bin/odys-db-load on every DB guest VM, root-owned, mode 0755.

#!/bin/bash
set -euo pipefail
# Run on each DB guest VM. Read load average and the online CPU count locally.
awk '{print $1}' /proc/loadavg
getconf _NPROCESSORS_ONLN

EC2 load plugin

Save as /opt/odys-wif/cluster_load.py on EC2, root-owned, mode 0755.

#!/opt/odys-wif/venv/bin/python
"""ODyS plugin: maximum normalized one-minute load over all configured DB nodes."""
from concurrent.futures import ThreadPoolExecutor
import json
import math
from pathlib import Path
import subprocess
import sys


def sample(host):
    result = subprocess.run([
        '/usr/bin/ssh', '-F', '/dev/null', '-o', 'BatchMode=yes',
        '-o', 'IdentitiesOnly=yes', '-o', 'StrictHostKeyChecking=yes',
        '-o', 'ConnectTimeout=5', '-o',
        'UserKnownHostsFile=/etc/odys-wif/known_hosts',
        '-i', '/var/lib/odys/.ssh/telemetry', 'odysmon@' + host
    ], check=True, capture_output=True, text=True, timeout=10)
    load, cpus = result.stdout.split()
    load, cpus = float(load), int(cpus)
    if not math.isfinite(load) or load < 0 or cpus < 1:
        raise ValueError('Invalid node telemetry')
    return min(100, math.ceil(100 * load / cpus))


try:
    hosts = json.loads(Path('/etc/odys-wif/db-nodes.json').read_text())
    if not hosts or not all(isinstance(h, str) and h and not h.startswith('-')
                            and not any(c.isspace() for c in h) for h in hosts):
        raise ValueError('Configure every DB node')
    with ThreadPoolExecutor(max_workers=len(hosts)) as pool:
        print(max(pool.map(sample, hosts)))
except Exception:
    # With thresholds 60 and 80, 70 requests neither up nor down scaling.
    # Do not convert missing telemetry into a low-load sample.
    print('ODyS telemetry unavailable; holding load at 70', file=sys.stderr)
    print(70)