I am looking to use AWS RDS IAM database authentication with Ruby on Rails, as it allows a convenient way for AWS users to manage database permissions and avoid storing database passwords in their codebases.
At a high level, it works by generating a password based on your AWS credentials to connect to the database that are valid for only 15 minutes. If you want to connect again after 15 minutes, you would need to generate a new password.
This password can be generating using the AWS Ruby SDK easily, and thus can theoretically be embedded in config/database.yml
like so;
production:
adapter: mysql2
host: db_host
database: db_name
username: db_user
password: <%=
Aws::RDS::AuthTokenGenerator
.new(credentials: Aws::InstanceProfileCredentials.new)
.auth_token(
region: 'us-east-1',
endpoint: 'db_host:3306',
user_name: 'db_user'
)
%>
However, as far as I can tell, config/database.yml
is evaluated only once on startup, and remains cached in that state for Rails' lifetime.
Therefore, by using this approach, the Rails server would initially successfully connect to the database, but if at any point after the first 15 minute window Rails tried to open a new DB connection or reconnect a dropped connection, the now-expired credentials would be rejected.
What would be the best way to get IAM database authentication working with Rails? Do I need to somehow have a database configuration with a password that is re-evaluated on each connection establishment?