Oracle Cloud Free Tier: Getting a VM, Setting Budget Alerts, and Deploying an SGD 5 Auto-Stop Guard
A cloud VM running a few lightweight jobs can have a zero bill and still leave a question hanging: what happens if a program goes wrong, or someone compromises the server and starts generating traffic?
For this deployment, an Oracle Cloud ARM instance in Singapore now checks the tenancy's monthly cost every 15 minutes. At SGD 5, it calls the cloud API to stop that instance. The first production-mode check succeeded, reported 0 SGD, and left the instance running.
One boundary matters up front: authorization, cost retrieval, the below-threshold decision, and scheduled execution were verified. No money was deliberately spent to reach the threshold, and no actual shutdown was triggered. This is a cost safeguard, not an exact SGD 5 billing cap.
This article starts with getting a VM, then explains why budget alerts alone are insufficient and how the automatic check was deployed. Signup and budget instructions are based on official documentation; the hands-on findings come from an existing instance. Account details, addresses, and resource identifiers have been removed or replaced.
Separate trial credits from ongoing free allowances
Oracle Cloud Free Tier includes time-limited trial credits and Always Free resources. The website currently lists up to US$300 in credits valid for up to 30 days. Being able to create a resource during the trial does not mean it remains free afterward. Free Tier documentation
Start at the Oracle Cloud Free Tier website. Signup typically requires an email address, a phone number, and an eligible payment card for identity verification. Oracle says temporary card authorization holds are not actual charges; virtual, single-use, and prepaid cards are not accepted. Signup success rates were not tested for this article, and there is no claim of a guaranteed signup method. Signup FAQ
Pay attention to Home Region. Always Free compute instances must be created there. Selecting another region with apparent capacity does not carry the free compute eligibility with it. This deployment happens to be in Singapore; that is not a recommendation that every new account should select Singapore.
Older tutorials can also give the wrong numbers. As checked on November 9, 2026, Oracle's Always Free documentation lists:
| Resource | Currently documented allowance |
|---|---|
| Ampere A1 compute | 1,500 OCPU-hours and 9,000 GB-hours of memory per month, roughly equivalent to 2 OCPUs and 12GB running continuously |
| Block storage | 200GB total across boot and block volumes |
| Outbound data | 10TB per month |
Do not copy an older “4 cores, 24GB” recommendation without checking the current documentation, account limits, and actual billing details. Creating another instance does not create another independent free allowance. Always Free resources
Create the instance—and understand capacity errors
In your home region, open Compute → Instances → Create instance. For ARM, select VM.Standard.A1.Flex, allocate CPU and memory within your remaining free allowances, and choose a compatible Linux image.
Configure networking and an SSH public key. Public SSH access requires an appropriate public network path; restrict the SSH ingress rule to your source address where possible. Keep the private key locally rather than pasting it into articles, chats, or repositories. A1 uses ARM, so downloaded binaries need to support arm64/aarch64, not just x86.
Check the boot volume size, image licensing, and any additional resources. Free CPU and memory do not make every associated resource free.
An out of host capacity error means capacity is unavailable. Oracle suggests trying another availability domain or trying again later. Upgrading to a paid account expands the available resource choices; it does not establish a guarantee of A1 capacity. Oracle also says idle Always Free instances may be reclaimed, so important data needs another copy. Capacity and idle-instance documentation
Upgrading to Pay As You Go is a separate decision. A free trial does not automatically become a paid account when it ends. On an upgraded account, eligible Always Free usage remains free and usage above the allowances is billed under the applicable rules. The auto-stop guard is particularly relevant when an account can incur paid usage. Free and paid account overview
Set a budget alert, but do not mistake it for a switch
Open Billing & Cost Management → Budgets → Create Budget. For an SGD 5 monthly budget:
| Field | Setting |
|---|---|
| Budget Scope | Compartment |
| Target Compartment | Root compartment for the whole tenancy, or the compartment for a specific project |
| Schedule | Monthly |
| Budget Amount | 5; verify the displayed currency |
| Start day | First day of the month |
| Threshold Metric | Actual Spend |
| Threshold Type | Absolute Amount |
| Threshold Amount | 5 |
| Email Recipients | An email address you actually monitor |
You can add another actual-spend rule at SGD 1 within the same budget to catch the first charges on an otherwise free account. That is a suggested configuration, not an email delivery result verified in this deployment. Budget creation instructions
A budget alert does not stop the instance. Oracle calls budgets soft limits, and its budget overview states that alerts are evaluated every 24 hours. Entering 5 does not cause the server to turn off the instant the fifth dollar is spent. How budgets work
No budget was created through the console during this deployment, and email delivery was not tested. The automatic cost-checking path below was deployed independently; it does not wait for a budget email.
Automatic stopping: query costs, then call OCI
Oracle supports budget events flowing through Events to Functions. That can suit centralized management. For this single instance, the implementation uses a simpler path:
systemd starts a check every 15 minutes
↓
Use instance identity to query current-month tenancy costs
↓
Require SGD and compare the amount with 5
↓
Below threshold: record the result and exit
At or above threshold: request OCI SOFTSTOP for the specified instance
Oracle provides a Budgets → Events → Functions example, but its quota-setting code restricts new resource creation. It does not stop instances that are already running. A shutdown implementation needs its own stop action.
Authorize the instance without installing an administrator's private key
This deployment uses an Instance Principal. An account administrator creates a dynamic group and IAM policy in Cloud Shell. The instance can then authenticate as itself, without storing an administrator's API private key.
Copy the instance OCID from its details page and the tenancy OCID from tenancy details. The placeholders below must be replaced with your own values.
Dynamic-group matching rule:
ALL {instance.id = '<INSTANCE_OCID>'}
After creating the group, copy its OCID and create these policy statements at the tenancy root:
Allow dynamic-group id <DYNAMIC_GROUP_OCID> to {USAGE_REPORT_READ} in tenancy
Allow dynamic-group id <DYNAMIC_GROUP_OCID> to {INSTANCE_READ, INSTANCE_POWER_ACTION} in tenancy where target.instance.id = '<INSTANCE_OCID>'
The first statement permits cost retrieval. The second restricts instance reads and power actions to one instance. Power-action permission includes operations such as starting and stopping; the script only requests a stop. There is no need to grant tenancy-wide resource administration.
The first deployment issue appeared in Cloud Shell: a Python wrapper around OCI CLI failed with Expecting value: line 1 column 1 (char 0). Region retrieval worked. After adding empty-output handling to list commands, group and policy creation succeeded. Only a list operation may interpret empty output as an empty list; empty output from a create operation remains an error, so missing creation results cannot silently count as success.
Query monthly cost, not CPU utilization
The script calls Usage API with query_type='COST', groups by currency, and requests reported costs between the first day of the current UTC month and the first day of the next month. There is no regional or compartment filter, so it checks the whole tenancy, but stops only the configured instance.
A monthly time range does not mean forecast spending is included. The request does not ask for a forecast, and the code rejects any unexpectedly forecast-marked row. See Oracle's COST query and time-boundary documentation.
The second issue was currency. The initial request referred to “5 dollars,” but the API returned:
{"computed_amount": 0.0, "currency": "SGD"}
A Singapore region and an SGD billing currency are different facts. The program must inspect the returned currency. The final choice was an SGD 5 threshold, removing exchange-rate conversion and its external dependency.
Stop through the cloud platform
At the threshold, the script calls:
compute.instance_action(INSTANCE, 'SOFTSTOP')
It does not run sudo shutdown -h now.
Oracle explicitly says that shutting down from inside the operating system does not stop instance billing; the instance must also be stopped through the console or API. Stopping Standard shapes pauses compute billing. Some GPU, Dense I/O, and HPC shapes have different rules. This deployment targets VM.Standard.A1.Flex. Billing for stopped instances
What the deployment actually showed
The environment was Oracle Linux 9 ARM64 with OCI Python SDK 2.187.0. The script lives at /opt/oracle-cost-guard/check.py and runs through a systemd service and timer.
It was first run without --execute, which queries and evaluates costs without stopping anything. After checking the account, currency, amount, and target instance, execution mode was enabled. Here is the sanitized first production-mode result:
{
"month": "2026-11",
"scope": "tenancy",
"costs": {"SGD": "0.0"},
"sgd": "0.0",
"limit_sgd": "5",
"instance_state": "RUNNING",
"execute": true,
"action": "below_limit"
}
execute: true means the run is allowed to request a stop if the threshold is reached. below_limit means that did not happen on this run. The timer was active.
The implementation handles pagination, rejects unexpected currencies, refuses to treat empty data as zero cost, and exits with an error on failure so systemd records it and the next scheduled run can try again. Those are descriptions of the code, not claims that every failure path was fault-injection tested. No external notification for failed queries is configured.
Useful operational commands:
# Latest result
cat /var/lib/oracle-cost-guard/status.json
# Timer schedule
systemctl list-timers oracle-cost-guard.timer
# Check logs
sudo journalctl -u oracle-cost-guard.service -n 30 --no-pager
# Disable automatic checks
sudo systemctl disable --now oracle-cost-guard.timer
What this safeguard does—and what remains outside it
During normal lightweight use, the task only queries costs and logs a result. If abnormal traffic starts incurring charges, a later check may detect them and stop the instance. However, 15 minutes is the checking interval, not the billing-data refresh interval. Costs that have not reached Usage API are invisible to it. Disks, backups, and other resources do not automatically stop incurring charges when an instance stops.
Cryptomining has another important distinction: saturating the CPU on a fixed-size instance that stays within its free allowances does not necessarily create an additional bill. A cost threshold cannot replace CPU, traffic, or process monitoring. An attacker with administrator access may also disable a checker running on the compromised server itself.
The accepted scope here is deliberately limited: SGD 5 per UTC month, tenancy-wide cost monitoring, one instance to stop, and no automatic restart. If the instance is manually started again while the month's cost remains above the threshold, the next check will request another stop. Costs reset to a new monthly query period at the month boundary; the instance does not start itself.
Authorization, querying, below-threshold evaluation, and scheduled execution were confirmed. An actual over-budget API shutdown, its latency, and the final resulting bill were not tested.
A prompt to give Claude Code or Codex
To have a terminal-capable agent perform the setup, fill in the brackets below. Leave unknown fields as “query this” so the agent resolves them before configuring anything. A local SSH-key path is for local use; do not paste the private key itself.
Please deploy budget alerts and an automatic cost-based stop guard for one Oracle Cloud instance. Complete the deployment rather than only proposing a plan.
My settings:
- SSH connection: [for example, ssh oracle-server; otherwise, needs setup]
- Instance OCID: [value, or query this]
- Instance region: [for example, ap-singapore-1, or query this]
- Tenancy OCID: [value, or query this]
- Monthly stop threshold: [for example, 5 SGD; specify currency, not just $5]
- Alert thresholds and email: [for example, 1 SGD and 5 SGD; address, or skip email]
- Cost scope: entire tenancy; stop only the specified instance
- Period: UTC calendar month, checked every 15 minutes, no automatic restart
I authorize deployment of the cost-check task, the minimum IAM permissions required within this scope, and automation to stop the specified instance when the threshold is reached.
Follow this sequence:
1. Read the project's instructions and inspect existing OCI access, SSH, OS version, and deployment directories. Confirm the instance, its shape's stopped-billing rules, current costs, and actual billing currency. Do not modify other machines or business services.
2. Reuse existing authorization where possible. For Instance Principal, match only the target instance in the dynamic group. Grant only cost-reading access and reads/power actions on that instance. Do not install an administrator API private key or print credentials. Compare existing named resources before reusing them; do not blindly overwrite them.
3. If cloud-management access is missing, explain exactly what is needed and provide authorization commands for my authenticated Cloud Shell. Make them rerunnable, distinguish empty lists from creation failures, and report the failing step. Wait for my execution result rather than assuming authorization succeeded.
4. If email alerts are enabled, configure a Monthly Budget with Actual Spend alerts and verify the amounts, currency, scope, and recipients. Budget alerts are separate from automatic stopping. Do not claim email delivery was verified unless an email was actually received.
5. Deploy a separate checker and systemd service/timer. Query this month's COST through Usage API, handle pagination, compare amounts precisely, and reject forecast data, empty responses, and unexpected currencies. Log failures and retry at the next scheduled run rather than treating failures as zero. If the account currency differs from my threshold, explain and ask me to choose; do not add an exchange-rate service on your own.
6. At or above the threshold, call OCI SOFTSTOP only for the specified instance. Do not substitute an OS shutdown or delete instances, volumes, or backups. Record check time, month, costs, currency, threshold, instance state, and action result.
7. First query the actual bill in a mode that cannot stop the instance. If it is below the threshold, proceed to enable the task. If it is already at or above the threshold, show the amount and ask whether I want to enable it now, since deployment could interrupt service. Do not lower the threshold or perform a real shutdown just to test it.
8. Run one production-mode check and inspect the timer. Deliver deployment paths, current costs, the next check time, and commands to inspect logs and pause the task. Separate completed, failed, and unverified work. A successful zero-cost check is not an end-to-end over-budget shutdown test.
Explain the relevant limits: cost data is delayed; other resources can keep billing after the instance stops; an administrator-level attacker could disable an on-instance checker; high CPU use may not increase charges, so this does not replace intrusion monitoring.
This prompt authorizes a limited deployment. It does not give the agent access to your Oracle account. Any required login or Cloud Shell authorization still happens in your own account.
Appendix: sanitized deployment code
The code below preserves the deployed logic and replaces tenancy and instance OCIDs with placeholders. Complete the IAM setup above, fill in your OCIDs, and check REGION and billing currency. This version expects SGD; other currencies produce an error rather than a guessed conversion.
The Linux host needs Python 3, the oci SDK, and systemd. The SDK was already installed on the tested host. On another host, you can install it in a dedicated virtual environment and point the service at that interpreter. The example uses Oracle Linux's opc user and group; adjust them for a different system.
Save as /opt/oracle-cost-guard/check.py:
#!/usr/bin/env python3
"""Stop only the configured instance when UTC monthly tenant cost reaches SGD 5."""
import argparse
from datetime import datetime, timezone
from decimal import Decimal
import json
from pathlib import Path
import sys
import oci
TENANCY = '<TENANCY_OCID>'
INSTANCE = '<INSTANCE_OCID>'
REGION = 'ap-singapore-1'
LIMIT = Decimal('5')
STATE = Path('/var/lib/oracle-cost-guard')
def save(name, value):
target = STATE / name
temp = target.with_suffix('.tmp')
temp.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
temp.replace(target)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--execute', action='store_true')
args = parser.parse_args()
now = datetime.now(timezone.utc)
start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
end = (start.replace(year=start.year + 1, month=1) if start.month == 12
else start.replace(month=start.month + 1))
signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner()
if signer.tenancy_id != TENANCY:
raise ValueError('Unexpected tenancy')
options = dict(signer=signer, timeout=(10, 60),
retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY)
usage = oci.usage_api.UsageapiClient({'region': REGION}, **options)
compute = oci.core.ComputeClient({'region': REGION}, **options)
instance = compute.get_instance(INSTANCE).data
details = oci.usage_api.models.RequestSummarizedUsagesDetails(
tenant_id=TENANCY, time_usage_started=start, time_usage_ended=end,
granularity='MONTHLY', query_type='COST', group_by=['currency'],
is_aggregate_by_time=True)
totals = {}
page = None
while True:
response = usage.request_summarized_usages(details, page=page)
for row in response.data.items:
if row.is_forecast:
raise ValueError('Unexpected forecast in actual-cost response')
if row.computed_amount is None or not row.currency:
raise ValueError('Missing cost or currency in usage response')
amount = Decimal(str(row.computed_amount))
if not amount.is_finite():
raise ValueError('Non-finite cost')
totals[row.currency] = totals.get(row.currency, Decimal(0)) + amount
page = response.headers.get('opc-next-page')
if not page:
break
if not totals:
raise ValueError('No cost data returned; not treating missing data as zero')
if set(totals) != {'SGD'}:
raise ValueError('Expected SGD billing; received ' + ', '.join(totals))
sgd = totals['SGD']
result = dict(checked_at=now.isoformat(), month=start.strftime('%Y-%m'),
scope='tenancy', costs={k: str(v) for k, v in totals.items()},
sgd=str(sgd), limit_sgd=str(LIMIT),
instance_state=instance.lifecycle_state, execute=args.execute,
action='below_limit' if sgd < LIMIT else 'would_stop')
# Persist the decision before an API call that may shut down this process.
save('status.json', result)
print(json.dumps(result), flush=True)
if sgd >= LIMIT and args.execute:
if instance.lifecycle_state in ('STOPPING', 'STOPPED'):
result['action'] = 'already_stopped_or_stopping'
elif instance.lifecycle_state == 'RUNNING':
result['action'] = 'requesting_softstop'
save('status.json', result)
response = compute.instance_action(INSTANCE, 'SOFTSTOP')
result['action'] = 'softstop_accepted'
result['request_id'] = response.headers.get('opc-request-id')
else:
raise RuntimeError('Instance not ready for stop: ' + instance.lifecycle_state)
save('status.json', result)
print(json.dumps(result), flush=True)
if __name__ == '__main__':
try:
main()
except Exception as exc:
print('ERROR: ' + str(exc), file=sys.stderr, flush=True)
sys.exit(1)
Save as /etc/systemd/system/oracle-cost-guard.service:
[Unit]
Description=Stop Oracle instance at SGD 5 monthly tenant cost
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
User=opc
Group=opc
StateDirectory=oracle-cost-guard
StateDirectoryMode=0700
ExecStart=/usr/bin/python3 /opt/oracle-cost-guard/check.py --execute
TimeoutStartSec=10min
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
UMask=0077
Save as /etc/systemd/system/oracle-cost-guard.timer:
[Unit]
Description=Check Oracle monthly cost every 15 minutes
[Timer]
OnCalendar=*-*-* *:00,15,30,45:00 UTC
Persistent=true
AccuracySec=30s
[Install]
WantedBy=timers.target
After saving the files, create the state directory and run a query-only check:
sudo install -d -o opc -g opc -m 700 /var/lib/oracle-cost-guard
sudo -u opc /usr/bin/python3 /opt/oracle-cost-guard/check.py
Enable it only after the output matches your expectations. The first start command below runs in execution mode: if costs are already at SGD 5, it will immediately attempt to stop the target instance.
sudo systemctl daemon-reload
sudo systemctl start oracle-cost-guard.service
sudo systemctl enable --now oracle-cost-guard.timer
Tested on November 9, 2026. Free allowances, console navigation, and billing rules can change; use current official documentation and your account's actual details when configuring your deployment.