Created
September 17, 2021 15:26
-
-
Save ngoduykhanh/e7ea95d5a2f6c8c32bbe413295ac6974 to your computer and use it in GitHub Desktop.
GCP Secret Manager Ansible library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from google.cloud import secretmanager | |
from ansible.module_utils.basic import AnsibleModule | |
def main(): | |
module = AnsibleModule( | |
argument_spec=dict( | |
name=dict(required=True), | |
version=dict(default='latest'), | |
gcp_project=dict(required=True), | |
state=dict(default='info', choices=['info']) | |
), | |
supports_check_mode=True | |
) | |
result = dict( | |
changed=False, | |
state=module.params['state'] | |
) | |
gcp_project = module.params['gcp_project'] | |
secret_name = module.params['name'] | |
secret_version = module.params['version'] | |
data = _get_secret_plaintext(gcp_project, secret_name, secret_version) | |
if module.check_mode: | |
module.exit_json(**result) | |
if module.params['state'] == 'info': | |
result['data'] = data | |
result['msg'] = 'Read the secret successfully' | |
module.exit_json(**result) | |
def _get_secret_plaintext(gcp_project, secret_name, version): | |
# Build GCP secret id with this format | |
secret_id = f"projects/{gcp_project}/secrets/{secret_name}/versions/{version}" | |
# Create the Secret Manager client | |
client = secretmanager.SecretManagerServiceClient() | |
# Get the response from Secret Manager API and decode it | |
response = client.access_secret_version(request={"name": secret_id}) | |
plaintext = response.payload.data.decode("UTF-8") | |
return plaintext | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Put the file in
library
directory then you can use it with