I Tried Connecting from the dbt platform to Amazon Redshift Serverless Using IAM Authentication

I Tried Connecting from the dbt platform to Amazon Redshift Serverless Using IAM Authentication

This article explains how to connect dbt platform to Amazon Redshift Serverless by combining IAM authentication with an SSH tunnel, using different IAM users for development and production environments.
2026.11.24

This page has been translated by machine translation. View original

Introduction

When connecting from the dbt platform to Amazon Redshift, you can authenticate with a username and password, but then you have to manage a long-lived password. With IAM authentication, you can connect with an IAM user's access key without using a database password.

This article summarizes what I tried: connecting from the dbt platform to Amazon Redshift Serverless under the following conditions.

  • Use IAM authentication
  • Use separate IAM users for the development and production environments
  • Place Redshift Serverless in a private subnet and connect through an SSH tunnel via a bastion EC2 instance

Redshift authentication methods available in the dbt platform

The dbt platform's Redshift connection is described in the following documentation.

https://docs.getdbt.com/docs/platform/connect-data-platform/connect-redshift?version=2

According to the documentation, the authentication methods available in the dbt platform are as follows.

Method Development Production Notes
Username and password ○ ○ Can be selected on the connection settings screen
IAM user authentication ○ ○ Can only be set via extended attributes
External OAuth (AWS IAM Identity Center) ○ Not documented Development connections only. Targets Okta or Entra ID, and requires the Enterprise plan or higher

Note that browser_identity_center (IAM Identity Center authentication via the browser), which is available when running dbt Core locally, is not yet supported in the dbt platform.

https://docs.getdbt.com/docs/local/connect-data-platform/redshift-setup?version=2

IAM user authentication has no input fields on the connection settings screen; you configure it with extended attributes. Extended attributes let you override part of the connection settings by writing a fragment of profiles.yml in YAML.

https://docs.getdbt.com/docs/dbt-platform-environments?version=2#extended-attributes

IAM authentication for Redshift Serverless

With IAM authentication for Redshift Serverless, the IAM user's access key is used to call redshift-serverless:GetCredentials, which returns temporary credentials used to connect. The username on the Redshift side is IAM:<IAM user name>.

Authorization is determined by the privileges GRANTed to this Redshift user. Therefore, the IAM policy only needs to allow GetCredentials.

Benefits and caveats of IAM authentication

Even with IAM authentication, you must register the IAM user's access key in the dbt platform. The credential you manage changes from a database password to an access key.

Still, compared with using a database password, I think it has the following benefits.

Aspect Database password IAM authentication
Revocation Change the password and apply it to every integration using it Just disable the key in the IAM console
Checking usage Check the database-side logs GetCredentials calls are recorded in CloudTrail. The key's last-used time can also be checked in IAM
Credentials at connection Uses a fixed password Obtains short-lived temporary credentials on each connection
Rotation Change the password manually Each user can have up to two keys, so you can update while switching between old and new
Permission management Only inside the database Authentication is handled by IAM and authorization by Redshift. IAM policies can restrict which Workgroups can be connected to

As a way to avoid access keys altogether, there is the external OAuth mentioned earlier. However, it applies only to the development environment.

Architecture

I verified with the configuration in the diagram below.

The features are as follows.

Item Details
Network VPC, 1 public subnet, 3 private subnets (for Redshift Serverless)
Bastion Amazon Linux 2023 t3.micro with an Elastic IP
Bastion SSH Allows only the dbt platform's source IPs
My own connection Uses SSM Session Manager port forwarding, so my own IP is not allowed
IAM users Two: one for development and one for production
Output schema Development uses the Schema in the dbt user's Development credentials (here dbt_tyasuhara); production uses analytics

IAM users and Redshift users correspond one to one. Therefore, by separating IAM users for development and production, you can also set separate permissions on the Redshift side.

Trying it out

Prerequisites

  • An environment where the AWS CLI, the Session Manager plugin, and psql are available
  • dbt platform

https://docs.getdbt.com/docs/cloud/about-cloud/access-regions-ip-addresses

Preparation

Set the variables used in the following steps. For <dbt の IP>, enter the source IPs you confirmed in the documentation above. This template accepts up to 6.

export AWS_REGION=ap-northeast-1
export PROJECT=dbt-rs-ssh

export DBT_CIDR1="<dbt の IP 1>/32"
export DBT_CIDR2="<dbt の IP 2>/32"
export DBT_CIDR3="<dbt の IP 3>/32"
export DBT_CIDR4="<dbt の IP 4>/32"
export DBT_CIDR5="<dbt の IP 5>/32"
export DBT_CIDR6="<dbt の IP 6>/32"

1. Create AWS resources with CloudFormation

Create the AWS resources with the following four templates.

Stack Template Resources created
${PROJECT}-network 01-network.yml VPC, subnets, IGW, route tables, security groups
${PROJECT}-redshift 02-redshift-serverless.yml Redshift Serverless Namespace and Workgroup
${PROJECT}-bastion 03-bastion.yml Bastion EC2, Elastic IP, IAM role for SSM
${PROJECT}-iam 04-iam-users.yml IAM users for development and production, policy allowing GetCredentials

01-network.yml

This creates a VPC, 1 public subnet, and 3 private subnets. A Redshift Serverless Workgroup requires subnets in multiple AZs, so I prepared three private subnets.

The bastion's security group allows only port 22 from the dbt platform's source IPs. The Redshift security group allows only port 5439 from the bastion.

01-network.yml
AWSTemplateFormatVersion: '2010-09-09'
Description: dbt platform SSH tunnel lab - 01 network (VPC, subnets, security groups)

Parameters:
  ProjectName:
    Type: String
    Default: dbt-rs-ssh
    Description: Prefix for resource names and export names
  VpcCidr:
    Type: String
    Default: 10.0.0.0/16
    Description: Must be a /16 (subnets are derived as /24)
  DbtCidr1:
    Type: String
    AllowedPattern: '^(\d{1,3}\.){3}\d{1,3}/\d{1,2}$'
    Description: dbt platform egress IP (CIDR). Check the dbt docs for your region
  DbtCidr2:
    Type: String
    Default: ''
    AllowedPattern: '^$|^(\d{1,3}\.){3}\d{1,3}/\d{1,2}$'
  DbtCidr3:
    Type: String
    Default: ''
    AllowedPattern: '^$|^(\d{1,3}\.){3}\d{1,3}/\d{1,2}$'
  DbtCidr4:
    Type: String
    Default: ''
    AllowedPattern: '^$|^(\d{1,3}\.){3}\d{1,3}/\d{1,2}$'
  DbtCidr5:
    Type: String
    Default: ''
    AllowedPattern: '^$|^(\d{1,3}\.){3}\d{1,3}/\d{1,2}$'
  DbtCidr6:
    Type: String
    Default: ''
    AllowedPattern: '^$|^(\d{1,3}\.){3}\d{1,3}/\d{1,2}$'

Conditions:
  HasDbtCidr2: !Not [!Equals [!Ref DbtCidr2, '']]
  HasDbtCidr3: !Not [!Equals [!Ref DbtCidr3, '']]
  HasDbtCidr4: !Not [!Equals [!Ref DbtCidr4, '']]
  HasDbtCidr5: !Not [!Equals [!Ref DbtCidr5, '']]
  HasDbtCidr6: !Not [!Equals [!Ref DbtCidr6, '']]

Resources:
  Vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !Ref VpcCidr
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: !Sub '${ProjectName}-vpc'

  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: !Sub '${ProjectName}-igw'

  InternetGatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref Vpc
      InternetGatewayId: !Ref InternetGateway

  # Public subnet (bastion)
  PublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      AvailabilityZone: !Select [0, !GetAZs '']
      CidrBlock: !Select [0, !Cidr [!Ref VpcCidr, 8, 8]]
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: !Sub '${ProjectName}-public-1'

  # Private subnets (Redshift Serverless, 3 AZs)
  PrivateSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      AvailabilityZone: !Select [0, !GetAZs '']
      CidrBlock: !Select [1, !Cidr [!Ref VpcCidr, 8, 8]]
      Tags:
        - Key: Name
          Value: !Sub '${ProjectName}-private-1'

  PrivateSubnet2:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      AvailabilityZone: !Select [1, !GetAZs '']
      CidrBlock: !Select [2, !Cidr [!Ref VpcCidr, 8, 8]]
      Tags:
        - Key: Name
          Value: !Sub '${ProjectName}-private-2'

  PrivateSubnet3:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      AvailabilityZone: !Select [2, !GetAZs '']
      CidrBlock: !Select [3, !Cidr [!Ref VpcCidr, 8, 8]]
      Tags:
        - Key: Name
          Value: !Sub '${ProjectName}-private-3'

  PublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref Vpc
      Tags:
        - Key: Name
          Value: !Sub '${ProjectName}-public-rt'

  PublicDefaultRoute:
    Type: AWS::EC2::Route
    DependsOn: InternetGatewayAttachment
    Properties:
      RouteTableId: !Ref PublicRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway

  PublicSubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet
      RouteTableId: !Ref PublicRouteTable

  # Private route table (no NAT / no internet route)
  PrivateRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref Vpc
      Tags:
        - Key: Name
          Value: !Sub '${ProjectName}-private-rt'

  PrivateSubnet1RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PrivateSubnet1
      RouteTableId: !Ref PrivateRouteTable

  PrivateSubnet2RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PrivateSubnet2
      RouteTableId: !Ref PrivateRouteTable

  PrivateSubnet3RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PrivateSubnet3
      RouteTableId: !Ref PrivateRouteTable

  BastionSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: SSH from dbt platform to bastion
      VpcId: !Ref Vpc
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: !Ref DbtCidr1
          Description: dbt platform 1
        - !If
          - HasDbtCidr2
          - IpProtocol: tcp
            FromPort: 22
            ToPort: 22
            CidrIp: !Ref DbtCidr2
            Description: dbt platform 2
          - !Ref AWS::NoValue
        - !If
          - HasDbtCidr3
          - IpProtocol: tcp
            FromPort: 22
            ToPort: 22
            CidrIp: !Ref DbtCidr3
            Description: dbt platform 3
          - !Ref AWS::NoValue
        - !If
          - HasDbtCidr4
          - IpProtocol: tcp
            FromPort: 22
            ToPort: 22
            CidrIp: !Ref DbtCidr4
            Description: dbt platform 4
          - !Ref AWS::NoValue
        - !If
          - HasDbtCidr5
          - IpProtocol: tcp
            FromPort: 22
            ToPort: 22
            CidrIp: !Ref DbtCidr5
            Description: dbt platform 5
          - !Ref AWS::NoValue
        - !If
          - HasDbtCidr6
          - IpProtocol: tcp
            FromPort: 22
            ToPort: 22
            CidrIp: !Ref DbtCidr6
            Description: dbt platform 6
          - !Ref AWS::NoValue
      Tags:
        - Key: Name
          Value: !Sub '${ProjectName}-bastion-sg'

  RedshiftSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Redshift Serverless from bastion
      VpcId: !Ref Vpc
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 5439
          ToPort: 5439
          SourceSecurityGroupId: !Ref BastionSecurityGroup
          Description: Redshift from bastion
      Tags:
        - Key: Name
          Value: !Sub '${ProjectName}-redshift-sg'

Outputs:
  VpcId:
    Value: !Ref Vpc
    Export:
      Name: !Sub '${ProjectName}-VpcId'
  PublicSubnetId:
    Value: !Ref PublicSubnet
    Export:
      Name: !Sub '${ProjectName}-PublicSubnetId'
  PrivateSubnetIds:
    Value: !Join [',', [!Ref PrivateSubnet1, !Ref PrivateSubnet2, !Ref PrivateSubnet3]]
    Export:
      Name: !Sub '${ProjectName}-PrivateSubnetIds'
  BastionSecurityGroupId:
    Value: !Ref BastionSecurityGroup
    Export:
      Name: !Sub '${ProjectName}-BastionSecurityGroupId'
  RedshiftSecurityGroupId:
    Value: !Ref RedshiftSecurityGroup
    Export:
      Name: !Sub '${ProjectName}-RedshiftSecurityGroupId'

02-redshift-serverless.yml

This creates a Redshift Serverless Namespace and Workgroup. The Workgroup is set to be inaccessible from outside (PubliclyAccessible: false). For the admin password, ManageAdminPassword is enabled so that Secrets Manager generates it automatically.

02-redshift-serverless.yml
AWSTemplateFormatVersion: '2010-09-09'
Description: dbt platform SSH tunnel lab - 02 Redshift Serverless (namespace, workgroup)

Parameters:
  ProjectName:
    Type: String
    Default: dbt-rs-ssh
    Description: Must match the network stack
  DbName:
    Type: String
    Default: dev
  AdminUsername:
    Type: String
    Default: admin
  BaseCapacity:
    Type: Number
    Default: 8
    AllowedValues: [8, 16, 24, 32]
    Description: Base RPU. 8 is the minimum (lowest cost)

Resources:
  Namespace:
    Type: AWS::RedshiftServerless::Namespace
    Properties:
      NamespaceName: !Sub '${ProjectName}-ns'
      DbName: !Ref DbName
      AdminUsername: !Ref AdminUsername
      # Admin password is generated and stored in Secrets Manager
      ManageAdminPassword: true

  Workgroup:
    Type: AWS::RedshiftServerless::Workgroup
    DependsOn: Namespace
    Properties:
      WorkgroupName: !Sub '${ProjectName}-wg'
      NamespaceName: !Sub '${ProjectName}-ns'
      BaseCapacity: !Ref BaseCapacity
      PubliclyAccessible: false
      SubnetIds: !Split [',', {'Fn::ImportValue': !Sub '${ProjectName}-PrivateSubnetIds'}]
      SecurityGroupIds:
        - {'Fn::ImportValue': !Sub '${ProjectName}-RedshiftSecurityGroupId'}

Outputs:
  NamespaceName:
    Value: !Sub '${ProjectName}-ns'
  WorkgroupName:
    Value: !Sub '${ProjectName}-wg'
    Export:
      Name: !Sub '${ProjectName}-WorkgroupName'
  WorkgroupArn:
    Value: !GetAtt Workgroup.Workgroup.WorkgroupArn
    Export:
      Name: !Sub '${ProjectName}-WorkgroupArn'
  WorkgroupEndpoint:
    Description: Use this as Server Hostname in dbt platform
    Value: !GetAtt Workgroup.Workgroup.Endpoint.Address

03-bastion.yml

This creates the bastion EC2 instance and an Elastic IP. UserData creates the OS user (dbtuser) that the dbt platform logs in as, and sets ClientAliveInterval and others so that SSH connections are less likely to drop.

AmazonSSMManagedInstanceCore is attached to the IAM role. This is so that registering the dbt platform's public key and connecting to Redshift from my own machine can both be done via SSM.

03-bastion.yml
AWSTemplateFormatVersion: '2010-09-09'
Description: dbt platform SSH tunnel lab - 03 bastion (EC2 + Elastic IP, SSM access)

Parameters:
  ProjectName:
    Type: String
    Default: dbt-rs-ssh
    Description: Must match the network stack
  InstanceType:
    Type: String
    Default: t3.micro
  BastionUser:
    Type: String
    Default: dbtuser
    Description: OS user that dbt platform logs in as (enter the same value in the dbt connection)
  LatestAmiId:
    Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
    Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64

Resources:
  BastionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: ec2.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        # SSM Session Manager / Run Command (used to register the dbt public key)
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore

  BastionInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Roles:
        - !Ref BastionRole

  BastionInstance:
    Type: AWS::EC2::Instance
    DependsOn: BastionInstanceProfile
    Properties:
      ImageId: !Ref LatestAmiId
      InstanceType: !Ref InstanceType
      IamInstanceProfile: !Ref BastionInstanceProfile
      SubnetId: {'Fn::ImportValue': !Sub '${ProjectName}-PublicSubnetId'}
      SecurityGroupIds:
        - {'Fn::ImportValue': !Sub '${ProjectName}-BastionSecurityGroupId'}
      Tags:
        - Key: Name
          Value: !Sub '${ProjectName}-bastion'
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          set -euxo pipefail
          useradd -m -s /bin/bash ${BastionUser}
          install -d -m 700 -o ${BastionUser} -g ${BastionUser} /home/${BastionUser}/.ssh
          install -m 600 -o ${BastionUser} -g ${BastionUser} /dev/null /home/${BastionUser}/.ssh/authorized_keys
          cat > /etc/ssh/sshd_config.d/99-dbt.conf <<'EOF'
          ClientAliveInterval 30
          ClientAliveCountMax 10
          EOF
          systemctl restart sshd

  BastionEip:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
      Tags:
        - Key: Name
          Value: !Sub '${ProjectName}-bastion-eip'

  BastionEipAssociation:
    Type: AWS::EC2::EIPAssociation
    Properties:
      AllocationId: !GetAtt BastionEip.AllocationId
      InstanceId: !Ref BastionInstance

Outputs:
  BastionInstanceId:
    Value: !Ref BastionInstance
  BastionPublicIp:
    Description: Use this as the bastion hostname in the dbt SSH tunnel settings
    Value: !Ref BastionEip
  BastionUser:
    Value: !Ref BastionUser

04-iam-users.yml

This creates IAM users for development and production, and attaches a policy that allows only redshift-serverless:GetCredentials on the Workgroup.
※ Access keys are not included in the template so that no secrets remain in the stack.

04-iam-users.yml
AWSTemplateFormatVersion: '2010-09-09'
Description: dbt platform SSH tunnel lab - 04 IAM users for dev / prod (access keys are NOT created here)

Parameters:
  ProjectName:
    Type: String
    Default: dbt-rs-ssh
    Description: Must match the other stacks

Resources:
  DbtDevUser:
    Type: AWS::IAM::User
    Properties:
      UserName: !Sub '${ProjectName}-dbt-dev'

  DbtProdUser:
    Type: AWS::IAM::User
    Properties:
      UserName: !Sub '${ProjectName}-dbt-prod'

  RedshiftServerlessAccessPolicy:
    Type: AWS::IAM::ManagedPolicy
    Properties:
      ManagedPolicyName: !Sub '${ProjectName}-redshift-serverless-access'
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - redshift-serverless:GetCredentials
            Resource: {'Fn::ImportValue': !Sub '${ProjectName}-WorkgroupArn'}
      Users:
        - !Ref DbtDevUser
        - !Ref DbtProdUser

Outputs:
  DbtDevUserName:
    Value: !Ref DbtDevUser
  DbtProdUserName:
    Value: !Ref DbtProdUser

Creating the stacks

Deploy the four templates in order from the top.

aws cloudformation deploy \
  --template-file 01-network.yml \
  --stack-name "$PROJECT-network" \
  --parameter-overrides ProjectName="$PROJECT" \
    DbtCidr1="$DBT_CIDR1" DbtCidr2="$DBT_CIDR2" DbtCidr3="$DBT_CIDR3" \
    DbtCidr4="$DBT_CIDR4" DbtCidr5="$DBT_CIDR5" DbtCidr6="$DBT_CIDR6" \
  --capabilities CAPABILITY_NAMED_IAM

aws cloudformation deploy \
  --template-file 02-redshift-serverless.yml \
  --stack-name "$PROJECT-redshift" \
  --parameter-overrides ProjectName="$PROJECT" \
  --capabilities CAPABILITY_NAMED_IAM

aws cloudformation deploy \
  --template-file 03-bastion.yml \
  --stack-name "$PROJECT-bastion" \
  --parameter-overrides ProjectName="$PROJECT" \
  --capabilities CAPABILITY_NAMED_IAM

aws cloudformation deploy \
  --template-file 04-iam-users.yml \
  --stack-name "$PROJECT-iam" \
  --parameter-overrides ProjectName="$PROJECT" \
  --capabilities CAPABILITY_NAMED_IAM

Creating Redshift Serverless takes a few minutes.

2. Create a verification DB and sample data via the bastion

Create a verification database dbt_verify to use as the dbt target, along with sample data to use as the source.
The Workgroup is in a private subnet, so I connect from my local psql using SSM Session Manager port forwarding. This means I don't need to add my own IP to the bastion's security group.

Get the values needed for the connection from the stack outputs.

get_out () {
  aws cloudformation describe-stacks --stack-name "$1" \
    --query "Stacks[0].Outputs[?OutputKey=='$2'].OutputValue" --output text
}

export RS_ENDPOINT=$(get_out "$PROJECT-redshift" WorkgroupEndpoint)
export BASTION_IP=$(get_out "$PROJECT-bastion" BastionPublicIp)
export BASTION_ID=$(get_out "$PROJECT-bastion" BastionInstanceId)

Next, start port forwarding in the first terminal. Keep this terminal open.

aws ssm start-session --target "$BASTION_ID" \
  --document-name AWS-StartPortForwardingSessionToRemoteHost \
  --parameters "host=$RS_ENDPOINT,portNumber=5439,localPortNumber=15439"

When Waiting for connections... is displayed, run the SQL in a second terminal. Get the admin password from Secrets Manager and put it in an environment variable.

export SECRET_ARN=$(aws redshift-serverless get-namespace --namespace-name "$PROJECT-ns" \
  --query "namespace.adminPasswordSecretArn" --output text)
export PGPASSWORD=$(aws secretsmanager get-secret-value --secret-id "$SECRET_ARN" \
  --query SecretString --output text | python3 -c 'import sys,json; print(json.load(sys.stdin)["password"])')

I ran the SQL files with psql -f. CREATE DATABASE is run while connected to dev, which exists from the start.
The sample data is loaded while connected to the newly created dbt_verify.

psql "host=localhost port=15439 dbname=dev user=admin sslmode=require" \
  -f 01-create-db.sql

psql "host=localhost port=15439 dbname=dbt_verify user=admin sslmode=require" \
  -f 02-sample-data.sql

This loads 5 rows into the customers table and 8 rows into the orders table.

The SQL files I ran are as follows.

SQL that runs CREATE DATABASE:

01-create-db.sql
-- 01-create-db.sql
CREATE DATABASE dbt_verify;

This SQL creates the sample data. It creates two tables, customers and orders, in the source_data schema.

02-sample-data.sql
-- 02-sample-data.sql
CREATE SCHEMA IF NOT EXISTS source_data;

DROP TABLE IF EXISTS source_data.orders;
DROP TABLE IF EXISTS source_data.customers;

CREATE TABLE source_data.customers (
    customer_id  INTEGER       NOT NULL,
    first_name   VARCHAR(50)   NOT NULL,
    last_name    VARCHAR(50)   NOT NULL,
    created_at   DATE          NOT NULL
);

CREATE TABLE source_data.orders (
    order_id     INTEGER       NOT NULL,
    customer_id  INTEGER       NOT NULL,
    order_date   DATE          NOT NULL,
    status       VARCHAR(20)   NOT NULL,
    amount       DECIMAL(10,2) NOT NULL
);

INSERT INTO source_data.customers (customer_id, first_name, last_name, created_at) VALUES
    (1, 'Taro',    'Yamada',  '2026-01-05'),
    (2, 'Hanako',  'Suzuki',  '2026-01-12'),
    (3, 'Ichiro',  'Sato',    '2026-02-03'),
    (4, 'Yuki',    'Tanaka',  '2026-02-20'),
    (5, 'Ken',     'Ito',     '2026-03-08');

INSERT INTO source_data.orders (order_id, customer_id, order_date, status, amount) VALUES
    (101, 1, '2026-03-01', 'completed', 1200.00),
    (102, 1, '2026-03-15', 'completed',  850.50),
    (103, 2, '2026-03-02', 'completed', 3000.00),
    (104, 3, '2026-03-10', 'returned',   450.00),
    (105, 3, '2026-03-18', 'completed',  980.00),
    (106, 4, '2026-03-20', 'placed',    1500.00),
    (107, 5, '2026-03-22', 'shipped',    620.75),
    (108, 2, '2026-03-25', 'completed',  275.00);

3. Create the connection in the dbt platform

Enable SSH tunnels from Account settings in the dbt platform and create the Redshift connection.

The values for the settings are as follows.

Item Value
Server Hostname Redshift endpoint
Port 5439
Database dbt_verify (default output destination)
SSH Tunnel Hostname Hostname of the SSH server
SSH Tunnel Username dbtuser
SSH Tunnel Port 22

When you save the settings, a public key is displayed. A new public key is generated every time you save, so save only once and use the key displayed last.

Register the public key with SSM Run Command.

export DBT_PUBKEY='<dbt platform に表示された公開鍵>'

aws ssm send-command \
  --instance-ids "$BASTION_ID" \
  --document-name AWS-RunShellScript \
  --parameters "commands=[\"echo '${DBT_PUBKEY}' >> /home/dbtuser/.ssh/authorized_keys\"]" \
  --query "Command.CommandId" --output text

Check the execution result with the Command ID that was output. If Success is displayed, the registration worked.

aws ssm get-command-invocation --command-id "<Command ID>" --instance-id "$BASTION_ID" \
  --query "[Status,StandardErrorContent]" --output text

4. Set the IAM users' permissions on the Redshift side

Create Redshift users corresponding to the IAM users and grant privileges. Here I create them with the following approach.

  • Development: The output schema is determined by the dbt-side setting (the Schema in Development credentials), so grant only the database CREATE privilege and read privileges on the source
  • Production: Grant the same privileges as development, and additionally create the output schema analytics owned by the production user. Do not grant the development user write privileges on analytics
03-grants.sql
-- 03-grants.sql
-- Users for IAM authentication (password disabled)
CREATE USER :"dev_user"  PASSWORD DISABLE;
CREATE USER :"prod_user" PASSWORD DISABLE;

-- dbt creates schemas, so CREATE on the database is required
GRANT CREATE ON DATABASE dbt_verify TO :"dev_user";
GRANT CREATE ON DATABASE dbt_verify TO :"prod_user";

-- Read access to the source (for both development and production)
GRANT USAGE ON SCHEMA source_data TO :"dev_user";
GRANT USAGE ON SCHEMA source_data TO :"prod_user";
GRANT SELECT ON ALL TABLES IN SCHEMA source_data TO :"dev_user";
GRANT SELECT ON ALL TABLES IN SCHEMA source_data TO :"prod_user";

-- Production output schema (owned by the production user; the development user cannot write)
CREATE SCHEMA analytics AUTHORIZATION :"prod_user";

Pass the user names with the -v option of psql. The Redshift-side user name is the IAM user name prefixed with IAM:.

psql "host=localhost port=15439 dbname=dbt_verify user=admin sslmode=require" \
  -v dev_user="IAM:$PROJECT-dbt-dev" \
  -v prod_user="IAM:$PROJECT-dbt-prod" \
  -f 03-grants.sql

5. Create the project

Create a project in the dbt platform. For development credentials (Personal development credentials), the only selectable authentication method is "Username and password". Here, enter a placeholder username and password, and set Schema to the schema name to use as the development output destination. This value becomes the Development credentials value for each dbt user (here dbt_tyasuhara).

The switch to IAM authentication is done in a later step (step 7).

6. Issue access keys and register them as dbt platform environment variables

Issue access keys for the development and production IAM users.

aws iam create-access-key --user-name "$PROJECT-dbt-dev" \
  --query "AccessKey.[AccessKeyId,SecretAccessKey]" --output text

aws iam create-access-key --user-name "$PROJECT-dbt-prod" \
  --query "AccessKey.[AccessKeyId,SecretAccessKey]" --output text

In the dbt platform under Orchestration > Environments > Environment variables, register two environment variables as follows.

Environment variable Value
DBT_ENV_SECRET_ACCESS_KEY_ID Access key ID
DBT_ENV_SECRET_ACCESS_KEY Secret access key
  • Register the development key in the development environment column
  • Register the production key in the Project default column
  • ※ I created the production (prd) environment later, which is why it is registered this way. In actual operation, you would register the development key in Project default and override it in the production environment's column
  • If a variable name starts with DBT_ENV_SECRET_, the dbt platform treats it as a secret. I gave the key ID the same prefix so that it is also masked

7. Switch to IAM authentication with extended attributes in development and production

First, switch the development environment of the project created in step 5 to IAM authentication using extended attributes. The setting location is Orchestration > Environments > development environment > Settings > Edit > Extended attributes.

method: iam
region: ap-northeast-1
user: dummy
is_serverless: true
serverless_work_group: dbt-rs-ssh-wg
serverless_acct_id: '<AWS アカウント ID>'
access_key_id: '{{ env_var(''DBT_ENV_SECRET_ACCESS_KEY_ID'') }}'
secret_access_key: '{{ env_var(''DBT_ENV_SECRET_ACCESS_KEY'') }}'
  • user is not used with Redshift Serverless, but it is required
  • password is ignored with IAM authentication

Next, create the production deployment environment and set the extended attributes in the same way.

  • Schema was set to analytics
  • Extended attributes are set not on the environment but on the connection profile assigned to the environment
  • The content is the same YAML as the development environment

https://docs.getdbt.com/docs/platform/connect-data-platform/connect-redshift?version=2#authentication-parameters

8. Add sources and models and run dbt run

First, run basic commands in Studio in the development environment.

In Studio, add a source and models that read the sample data. The models do not specify a schema, so the output destination is the Profile's Schema in development and the deployment environment's Schema in production.

models/staging/_sources.yml
version: 2

sources:
  - name: source_data
    database: dbt_verify
    schema: source_data
    tables:
      - name: customers
        columns:
          - name: customer_id
            data_tests:
              - unique
              - not_null
      - name: orders
        columns:
          - name: order_id
            data_tests:
              - unique
              - not_null
          - name: status
            data_tests:
              - accepted_values:
                  arguments:
                    values: ['placed', 'shipped', 'completed', 'returned']
models/staging/stg_customers.sql
select
    customer_id,
    first_name,
    last_name,
    first_name || ' ' || last_name as full_name,
    created_at
from {{ source('source_data', 'customers') }}
models/staging/stg_orders.sql
select
    order_id,
    customer_id,
    order_date,
    status,
    amount
from {{ source('source_data', 'orders') }}
models/marts/customer_orders.sql
{{ config(materialized='table') }}

with customers as (
    select * from {{ ref('stg_customers') }}
),

orders as (
    select * from {{ ref('stg_orders') }}
),

order_summary as (
    select
        customer_id,
        count(*) as order_count,
        sum(case when status = 'completed' then amount else 0 end) as completed_amount,
        min(order_date) as first_order_date,
        max(order_date) as latest_order_date
    from orders
    group by customer_id
)

select
    c.customer_id,
    c.full_name,
    c.created_at,
    coalesce(s.order_count, 0) as order_count,
    coalesce(s.completed_amount, 0) as completed_amount,
    s.first_order_date,
    s.latest_order_date
from customers as c
left join order_summary as s
    on c.customer_id = s.customer_id

Run the commands in Studio.
Even with the SSH-tunnel-enabled connection, the extended attributes were applied and the connection worked with IAM authentication.

9. Run the production job

Run a job in the production deployment environment where the extended attributes are set.

In Orchestration > Jobs, create a job that targets the production environment, set the command to dbt build, and run it.

This also ran without problems.

10. Check the executing user on the Redshift side

Check on the Redshift side whether development and production ran as different users. With port forwarding open, check the owners of tables and views as the admin.

psql "host=localhost port=15439 dbname=dbt_verify user=admin sslmode=require" -c "
select schemaname, tablename as name, tableowner as owner, 'table' as type
from pg_tables where schemaname in ('analytics') or schemaname like 'dbt\_%'
union all
select schemaname, viewname, viewowner, 'view'
from pg_views where schemaname in ('analytics') or schemaname like 'dbt\_%'
order by 1, 2;"

The output is as follows. The objects in production's analytics are owned by IAM:dbt-rs-ssh-dbt-prod, and the objects in the development schema are owned by IAM:dbt-rs-ssh-dbt-dev. This confirms that development and production ran as different IAM users (different Redshift users).

The development output destination also follows the settings of the executing user on the dbt platform.

  schemaname   |      name       |          owner          | type
---------------+-----------------+-------------------------+-------
 analytics     | customer_orders | IAM:dbt-rs-ssh-dbt-prod | table
 analytics     | stg_customers   | IAM:dbt-rs-ssh-dbt-prod | view
 analytics     | stg_orders      | IAM:dbt-rs-ssh-dbt-prod | view
 dbt_tyasuhara | customer_orders | IAM:dbt-rs-ssh-dbt-dev  | table
 dbt_tyasuhara | stg_customers   | IAM:dbt-rs-ssh-dbt-dev  | view
 dbt_tyasuhara | stg_orders      | IAM:dbt-rs-ssh-dbt-dev  | view
(6 rows)

Let's also query the production mart table.

psql "host=localhost port=15439 dbname=dbt_verify user=admin sslmode=require" -c "
select customer_id, full_name, order_count, completed_amount,
       first_order_date, latest_order_date
from analytics.customer_orders
order by customer_id;"
 customer_id |   full_name   | order_count | completed_amount | first_order_date | latest_order_date
-------------+---------------+-------------+------------------+------------------+-------------------
           1 | Taro Yamada   |           2 |          2050.50 | 2026-03-01       | 2026-03-15
           2 | Hanako Suzuki |           2 |          3275.00 | 2026-03-02       | 2026-03-25
           3 | Ichiro Sato   |           2 |           980.00 | 2026-03-10       | 2026-03-18
           4 | Yuki Tanaka   |           1 |             0.00 | 2026-03-20       | 2026-03-20
           5 | Ken Ito       |           1 |             0.00 | 2026-03-22       | 2026-03-22

I got the expected aggregation results from the sample data.

Caveats

Writing host in the extended attributes causes a timeout

The example in the Redshift Serverless IAM authentication documentation includes host in the extended attributes. At first I followed this example and wrote the Workgroup endpoint in host, and dbt debug timed out with the following error.

redshift_connector.error.OperationalError: ('connection time out', TimeoutError(110, 'Connection timed out'))

Looking at Connection: in the log, port was the value the dbt platform assigned for the SSH tunnel (here 45018), and host was the Redshift endpoint I wrote in the extended attributes. The dbt platform rewrites the connection target when using an SSH tunnel, but overriding it with host in the extended attributes seems to have made it try to connect directly to port 45018 on the Redshift endpoint without using the tunnel, which timed out.

So I removed host from the extended attributes, and dbt debug succeeded.
I have not checked the behavior without an SSH tunnel.

Conclusion

I connected from the dbt platform to Amazon Redshift Serverless using an SSH tunnel and IAM authentication, as separate IAM users for development and production.
You need to be careful about using extended attributes.
I hope this helps someone.


dbtの導入支援はクラスメソッドにお任せください!

クラスメソッドでは dbt の導入を支援しております。
製品の詳細や支援の内容についてお気軽にお問い合わせください。

dbtの詳細を見る

Share this article

Related articles