Rds Db2
AWSOfficialPublished by AWS
- Skill
- Tool integration
- Cloud and DevOps
- Apache-2.0
- Medium risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured framework for the lifecycle management of Amazon RDS for Db2. It bridges the gap between general IBM Db2 knowledge and the specific constraints of the AWS managed service, such as the absence of SSH access, the use of rdsadmin procedures, and integration with AWS-native services like Secrets Manager, KMS, and S3. The skill includes detailed workflows for provisioning, cross-region disaster recovery, Kerberos authentication, and complex migrations from on-premises or mainframe environments.
What it does
- Provides AWS CLI-based workflows for provisioning and managing RDS for Db2 instances.
- Details procedures for migrating data from self-managed Db2 LUW or z/OS mainframe environments.
- Configures security controls including customer-managed KMS keys (BYOK) and self-managed Active Directory with Kerberos.
- Manages high availability and disaster recovery via Multi-AZ and cross-region mounted replicas.
- Offers troubleshooting steps for common RDS-specific errors like SQL30082N and S3 integration issues.
- Enforces standardized resource tagging for all created infrastructure.
When to use it
- When deploying or managing Amazon RDS for Db2 instances in production environments.
- When migrating existing IBM Db2 databases from on-premises Linux, AIX, Windows, or z/OS systems.
- When implementing enterprise security requirements like BYOK encryption or Kerberos authentication.
- When configuring cross-region disaster recovery or high-availability standby replicas.
- When troubleshooting connectivity or authentication issues specific to the RDS-managed environment.
Advantages
- Provides RDS-specific operational constraints that general Db2 documentation often omits.
- Standardizes infrastructure deployment with consistent tagging and security best practices.
- Reduces manual effort for complex tasks like S3-based backup/restore and AD domain joining.
- Ensures compliance with AWS-native security patterns like confused-deputy protection.
- Offers clear, actionable CLI commands for deterministic operations.
Usage examples
- “How do I fix SQL30082N errors on my RDS for Db2 instance?”
- The agent identifies that the master password likely rotated in Secrets Manager and instructs the user to run the db2_use helper to refresh the local credential cache.
- “Create a cross-region standby replica for my Db2 instance in us-west-2.”
- The agent provides the exact AWS CLI command using --replica-mode mounted and lists the six mandatory prerequisites, including automated backups and custom parameter groups.
- “How can I use my own KMS key to encrypt my RDS for Db2 instance?”
- The agent explains the BYOK workflow, including the requirement for a multi-region key, the need for specific IAM permissions, and the process for importing key material.
- “Can I use unfenced C stored procedures on RDS for Db2?”
- The agent states clearly that unfenced C/COBOL procedures are not supported and provides guidance on rewriting them in Java or SQL PL.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/aws/rds-db2/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip rds-db2.zip -d .agents/skills
Documentation by AWS
Amazon RDS for Db2
Overview
Amazon RDS for Db2 is a managed IBM Db2 LUW service. RDS for Db2 is managed — you cannot SSH to the host, install agents, or run unfenced external stored procedures in C/COBOL. Java stored procedures work via sqlj.install_jar. This skill covers the operator lifecycle: provisioning with IBM licensing, client install and TLS connectivity, migration from self-managed Db2 on Linux/AIX/Windows/z/OS/AS400, S3 backup and restore, Multi-AZ and cross-region standby replicas, and RDSADMIN stored procedures that replace SYSCTRL/SYSMAINT authority.
It also covers six additional security and operations areas: customer-managed KMS keys (BYOK), self-managed Active Directory with Kerberos authentication, Db2 audit to S3, code page and collation selection (EBCDIC, CCSID), minimum IAM permissions, and EC2/RDS colocation for Multi-AZ latency and failover.
The AWS MCP server is recommended but not required; all operations are expressed in AWS CLI syntax and run with or without it.
Routes to the matching sub-skill reference. Load only the matching reference.
Common Tasks
Verify Dependencies
Before executing an RDS for Db2 workflow, confirm required tools exist. Do not run installers or API calls yet.
AWS CLI v2 for every RDS API call
AWS credentials via managed mechanism (IAM role, instance profile,
ada credentials update) — not pasted credentialsClient install:
bash/curlaccess, run as root and asdb2inst1Airgap install: internet-connected machine + target with VPC endpoints for S3, SSM, Secrets Manager
Mainframe migration: z/OS access, IBM ADB2GEN license, Python 3
BYOK / customer-managed KMS:
openssl(to wrap imported key material) andjq(to parseget-parameters-for-importoutput)Self-managed Active Directory + Kerberos:
realmd,sssd,adcli,krb5-workstationon the client, plus a valid Kerberos ticket (kinitproduces a TGT — check withklist)Kerberos JDBC test: a JDK and the Db2 JDBC driver
db2jcc4.jarv4.33+ (earlier driver versions lacksecurityMechanism=11Kerberos support)
Constraints:
The agent MUST check dependencies before running any install or AWS API command.
The agent MUST NOT prompt the user to paste credentials because credentials MUST flow through an IAM role or instance profile.
The agent MUST tell the user which dependencies are missing and MUST respect the user's decision to abort.
The agent MUST explain, for each step, what it does, why, and which tool will be invoked — before invoking it.
Classify and Route
Map the user's question to the correct sub-skill reference, then load only that file.
| User says | Sub-skill | Load |
|---|---|---|
| create / provision / parameter group / IBM customer ID / IBM site ID / License Manager / BYOL / GovCloud | provisioning | provisioning.md |
| connect / SQL30082N / SQL1531N / DSN / CLP / Python / Java / CloudShell / airgap | connectivity | connectivity.md |
| SSL / TLS / GSKit / certificate / truststore / bundle.pem | connectivity-tls | connectivity-tls.md |
| Python driver / JDBC / laptop / multi-instance / db2_use | connection drivers | connection-drivers.md |
| migrate / DMS / Q Replication / IIDR / AIX / Windows / AS400 / precheck | migration | migration.md |
| z/OS / mainframe / ADB2GEN / schema conversion | mainframe-migration | mainframe-migration.md |
| code page / collation / CCSID / EBCDIC / UTF-8 / CODEUNITS32 / territory | code page & collation | code-page-collation.md |
| snapshot / backup / restore / rollforward / PiTR / S3 integration | backup-restore | backup-restore.md |
| Multi-AZ / standby replica / read replica / HADR / cross-region / failover | ha-dr | ha-dr.md |
| parameter group / RDSADMIN / scale / storage / CloudWatch / registry variable | operations | operations.md |
| BYOK / customer-managed KMS / bring your own key / imported key material / multi-region key | byok | byok-kms.md |
| Active Directory / Kerberos / domain join / self-managed AD / kinit / SPN / realm | ad-kerberos | ad-kerberos.md |
| audit / DB2_AUDIT / audit policy / audit to S3 / option group | db2-audit | db2-audit.md |
| minimum IAM / least privilege / IAM policy / trust policy / permissions | minimum-iam | minimum-iam.md |
| colocation / co-locate / EC2 app latency / ASG / ALB / failover routing | colocation | colocation.md |
Constraints:
The agent MUST read only the reference files that match the user's question, to keep the context focused.
The agent MUST NOT invent RDSADMIN procedure signatures, because wrong parameter order will fail at runtime — always cite the signature from the reference file.
The agent MUST cite the source blog URL when an answer is blog-sourced, so the user can verify specifics.
If a question crosses two sub-skills (e.g. "migrate z/OS with near-zero downtime", or "BYOK plus cross-region standby"), the agent SHOULD load each matching reference and combine them.
Execute Workflow
Once routed, give the user a concrete, runnable answer grounded in the reference file.
Parameter acquisition:
All required parameters (region, instance identifier, source/target ARNs, S3 bucket, prefix, the
--master-usernamevalue) MUST be collected upfront in a single message.Parameter formats MUST be specified: region
us-east-1-style; instance identifier^[a-zA-Z][a-zA-Z0-9-]{0,62}$; ARNarn:aws:rds:<region>:<account>:db:<name>; S3 bucket 3–63 chars lowercase.The agent MUST accept parameters via direct input, a JSON/YAML file path, or a URL.
Tool use:
Use AWS CLI for RDS operations (example:
aws rds create-db-instance-read-replica --db-instance-identifier <name> --source-db-instance-identifier <arn> --replica-mode mounted --region <dr-region>). Every operation is expressed in AWS CLI syntax so it runs whether or not the AWS MCP server is installed.Use bundled scripts — db2-driver.sh, db2client-configure.sh, db2client-airgap.sh, functions.sh — instead of rewriting install steps.
Write migration plans, upgrade plans, validation reports to a local
artifacts/<app-name>/directory created at runtime in the working directory (this is a run-time output location, not part of the shipped skill).
Constraints:
The agent MUST give exact CLI commands when behavior is deterministic, not descriptions like "enable Multi-AZ".
The agent MUST obtain AWS credentials through an IAM role or instance profile and MUST NOT prompt the user to paste credentials.
The agent MUST cite the source blog or documentation URL whenever the answer is sourced from published material, so the user can verify it.
The agent MUST write long-form artifacts to a local
artifacts/<app-name>/directory (created at runtime in the working directory) so the workspace is inspectable.When a requested action is unsupported on managed RDS for Db2, the agent MUST state the limitation plainly — no hedging like "limited support" or "with special config" — and offer a supported alternative (for example, unfenced C/COBOL stored procedures are not supported; rewrite them in Java via
sqlj.install_jar, or in SQL PL).The AWS MCP server is recommended but not required. When the MCP server is in use, prefer inline JSON strings over positional filesystem arguments with
call_aws; this is guidance for the MCP path only, not a requirement. Never treatcall_awsorrun_scriptas the only way to perform an operation — the AWS CLI command always works on its own.
Resource tagging (always apply on resource creation)
When creating any RDS for Db2 resource (create-db-instance, create-db-parameter-group, create-db-cluster for Multi-AZ deployments, create-db-instance-read-replica for standby replicas), ALWAYS include these tags using the RDS list-of-records --tags syntax:
--tags Key=created_by,Value=rds-db2-skill Key=generation_model,Value={your-model-id}
Example: --tags Key=created_by,Value=rds-db2-skill Key=generation_model,Value=claude-sonnet-4-20250514
The same convention applies to every resource this skill creates, including BYOK-encrypted instances (create-db-instance --storage-encrypted --kms-key-id ...), audit option groups (create-option-group), and customer-managed KMS keys (kms create-key, tagged with --tags TagKey=created_by,TagValue=rds-db2-skill TagKey=generation_model,TagValue={your-model-id} per the KMS tag syntax).
Include these tags even if the user does not mention tagging, so that they can identify the resources created via this skill. If the user provides additional tags, append these to their tags rather than replacing them. The same applies when tagging via add-tags-to-resource on existing resources.
RDS-managed facts the agent must always surface
These RDS-for-Db2-specific facts are what differentiates this skill from general IBM Db2 knowledge. General-Db2 answers typically omit the RDS-managed constraints (no unfenced C/COBOL, Secrets Manager rotation side effects, rdsadmin.* procedures) and the AWS-native migration tooling nuances (DMS z/OS limits, ADB2GEN vs SCT).
For "create cross-region standby replica for DR", you MUST tell the user ALL of the following six facts:
Use
aws rds create-db-instance-read-replicawith--replica-mode mountedand the cross-region source ARN — Db2 cross-region standby uses mounted replica mode, NOT transactional read-replica mode.Source prerequisite: automated backups enabled on the source instance (backup retention period > 0).
Target-region prerequisite: custom parameter group created in the target region before the command runs.
Target-region prerequisite: KMS key available in the target region (multi-region KMS key or a target-region customer-managed KMS key).
State prerequisites: all databases in
activestate, no pending reboots, no license-model restrictions blocking cross-region replicas.Explain the mounted-vs-transactional distinction — mounted replicas do not accept reads or SQL from applications; they exist purely as a DR standby that can be promoted. Do not suggest read offload use cases.
For "restore Db2 backup from S3 (multi-part, N files)", you MUST tell the user ALL of the following six facts — never omit any of the procedure names:
Attach IAM role with S3 access via
aws rds add-role-to-db-instanceusing--feature-name S3_INTEGRATION.Set restore performance parameters via
rdsadmin.set_configuration— tuneUSE_STREAMING_RESTORE,RESTORE_DATABASE_NUM_BUFFERS, andPARALLELISMbefore starting the restore.Call
rdsadmin.restore_databasewith five parameters in this exact order: database name, restore mode (OFFLINEorONLINE), S3 prefix, S3 bucket, and region. Multi-file (multi-part) backups are handled by the shared prefix — there is no separate multi-part flag parameter. (Signature:rdsadmin.restore_database(dbname, type, prefix, bucket, region).)For
ONLINErestore mode, follow up withrdsadmin.rollforward_databaseto replay archive logs, thenrdsadmin.complete_rollforwardto finish.OFFLINErestores do NOT need rollforward.Monitor progress with
rdsadmin.get_task_status— everyrdsadminprocedure returns a task ID you poll.Warn about VPC endpoint for S3 if no internet egress from the private subnet, and warn about Db2 version compatibility between the source backup and the RDS instance engine version (forward-compatible, not backward).
For "C/COBOL unfenced external stored procedures — lift and shift to RDS for Db2?", you MUST tell the user ALL of the following four facts:
Unfenced external stored procedures in C and COBOL are NOT supported on RDS for Db2. State this as an unqualified "not supported" — do not hedge with "limited support" or "with special config."
All routines on RDS for Db2 MUST be fenced. This is a managed-service architectural constraint, not a flag.
Java stored procedures are supported — install via
sqlj.install_jar. C/COBOL SPs should be rewritten in Java or SQL PL (Db2's procedural SQL, equivalent to Oracle's PL/SQL).Offer to help identify which SPs are unfenced and prioritize the rewrite by call frequency (hot code path first).
For "migrate Db2 for z/OS to RDS for Db2 with near-zero downtime", you MUST tell the user ALL of the following five facts:
For near-zero-downtime from z/OS, use Q Replication (IBM IIDR), Qlik Replicate, or Precisely — these are the CDC tools that support Db2 for z/OS as a source streaming to RDS for Db2.
AWS DMS supports FULL LOAD ONLY from Db2 for z/OS. DMS does NOT support CDC from z/OS sources. Use DMS for a one-time bulk load, not for near-zero-downtime cutover.
Use ADB2GEN for schema conversion from z/OS. AWS SCT does NOT support Db2 for z/OS as a source — this is a common trap. Do not recommend SCT for z/OS sources.
Code-page conversion (EBCDIC → UTF-8) is the primary migration risk. Plan explicit collation and code page mapping before cutover — silent data corruption is the failure mode.
Plan explicit collation selection on the target RDS instance to match the semantic ordering of the z/OS source.
For "SQL30082N — USERNAME AND/OR PASSWORD INVALID" with RDS-managed master user (user didn't change it), you MUST tell the user ALL of the following four facts:
SQL30082N after a previously-working connection almost always means the master password rotated in Secrets Manager. RDS for Db2 rotates the master password on the Secrets Manager schedule — clients using a cached password will start failing with SQL30082N even though nothing on their side changed.
Fix: run
db2_use <instance-id>(fromfunctions.sh/ the bundled helpers). This fetches the current password from Secrets Manager and rewrites~/.db2envwith the new value.Alternative:
db2_test_connectionto verify the helper's fix worked end-to-end.If
db2_useisn't installed, the user needs to pull the current password withaws secretsmanager get-secret-valueand update their local credential cache manually. Do not tell them to rotate the password — the password rotation is what caused the problem.
For "BYOK / customer-managed KMS key for RDS for Db2", you MUST tell the user ALL of the following six facts:
Use a multi-region KMS key with
--origin EXTERNALwhen importing your own key material, so the same key ID and material can replicate to a DR region.The creating principal needs
kms:CreateGrantandkms:DescribeKeyon the key, or instance creation fails.Encryption is set at instance creation with
--storage-encrypted --kms-key-id <alias|arn>. You cannot encrypt an existing unencrypted instance in place — go snapshot →copy-db-snapshot --kms-key-id→restore-db-instance-from-db-snapshot.For cross-region DR, replicate the multi-region key (
kms:ReplicateKey) into the DR region first, thencopy-db-snapshotacross regions with the replica key.Import tokens expire after 24 hours — if
import-key-materialfails on expiry, re-runget-parameters-for-importto get a fresh token and wrapping key.Cite blog DBBLOG-5188 and byok-kms.md; do not invent KMS parameter names.
For "self-managed Active Directory with Kerberos on RDS for Db2", you MUST tell the user ALL of the following six facts:
RDS joins your AD via
--domain-fqdn,--domain-ou,--domain-auth-secret-arn, and--domain-dns-ips— the self-managed AD path, with no AWS Managed Microsoft AD required.The Secrets Manager secret uses keys
SELF_MANAGED_ACTIVE_DIRECTORY_USERNAME(the sAMAccountName only — noDOMAIN\prefix, which fails creation) andSELF_MANAGED_ACTIVE_DIRECTORY_PASSWORD, encrypted by a dedicated KMS key, with a resource policy trustingrds.amazonaws.comguarded byaws:SourceArnandaws:SourceAccount(confused-deputy protection).Delegate the nine AD permissions to a dedicated service account scoped to one OU; grant
servicePrincipalNameread/write on User objects using ADSI Edit, not the ADUC delegation wizard (which filters that attribute out) — this is the most common failure.Open AD ports between RDS and the domain controllers: DNS 53, Kerberos 88 and 464, LDAP 389 and 3268, and the RPC range 49152–65535. Missing the RPC range is the top cause of intermittent join failures. Keep clock skew under 5 minutes.
The RDS master user is a local account that cannot get a Kerberos ticket. AD users need
kinitplus aGRANT CONNECT. Kerberos JDBC usessecurityMechanism=11and a region-specific PEM viasslCertLocation(neverglobal-bundle.pem).Cite the self-managed AD blog and ad-kerberos.md; verify with
describe-db-instances ... DomainMembershipsshowingStatus: joined.
Troubleshooting
| Error | Cause | Fix |
|---|---|---|
SQL30082N | Password rotated in Secrets Manager | Run db2_use <instance-id> — the helper re-fetches the current password and rewrites ~/.db2env. |
SQL1531N | DSN not yet in cache | db2 terminate to clear, then retry; if still failing, re-run db2client-configure.sh. |
SQL01013N / TCP timeout | Security group blocks 50000/50443 | Check SG inbound rules — add client's SG on TCP 50000 (plain) or 50443 (SSL). |
| GSKit / SSL certificate error | RDS cert bundle missing or RSA cert not first | Re-download <region>-bundle.pem from RDS truststore and re-run db2client-configure.sh. |
| Access denied on RDSADMIN call | IAM role missing S3_INTEGRATION feature | aws rds add-role-to-db-instance --feature-name S3_INTEGRATION --role-arn <role-arn> --db-instance-identifier <id>. |
| Restore fails with "database in rollforward pending" | ONLINE restore left DB in rollforward state | Call rdsadmin.rollforward_database for each archive log, then rdsadmin.complete_rollforward. |
| Standby replica creation fails | Missing prereqs | Verify: automated backups enabled, custom parameter group in DR region, KMS multi-region key, no pending rdsadmin tasks, all databases in active state. |
AD domain join Status not joined | RPC port range blocked, wrong secret format, or SPN attribute missing | Open RPC 49152–65535 between RDS and the DCs, confirm the secret username is the sAMAccountName with no DOMAIN\ prefix, and grant servicePrincipalName on User objects via ADSI Edit — see ad-kerberos.md. |
import-key-material fails — token expired | Import token older than 24 hours | Re-run get-parameters-for-import for a fresh token and wrapping key, re-wrap the material with openssl, then retry the import — see byok-kms.md. |
| Throttling from RDS API | Exceeded API request rate | Exponential backoff with jitter; batch operations; check Service Quotas. |
Security Considerations
Surface these controls when advising on any production RDS for Db2 deployment. They consolidate the security guidance that the sub-skill references cover in depth.
Encryption at rest and in transit — Always create instances with
--storage-encrypted; for key ownership and compliance use a customer-managed KMS key (BYOK), and for DR use a multi-region key. Enforce TLS on every connection (port 50443,<region>-bundle.pem); never connect in plaintext for production. See byok-kms.md and connectivity-tls.md. (Guideline 1)Least-privilege IAM — Use the scoped policy and trust policy in minimum-iam.md; never attach a
*FullAccessmanaged policy. Scopeiam:PassRoleand ARN-pattern every mutating statement that supports resource-level permissions. (Guideline 5)Network isolation — Keep instances in private subnets, restrict security groups to the application/source SG (never
0.0.0.0/0), and use VPC endpoints for S3/SSM/Secrets Manager so traffic stays off the public internet. See colocation.md. (Guideline 5)Audit logging and monitoring — Enable Db2 audit to S3 (db2-audit.md), RDS Enhanced Monitoring, and CloudTrail for RDS/KMS/Secrets Manager API calls. Alarm on failed logins and configuration changes. (Guideline 12)
Secret rotation — Provision with
--manage-master-user-passwordso RDS stores and rotates the master password in Secrets Manager; never embed plaintext passwords. After rotation, refresh clients withdb2_use <instance-id>. (Guideline 13)Backup encryption and retention — Set a backup retention period, encrypt automated and manual snapshots with your KMS key, and apply S3 bucket encryption plus lifecycle/retention to any Db2 audit or backup buckets. (Guideline 13)
Additional Resources
In-scope documentation and blogs
AWS docs — RDS for Db2: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_RDSDb2.html
AWS docs — RDS for Db2 IAM permissions: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAM.html
AWS docs — Kerberos authentication for RDS for Db2: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/db2-kerberos.html
Blog — Connect to RDS for Db2 from CloudShell: https://aws.amazon.com/blogs/database/connect-to-amazon-rds-for-db2-using-aws-cloudshell/
Blog — Restore self-managed Db2 Linux into RDS for Db2: https://aws.amazon.com/blogs/database/restore-self-managed-db2-linux-databases-in-amazon-rds-for-db2/
Blog — Near-zero downtime from AIX/Windows to RDS for Db2 with Q Replication: https://aws.amazon.com/blogs/database/near-zero-downtime-migrations-from-self-managed-db2-on-aix-or-windows-to-amazon-rds-for-db2-using-ibm-q-replication/
Blog — Cross-region standby replicas: https://aws.amazon.com/blogs/database/configure-amazon-rds-for-db2-standby-replicas-for-high-availability-and-faster-disaster-recovery/
Blog — Mainframe DDL conversion (z/OS to RDS for Db2): https://aws.amazon.com/blogs/database/migrating-tables-from-ibm-db2-for-z-os-to-amazon-rds-for-db2/
Blog — Code page and collation for mainframe migration: https://aws.amazon.com/blogs/database/choosing-the-right-code-page-and-collation-for-migration-from-mainframe-db2-to-amazon-rds-for-db2/
Blog — Bring your own customer-managed KMS key for RDS for Db2 (DBBLOG-5188): https://aws.amazon.com/blogs/database/bring-your-own-key-to-amazon-rds-for-db2-with-a-customer-managed-kms-key/
Blog — Self-managed Active Directory with Kerberos for RDS for Db2: https://aws.amazon.com/blogs/database/use-kerberos-authentication-with-a-self-managed-active-directory-for-amazon-rds-for-db2/
Related topics (cited resources, not yet routed sub-skills)
These adjacent topics are not expanded into routed references in this iteration. Each is discoverable through the cited resource below.
Reverse log shipping for RDS for Db2 (DBBLOG-5352): https://aws.amazon.com/blogs/database/implement-reverse-log-shipping-for-amazon-rds-for-db2/
Multi-account connectivity: workspace source
04-db2-client/RDS-Db2-Multiple-Account-Connectivity/Terraform provisioning: workspace source
04-db2-client/RDS-Db2-Terraform/CIS compliance: workspace source
04-db2-client/CIS-Compliance/db2mon monitoring: workspace source
04-db2-client/db2mon_RDS/Compression savings: workspace source
04-db2-client/Compression-Savings/Migration prerequisite check (DBBLOG-5048): https://aws.amazon.com/blogs/database/migrate-from-ibm-db2-to-amazon-rds-for-db2-using-a-migration-prerequisite-check/
Load from S3: workspace source
04-db2-client/load-from-s3/Sample Java stored procedures: workspace source
04-db2-client/sample-java-sp/
Blog catalog
The authoritative list of published RDS for Db2 blogs and sample tools is maintained at https://github.com/aws-samples/sample-rds-db2-tools/tree/main — consult it for the current set of blog articles and companion code.
Related skill (migrating off Db2 LUW to PostgreSQL):
rds-postgres-migration(if present in corpus).
Handoff from aws-database-selection
This skill can be invoked directly, or it can be entered from the aws-database-selection parent skill after that skill has run a requirements interview and produced a requirements.json artifact. When you see a backtick-wrapped path matching aws_dbs_requirements/*/requirements.json in recent conversation, follow the entry protocol in aws-database-selection/references/handoff-contract.md:
Read the artifact using
file_read.Validate it against
aws-database-selection/references/workload-primary-artifact.schema.json. If malformed or unreadable, tell the user and proceed without it.Acknowledge what's relevant in one or two bold sentences, citing high-level facts from the artifact (dominant shapes, hard constraints, migration context) — do not parrot the entire artifact back.
Scope-check: this skill is scoped to Amazon RDS for Db2 — migrations from Db2 z/OS or LUW, HADR, standby replicas, SQL PL routines, Q Replication cutovers. If the artifact's
workload_primaries.dominant_shapesormigration_contextdon't match that scope, emit weak backpressure per the handoff contract: suggestamazon-aurorafor refactor-to-PostgreSQL from Db2, or go back toaws-database-selectionif Db2 isn't the source, then ask the user whether to go back or proceed anyway. Do not silently misuse the artifact.Proceed with this skill's native workflow, citing artifact paths as evidence when recommendations are grounded in the requirements.
The curated RDS-for-Db2 selection facts that the parent aws-database-selection skill consumes live at assets/selection-knowledge-input.json (with a human-readable companion at assets/selection-knowledge-input.md). These capture the in-scope source-migration scenarios, hard constraints, HA/DR options, and security areas in a structured, reusable form — read them when you need the curated selection view rather than re-deriving it.
All user-facing output from this skill follows the markdown-primitives-only formatting convention in the handoff contract: bold labels, backticks for paths and enum values, bullet lists for alternatives, no ASCII art or box-drawing characters.
Files
- ATTRIBUTION.mdAdded by AutoGineer902 B
- LICENSELicence file added by AutoGineer9.9 KiB
- NOTICELicence file added by AutoGineer67 B
- SKILL.md27.0 KiB
- assets/README.md963 B
- assets/rds-db2-minimal-iam-policy.json9.0 KiB
- assets/rds-db2-trust-policy.json317 B
- assets/selection-knowledge-input.json1.3 KiB
- assets/selection-knowledge-input.md2.4 KiB
- references/ad-kerberos.md6.4 KiB
- references/backup-restore.md6.4 KiB
- references/byok-kms.md6.7 KiB
- references/code-page-collation.md6.2 KiB
- references/colocation.md7.3 KiB
- references/connection-drivers.md4.3 KiB
- references/connectivity-tls.md3.1 KiB
- references/connectivity.md8.6 KiB
- references/db2-audit.md6.5 KiB
- references/ha-dr.md5.2 KiB
- references/mainframe-migration.md5.2 KiB
- references/migration.md7.8 KiB
- references/minimum-iam.md7.0 KiB
- references/operations.md7.2 KiB
- references/provisioning.md7.1 KiB
- scripts/Db2KerberosConnection.javaScript8.6 KiB
- scripts/Db2SslTest.javaScript6.3 KiB
- scripts/create-db2-audit-role.shScript4.5 KiB
- scripts/db2-driver.shScript19.8 KiB
- scripts/db2-kerberos-test.shScript10.6 KiB
- scripts/db2client-airgap.shScript14.1 KiB
- scripts/db2client-configure.shScript38.5 KiB
- scripts/functions.shScript18.6 KiB
scripts/functions.sh
#!/bin/bash
# =============================================================================
# functions.sh — DB2 helper functions for RDS DB2 RT client
# =============================================================================
# Source this file as db2inst1 to get all helper functions:
# source ~/functions.sh
#
# Quick start:
# db2_use # select instance, fetch credentials
# db2_connect # connect using stored credentials
# db2_test_connection # diagnose connection problems
# =============================================================================
# Guard against double-loading
[ -n "${_DB2_FUNCTIONS_LOADED:-}" ] && return 0
_DB2_FUNCTIONS_LOADED=1
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
BLUE='\033[0;34m'; CYAN='\033[0;36m'; NC='\033[0m'
log_info() { echo -e "${BLUE}[ INFO]${NC} $(date '+%H:%M:%S') - $1" >&2; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $(date '+%H:%M:%S') - $1" >&2; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $(date '+%H:%M:%S') - $1" >&2; }
log_error() { echo -e "${RED}[ ERROR]${NC} $(date '+%H:%M:%S') - $1" >&2; }
log_debug() { [[ "${VERBOSE:-}" == "true" ]] && echo -e "${CYAN}[ DEBUG]${NC} $(date '+%H:%M:%S') - $1" >&2 || true; }
DB2_ENV_FILE="${HOME}/.db2env"
# =============================================================================
# Credentials
# =============================================================================
set_credentials() {
if curl -s --connect-timeout 1 http://127.0.0.1:1338/latest/meta-data/ >/dev/null 2>&1; then
log_info "Detected AWS CloudShell environment"
local token creds
token=$(curl -sX PUT "http://127.0.0.1:1338/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
creds=$(curl -s -H "Authorization: $token" "http://127.0.0.1:1338/latest/meta-data/container/security-credentials")
export AWS_ACCESS_KEY_ID=$(echo "$creds" | jq -r .AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo "$creds" | jq -r .SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo "$creds" | jq -r .Token)
return
fi
if curl -s --connect-timeout 1 http://169.254.169.254/latest/meta-data/ >/dev/null 2>&1; then
log_info "Detected EC2 environment"
local token role creds
token=$(curl -sX PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
role=$(curl -s -H "X-aws-ec2-metadata-token: $token" http://169.254.169.254/latest/meta-data/iam/security-credentials/)
creds=$(curl -s -H "X-aws-ec2-metadata-token: $token" "http://169.254.169.254/latest/meta-data/iam/security-credentials/$role")
export AWS_ACCESS_KEY_ID=$(echo "$creds" | jq -r .AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo "$creds" | jq -r .SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo "$creds" | jq -r .Token)
return
fi
}
# =============================================================================
# Region detection
# =============================================================================
detect_region() {
[ -n "${REGION:-}" ] && return 0
[ -n "${AWS_DEFAULT_REGION:-}" ] && export REGION="$AWS_DEFAULT_REGION" && return 0
if curl -s --connect-timeout 1 http://169.254.169.254/latest/meta-data/ >/dev/null 2>&1; then
local token
token=$(curl -sX PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
REGION=$(curl -s -H "X-aws-ec2-metadata-token: $token" \
http://169.254.169.254/latest/meta-data/placement/region 2>/dev/null)
[ -n "$REGION" ] && export REGION && return 0
fi
REGION=$(aws configure get region 2>/dev/null)
[ -n "$REGION" ] && export REGION && return 0
log_error "Cannot detect region. Set: export REGION=us-east-1"
return 1
}
# =============================================================================
# Persistent env file — ~/.db2env
# =============================================================================
# Save current instance credentials to ~/.db2env
# WARNING: ~/.db2env contains the master password. It is written `chmod 600`
# (owner-only), but it MUST NEVER be (1) committed to version control,
# (2) shared with others, (3) backed up to unencrypted storage, or (4) used in
# production AWS environments. For production, obtain credentials from Secrets
# Manager via an IAM role (provision with --manage-master-user-password).
# Uses printf %q to safely escape special characters in the password
# (e.g. $, >, &, !) that would be re-expanded or misinterpreted by the
# shell when the file is sourced later.
db2_save_env() {
{
echo "export REGION=$(printf '%q' "${REGION:-}")"
echo "export DB_INSTANCE_ID=$(printf '%q' "${DB_INSTANCE_ID:-}")"
echo "export DB_DSN=$(printf '%q' "${DB_DSN:-}")"
echo "export MASTER_USER_NAME=$(printf '%q' "${MASTER_USER_NAME:-}")"
echo "export MASTER_USER_PASSWORD=$(printf '%q' "${MASTER_USER_PASSWORD:-}")"
} > "$DB2_ENV_FILE"
chmod 600 "$DB2_ENV_FILE"
log_success "Credentials saved to $DB2_ENV_FILE"
}
# Load credentials from ~/.db2env
db2_load_env() {
if [ ! -f "$DB2_ENV_FILE" ]; then
log_warning "$DB2_ENV_FILE not found — run db2_use first"
return 1
fi
source "$DB2_ENV_FILE"
log_success "Loaded: instance=$DB_INSTANCE_ID dsn=$DB_DSN user=$MASTER_USER_NAME"
}
# Show current active instance/credentials
db2_show_env() {
echo " REGION : ${REGION:-<not set>}"
echo " DB_INSTANCE_ID : ${DB_INSTANCE_ID:-<not set>}"
echo " DB_DSN : ${DB_DSN:-<not set>}"
echo " DB_SSL_DSN : ${DB_SSL_DSN:-<not set>}"
echo " MASTER_USER_NAME : ${MASTER_USER_NAME:-<not set>}"
echo " MASTER_USER_PASSWORD: ${MASTER_USER_PASSWORD:+<set>}${MASTER_USER_PASSWORD:-<not set>}"
}
# Switch active instance — fetches fresh password, rewrites ~/.db2env
# Usage: db2_use [instance-id]
db2_use() {
local registry="$HOME/.db2instances"
if [ ! -f "$registry" ]; then
log_error "No instance registry found. Run db2client-configure.sh first."
return 1
fi
# List available instances from registry
local instances
mapfile -t instances < <(cut -d'|' -f1 "$registry")
if [ ${#instances[@]} -eq 0 ]; then
log_error "No instances in registry. Run db2client-configure.sh first."
return 1
fi
local selected
if [ -n "${1:-}" ]; then
# Validate provided instance exists in registry
if ! grep -q "^${1}|" "$registry"; then
log_error "Instance '$1' not found in registry. Available:"
cut -d'|' -f1 "$registry" | while read -r i; do echo " $i" >&2; done
return 1
fi
selected="$1"
elif [ ${#instances[@]} -eq 1 ]; then
selected="${instances[0]}"
log_info "Auto-selected: $selected"
else
echo "Available DB2 instances:" >&2
for i in "${!instances[@]}"; do
local marker=""; [ "${instances[$i]}" = "${DB_INSTANCE_ID:-}" ] && marker=" (active)"
echo " $((i+1)). ${instances[$i]}${marker}" >&2
done
local choice
while true; do
read -p "Select instance (1-${#instances[@]}): " choice
[[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= ${#instances[@]} )) && break
log_warning "Invalid choice"
done
selected="${instances[$((choice-1))]}"
fi
# Parse registry entry: instance|master_user|tcp_dsn|ssl_dsn|krb_dsn|region
# (db2client-configure.sh writes 6 pipe-delimited fields; read all 6 so the
# trailing `region` is not corrupted by the krb_dsn field.)
local entry master_user tcp_dsn ssl_dsn krb_dsn region
entry=$(grep "^${selected}|" "$registry")
IFS='|' read -r _ master_user tcp_dsn ssl_dsn krb_dsn region <<< "$entry"
detect_region || true
[ -n "$region" ] && export REGION="$region"
set_credentials
# Fetch password — Secrets Manager → ~/.need_password → prompt
local secret_arn secret_json password
secret_arn=$(aws rds describe-db-instances \
--db-instance-identifier "$selected" \
--region "$REGION" \
--query "DBInstances[0].MasterUserSecret.SecretArn" \
--output text 2>/dev/null)
if [ -n "$secret_arn" ] && [ "$secret_arn" != "None" ]; then
secret_json=$(aws secretsmanager get-secret-value \
--secret-id "$secret_arn" --region "$REGION" \
--query "SecretString" --output text 2>/dev/null)
password=$(jq -r '.password' <<< "$secret_json")
[ -n "$password" ] && log_success "Password fetched from Secrets Manager"
fi
if [ -z "${password:-}" ]; then
# ~/.need_password is a DEVELOPMENT/TEST-ONLY fallback for instances not
# using Secrets Manager. It MUST be kept private (`chmod 600`), MUST NEVER be
# committed to version control, and MUST NEVER be shared or deployed to
# production. For production, provision with --manage-master-user-password so
# RDS stores and rotates the credential in Secrets Manager, and do not keep
# plaintext passwords on disk.
local file_password
file_password=$(grep "^${selected} " "$HOME/.need_password" 2>/dev/null | cut -d' ' -f2-)
if [ -n "$file_password" ] && [ "$file_password" != "replace this with the master user password" ]; then
password="$file_password"
log_warning "Password loaded from ~/.need_password (dev/test only — use --manage-master-user-password in production)"
fi
fi
if [ -z "${password:-}" ]; then
read -rsp "Password for ${master_user}@${selected}: " password; echo
fi
export DB_INSTANCE_ID="$selected"
export MASTER_USER_NAME="$master_user"
export MASTER_USER_PASSWORD="$password"
export DB_DSN="$tcp_dsn"
export DB_SSL_DSN="$ssl_dsn"
# Write ~/.db2env with printf %q so special chars ($, >, &, !) in the
# password are shell-escaped and survive being sourced later.
{
echo "export REGION=$(printf '%q' "$REGION")"
echo "export DB_INSTANCE_ID=$(printf '%q' "$selected")"
echo "export DB_DSN=$(printf '%q' "$tcp_dsn")"
echo "export DB_SSL_DSN=$(printf '%q' "$ssl_dsn")"
echo "export MASTER_USER_NAME=$(printf '%q' "$master_user")"
echo "export MASTER_USER_PASSWORD=$(printf '%q' "$password")"
} > "$DB2_ENV_FILE"
chmod 600 "$DB2_ENV_FILE"
log_success "Active instance: $selected | TCP: $tcp_dsn | SSL: $ssl_dsn"
log_info "Connect: db2 \"connect to $tcp_dsn user $master_user using '\$MASTER_USER_PASSWORD'\""
[ -n "$ssl_dsn" ] && \
log_info "SSL: db2 \"connect to $ssl_dsn user $master_user using '\$MASTER_USER_PASSWORD'\""
}
# Connect to a DSN — uses stored credentials, optional DSN override
# Usage: db2_connect [DSN]
db2_connect() {
local dsn="${1:-${DB_DSN:-${DB_SSL_DSN:-RDSADMIN}}}"
if [ -z "${MASTER_USER_NAME:-}" ] || [ -z "${MASTER_USER_PASSWORD:-}" ]; then
if [ -f "$DB2_ENV_FILE" ]; then
source "$DB2_ENV_FILE"
else
log_error "No credentials loaded. Run db2_use first."
return 1
fi
fi
# Escape single quotes in password for Db2 CLP: Db2 uses '' inside a
# single-quoted string to represent a literal single quote.
local _db2pw="${MASTER_USER_PASSWORD//\'/\'\'}"
log_info "Connecting to $dsn as $MASTER_USER_NAME ..."
db2 "connect to $dsn user $MASTER_USER_NAME using '$_db2pw'"
}
# Disconnect
db2_disconnect() {
db2 connect reset
db2 terminate
}
# =============================================================================
# Connection diagnostics
# =============================================================================
db2_test_connection() {
local dsn="${1:-${DB_DSN:-${DB_SSL_DSN:-RDSADMIN}}}"
if [ -z "${MASTER_USER_NAME:-}" ] || [ -z "${MASTER_USER_PASSWORD:-}" ]; then
[ -f "$DB2_ENV_FILE" ] && source "$DB2_ENV_FILE"
fi
echo "============================================================================"
echo " DB2 Connection Diagnostics"
echo " DSN : $dsn"
echo " User : ${MASTER_USER_NAME:-<not set>}"
echo " Password : ${MASTER_USER_PASSWORD:+<set>}${MASTER_USER_PASSWORD:-<not set>}"
echo " DB_INSTANCE_ID : ${DB_INSTANCE_ID:-<not set>}"
echo "============================================================================"
# 1. Check DSN exists in db2dsdriver.cfg
if db2cli validate -dsn "$dsn" 2>&1 | grep -q "not found\|invalid"; then
log_error "DSN '$dsn' not found in db2dsdriver.cfg"
log_info "Run: db2cli writecfg list — to see configured DSNs"
log_info "Run: BUCKET=... REGION=... source ~/db2client-configure.sh — to reconfigure"
return 1
fi
log_success "DSN '$dsn' found in db2dsdriver.cfg"
# 2. Extract host/port from DSN and test TCP reachability
local host port
host=$(db2cli validate -dsn "$dsn" 2>/dev/null | grep -i "hostname" | awk '{print $NF}')
port=$(db2cli validate -dsn "$dsn" 2>/dev/null | grep -i "port" | awk '{print $NF}')
if [ -n "$host" ] && [ -n "$port" ]; then
log_info "Testing TCP connectivity to $host:$port ..."
if timeout 5 bash -c "echo >/dev/tcp/$host/$port" 2>/dev/null; then
log_success "TCP connection to $host:$port OK"
else
log_error "Cannot reach $host:$port — check security group / VPC routing"
return 1
fi
fi
# 3. Attempt DB2 connect and capture error
log_info "Attempting db2 connect to $dsn ..."
local out rc _db2pw
_db2pw="${MASTER_USER_PASSWORD//\'/\'\'}"
out=$(db2 "connect to $dsn user $MASTER_USER_NAME using '$_db2pw'" 2>&1)
rc=$?
if [ $rc -eq 0 ]; then
log_success "Connection successful"
db2 connect reset >/dev/null 2>&1
return 0
fi
# Diagnose common error codes
log_error "Connection failed (rc=$rc)"
echo "$out" >&2
if echo "$out" | grep -q "SQL30082N"; then
log_error "Authentication failed — wrong username or password"
log_info "Check: MASTER_USER_NAME=$MASTER_USER_NAME"
log_info "Run db2_use to refresh credentials"
elif echo "$out" | grep -q "SQL08001N\|SQL30061N"; then
log_error "Database not found — DSN may point to wrong database name"
log_info "Run: BUCKET=... REGION=... source ~/db2client-configure.sh — to reconfigure DSNs"
elif echo "$out" | grep -q "SQL01013N\|TCP"; then
log_error "Network error — cannot reach DB2 server"
log_info "Check security group allows port $port from this host"
elif echo "$out" | grep -q "GSKit\|SSL\|certificate"; then
log_error "SSL certificate error"
log_info "Check: ls -la ~/$REGION-bundle.pem"
log_info "Run: BUCKET=... REGION=... source ~/db2client-configure.sh — to re-download cert"
fi
return 1
}
# List all configured DSNs
db2_list_dsns() {
log_info "Configured DSNs in db2dsdriver.cfg:"
db2cli validate -dsn 2>/dev/null | grep -i "data source\|dsn" || \
cat "$HOME/sqllib/cfg/db2dsdriver.cfg" 2>/dev/null || \
log_warning "No DSNs found"
}
# =============================================================================
# RDS task monitoring (uses stored credentials)
# =============================================================================
get_task_status() {
db2_connect RDSADMIN || return 1
db2 "SELECT VARCHAR(task_type,25) AS task_type,
VARCHAR(lifecycle,15) AS lifecycle,
created_at,
completed_work_bytes
FROM TABLE(rdsadmin.get_task_status(null,null,null)) AS r
ORDER BY created_at DESC"
db2_disconnect
}
get_task_elapsed() {
db2_connect RDSADMIN || return 1
db2 "SELECT task_id,
VARCHAR(task_type,25) AS task_type,
VARCHAR(lifecycle,15) AS lifecycle,
NVL(TIMESTAMPDIFF(2, (last_updated_at - created_at)),-1) AS elapsed_seconds
FROM TABLE(rdsadmin.get_task_status(null,null,null)) AS r
ORDER BY created_at DESC"
db2_disconnect
}
get_task_output() {
db2_connect RDSADMIN || return 1
db2 "SELECT VARCHAR(r.task_type,25) AS task_type,
VARCHAR(r.lifecycle,15) AS lifecycle,
r.created_at,
r.completed_work_bytes,
VARCHAR(bson_to_json(task_input_params),256) AS input_params,
VARCHAR(r.task_output,1024) AS task_output
FROM TABLE(rdsadmin.get_task_status(null,null,null)) AS r
ORDER BY created_at DESC
LIMIT 1"
db2_disconnect
}
# =============================================================================
# RDS instance monitoring
# =============================================================================
monitor_db_instance_creation() {
[ -z "${DB_INSTANCE_ID:-}" ] && log_error "DB_INSTANCE_ID not set. Run db2_use first." && return 1
detect_region || return 1
log_info "Monitoring RDS instance '$DB_INSTANCE_ID' ..."
local status=""
while [ "$status" != "available" ]; do
status=$(aws rds describe-db-instances \
--db-instance-identifier "$DB_INSTANCE_ID" \
--region "$REGION" \
--query "DBInstances[0].DBInstanceStatus" \
--output text 2>/dev/null)
if [ "$status" = "available" ]; then
log_success "Instance '$DB_INSTANCE_ID' is available"
else
log_info "$(date '+%H:%M:%S') status: $status — waiting 30s ..."
sleep 30
fi
done
}
# =============================================================================
# Help
# =============================================================================
db2_help() {
echo
echo " DB2 Helper Functions (source ~/functions.sh to load)"
echo " ======================================================"
echo
echo " Setup"
echo " db2_use [instance-id] Switch active instance — fetches fresh password, rewrites ~/.db2env"
echo " db2_load_env Load saved credentials from ~/.db2env"
echo " db2_save_env Save current credentials to ~/.db2env"
echo " db2_show_env Show current instance/credentials in use"
echo
echo " Connection"
echo " db2_connect [DSN] Connect using stored credentials (default DSN: RDSADMIN)"
echo " db2_disconnect Reset and terminate current connection"
echo " db2_list_dsns List all configured DSNs from db2dsdriver.cfg"
echo
echo " Diagnostics"
echo " db2_test_connection [DSN] Test connectivity — checks DSN, TCP, auth, SSL"
echo
echo " RDS Tasks"
echo " get_task_status Show RDS task status (connects to RDSADMIN)"
echo " get_task_elapsed Show RDS task elapsed time"
echo " get_task_output Show latest task output, input params, and lifecycle"
echo " monitor_db_instance_creation Poll instance status until available"
echo
echo " Quick start"
echo " db2_use # select instance and fetch credentials"
echo " db2_connect # connect using saved credentials"
echo " db2_test_connection # if connection fails, run this to diagnose"
echo
}
# =============================================================================
# Auto-load ~/.db2env if it exists (silent)
# =============================================================================
[ -f "$DB2_ENV_FILE" ] && source "$DB2_ENV_FILE" 2>/dev/null || true
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an MCP server
Security
What our scanner noticed· Medium risk
- Instructions that use the network
- Downloads piped into a shell
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- AWS
- Publisher
- AWS (Official)
- Source
- aws/agent-toolkit-for-aws · skills/specialized-skills/database-skills/rds-db2 · commit 0a218f8
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- NOTICE (added by AutoGineer from NOTICE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by AWS or AWS.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download rds-db2.zip