title: AWS RDS - IAM Database Authentication with Rails
body: <p>I am looking to use AWS RDS <a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.Connecting.html" rel="noreferrer">IAM database authentication</a> 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.</p>
  
  <p>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.</p>
  
  <p>This password can be generating using the AWS Ruby SDK easily, and thus can theoretically be embedded in <code>config/database.yml</code> like so;</p>
  
  <pre><code>production:
    adapter: mysql2
    host: db_host
    database: db_name
    username: db_user
    password: &lt;%=
                Aws::RDS::AuthTokenGenerator
                  .new(credentials: Aws::InstanceProfileCredentials.new)
                  .auth_token(
                    region: 'us-east-1',
                    endpoint: 'db_host:3306',
                    user_name: 'db_user'
                  )
              %&gt;
  </code></pre>
  
  <p>However, as far as I can tell, <code>config/database.yml</code> is evaluated only once on startup, and remains cached in that state for Rails' lifetime.</p>
  
  <p>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.</p>
  
  <p>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?</p>