|
584 | 584 | "source": [
|
585 | 585 | "### 🪪 IAM Database Authentication \n",
|
586 | 586 | "\n",
|
587 |
| - "[Manual IAM database authentication](https://cloud.google.com/sql/docs/mysql/authentication#manual) is supported for **MySQL** Cloud SQL instances. \n", |
| 587 | + "[Automatic IAM database authentication](https://cloud.google.com/sql/docs/mysql/authentication#automatic) is supported for **MySQL** Cloud SQL instances. \n", |
588 | 588 | "\n",
|
589 |
| - "> 💡 This allows an IAM user to establish an authenticated connection to a MySQL database using an **OAuth2** token as their password in the connector's `connect` method.\n", |
| 589 | + "> 💡 This allows an IAM user to establish an authenticated connection to a MySQL database without having to set a password and enabling the `enable_iam_auth` parameter in the connector's `connect` method.\n", |
590 | 590 | "\n",
|
591 | 591 | "> 🚨 If you are using a pre-existing Cloud SQL instance within this notebook you may need to [configure Cloud SQL instance to allow IAM authentication](https://cloud.google.com/sql/docs/mysql/create-edit-iam-instances#configuring_existing_instances_for) by setting the `cloudsql_iam_authentication` database flag to `On`. \n",
|
592 | 592 | "(Cloud SQL instances created within this notebook already have it enabled)\n"
|
|
663 | 663 | "import sqlalchemy\n",
|
664 | 664 | "\n",
|
665 | 665 | "# IAM database user parameter (IAM user's email before the \"@\" sign, mysql truncates usernames)\n",
|
666 |
| - "# ex. IAM user with email \"[email protected]\" would have database user name \"demo-user\"\n", |
| 666 | + "# ex. IAM user with email \"[email protected]\" would have database username \"demo-user\"\n", |
667 | 667 | "IAM_USER = current_user[0].split(\"@\")[0]\n",
|
668 | 668 | "\n",
|
669 |
| - "# get application default credentials of IAM user (current logged in user)\n", |
670 |
| - "credentials, project = google.auth.default()\n", |
671 |
| - "\n", |
672 |
| - "# refresh credentials if expired\n", |
673 |
| - "if not credentials.valid:\n", |
674 |
| - " request = Request()\n", |
675 |
| - " credentials.refresh(request)\n", |
676 |
| - "\n", |
677 | 669 | "# initialize connector\n",
|
678 | 670 | "connector = Connector()\n",
|
679 | 671 | "\n",
|
680 |
| - "# getconn now using IAM user and OAuth2 token as password\n", |
| 672 | + "# getconn now using IAM user and requiring no password with IAM Auth enabled\n", |
681 | 673 | "def getconn():\n",
|
682 | 674 | " conn = connector.connect(\n",
|
683 | 675 | " INSTANCE_CONNECTION_NAME,\n",
|
684 | 676 | " \"pymysql\",\n",
|
685 | 677 | " user=IAM_USER,\n",
|
686 |
| - " password=credentials.token,\n", |
687 | 678 | " db=\"\", # log in to instance but don't connect to specific database\n",
|
| 679 | + " enable_iam_auth=True\n", |
688 | 680 | " )\n",
|
689 | 681 | " return conn\n",
|
690 | 682 | "\n",
|
|
0 commit comments