Authentication to GCP with Ansible using federated credentials without gcloud CLI

I have created a Kubernetes pod manifest in a cluster which I have integrated with GCP using Workload Identity Federation following this procedure Configure Workload Identity Federation with Kubernetes  |  IAM Documentation  |  Google Cloud.

I can execute the command below to generate a valid token for GCP.

gcloud auth login --cred-file /etc/workload-identity/credential-configuration.json
gcloud auth print-access-token

If I feed this token into the task below, it runs successfully.

- name: List GCP VMs
  google.cloud.gcp_compute_instance_info:
    auth_kind: accesstoken
    access_token: "{{ lookup ('env', 'GCP_TOKEN') }}"
    project: "{{ gcp_project }}"
    zone: "{{ gcp_zone }}"

Is there a way to execute the equivalent ‘gcloud’ using a standard Ansible module, where this CLI is not installed?

I found a solution, as below:

---
- hosts: 'localhost'
  gather_facts: false
  connection: 'local'
  vars:
    gcp_project: '...'
    gcp_zone: '...'
  tasks:
    - name: Obtain an access token
      uri:
        url: "https://sts.googleapis.com/v1/token"
        method: POST
        headers:
          Content-Type: application/json
        body_format: json
        body:
          audience: "{{ (lookup('file', '/etc/workload-identity/credential-configuration.json') | from_json).audience }}"
          grantType: "urn:ietf:params:oauth:grant-type:token-exchange"
          requestedTokenType: "urn:ietf:params:oauth:token-type:access_token"
          subjectTokenType: "urn:ietf:params:oauth:token-type:jwt"
          subjectToken: "{{ lookup('file', '/var/run/service-account/token') }}"
          scope: "https://www.googleapis.com/auth/cloud-platform"
      register: _token_response   

    - name: Impersonate the service account
      uri:
        url: "{{ (lookup('file', '/etc/workload-identity/credential-configuration.json') | from_json).service_account_impersonation_url }}"
        method: POST
        headers:
          Content-Type: application/json
          Authorization: "Bearer {{ _token_response.json.access_token }}"
        body_format: json
        body:
          scope: "https://www.googleapis.com/auth/cloud-platform"
      register: _impersonate_response

    - name: List GCP VMs
      google.cloud.gcp_compute_instance_info:
        auth_kind: accesstoken
        access_token: "{{ _impersonate_response.json.accessToken }}"
        project: "{{ gcp_project }}"
        zone: "{{ gcp_zone }}"
      register: _vm_info

    - name: Display VM info
      debug:
        var: _vm_info
1 Like