Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run a command on localhost to define variable for an Ansible playbook?

I’m very new to Ansible and trying to figure things out. I have a simple playbook to run on a remote host. To simplify drastically:

- hosts: all
  name: build render VM
  tasks:
    - copy:
        src: ./project_{{ project_id }}.yaml
        dest: /app/project.yaml
        owner: root

I would like to have project_id set to the output of this command, run on localhost: gcloud config get-value project. Ideally I’d like that to be stored into a variable or fact that can be used throughout the playbook. I know I can pass project_id=$(...) on the ansible cmd line, but I’d rather have it set up automatically in the playbook.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Taking for granted the given command only returns the id and nothing else.

With a task delegated to localhost:

- hosts: all
  name: build render VM
  tasks:
    - name: get project id
      command: gcloud config get-value project
      register: gcloud_cmd
      run_once: true
      delegate_to: localhost

    - name: set project id
      set_fact:
        project_id: "{{ gcloud_cmd.stdout }}"

    - copy:
        src: ./project_{{ project_id }}.yaml
        dest: /app/project.yaml
        owner: root

With a pipe lookup:

- hosts: all
  name: build render VM
  tasks:

    - name: set project id from localhost command
      set_fact:
        project_id: "{{ lookup('pipe', 'gcloud config get-value project') }}"
      run_once: true

    - copy:
        src: ./project_{{ project_id }}.yaml
        dest: /app/project.yaml
        owner: root
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading