Rotate a PostgreSQL password
(self, record, new_password, revert=False)
| 39 | self.rotate(record, new_password, revert=True) |
| 40 | |
| 41 | def rotate(self, record, new_password, revert=False): |
| 42 | """Rotate a PostgreSQL password""" |
| 43 | if revert: |
| 44 | old_password = new_password |
| 45 | new_password = self.password |
| 46 | else: |
| 47 | old_password = self.password |
| 48 | |
| 49 | try: |
| 50 | with psycopg2.connect(host=self.host, port=self.port, user=self.login, password=old_password, |
| 51 | database=self.db) as connection: |
| 52 | logging.debug(f'Connected to {self.host}') |
| 53 | with connection.cursor() as cursor: |
| 54 | sql = f'alter user {self.login} with password %s' |
| 55 | cursor.execute(sql, (new_password,)) |
| 56 | return True |
| 57 | except Exception as e: |
| 58 | if revert: |
| 59 | logging.error('Error reverting password rotation of Postgres server: %s', e) |
| 60 | else: |
| 61 | logging.error('Error rotating password of Postgres server: %s', e) |
| 62 | |
| 63 | return False |