Ansible GCP dynamic Inventory Plugin How to pass Project ID

Hi Everyone,

I am using the dynamic inventory file for setting up Ansible for running configurations in GCP

inventory.compute.gcp.yml

plugin: gcp_compute # name the plugin you want to use (use ansible-doc -t inventory -l to list available plugins)
projects:

  • <gcp_project_id> # Id of your gcp project
    regions: # regions from your project you want to fetch inventory from (you can also use zones instead of regions if you target one or several specific zones)
  • <gcp_project_region>
    filters:
    auth_kind: serviceaccount # gcp authentication kind. with service account you should provide the service account json key file to authenticate
    service_account_file: <service_account_file>.json # Service account json keyfile

How do I set the project_id as a variable?how can I pass the project ID from CLI when executing an ansible playbook? does ansible support jinja templating for inventory file? Please advise

Use templating to expand a variable name.

inventory.compute.gcp.yml

plugin: gcp_compute # name the plugin you want to use (use ansible-doc -t inventory -l to list available plugins)
projects:

  • “{{ gcp_project_id }}” # Id of your gcp project
    regions: # regions from your project you want to fetch inventory from (you can also use zones instead of regions if you target one or several specific zones)
  • "{{ gcp_project_region }}"
    filters:
    auth_kind: serviceaccount # gcp authentication kind. with service account you should provide the service account json key file to authenticate
    service_account_file: “{{ service_account_file }}.json” # Service account json keyfile

Use the -e (extra var) command line option to specify the variable values on the command line.

% ansible-playbook my_gcp_inventory.yml -e “gcp_project_id=XYZ123 gcp_project_region=ABC789 service_account_file=my_gcp_file”