Skip to content

Instantly share code, notes, and snippets.

@ngoduykhanh
Created September 17, 2021 15:26
Show Gist options
  • Save ngoduykhanh/e7ea95d5a2f6c8c32bbe413295ac6974 to your computer and use it in GitHub Desktop.
Save ngoduykhanh/e7ea95d5a2f6c8c32bbe413295ac6974 to your computer and use it in GitHub Desktop.
GCP Secret Manager Ansible library
#!/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()
@ngoduykhanh
Copy link
Author

Put the file in library directory then you can use it with

    - name: Get token
      google_secret_manager:
        name: my-token
        gcp_project: my-gcp-project
        version: latest
      register: token

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment