18

Is it possible to use variables on command or shell modules? I have the following code, and I would like to use variable file to provide some configurations:

I would like to read the Hadoop version from my variables file. On other modules of ansible I could use {{ansible_version}}, but with command or shell it doesn't works.

- name: start ZooKeeper HA
  command: hadoop-2.7.1/bin/hdfs zkfc -formatZK -nonInteractive

- name: start zkfc
  shell: hadoop-2.7.1/sbin/hadoop-daemon.sh start zkfc

I would like to convert to the following:

- name: Iniciar zkfc
  command: {{ hadoop_version }}/sbin/hadoop-daemon.sh start zkfc

Because if I run the with this syntax it throws this error:

- name: inicializar estado ZooKeeper HA
  command: {{hadoop_version}}/bin/hdfs zkfc -formatZK -nonInteractive
                             ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes.  Always quote template expression brackets when they
start a value. For instance:

    with_items:
      - {{ foo }}

Should be written as:

    with_items:
      - "{{ foo }}"

I have try using, but same problem:

- name: Iniciar zkfc
  command: "{{ hadoop_version }}"/sbin/hadoop-daemon.sh start zkfc

What is the correct syntax?

the
  • 21,007
  • 11
  • 68
  • 101
Asier Gomez
  • 6,034
  • 18
  • 52
  • 105

3 Answers3

31

Quote the full string in the command argument:

- name: Iniciar zkfc
  command: "{{ hadoop_version }}/sbin/hadoop-daemon.sh start zkfc"
techraf
  • 64,883
  • 27
  • 193
  • 198
  • Would be nice if it threw some sort of error or warning when the whole line not being quoted causes it to not interpret the variable format, instead of just failing silently. – theferrit32 Jun 14 '19 at 02:36
6

The syntax error is because you started a value with {. If you begin a value with a variable like so:

command: {{ my_var }}

then you must quote the whole line:

command: "{{ my_var }}"

This is due to the parser not being able to distinguish between YAML's dictionary syntax and variable interpolation otherwise.

Tom Manterfield
  • 6,515
  • 6
  • 36
  • 52
4

I have done below steps to replacing the inventory hostname in ansible shell module

- name: 'Task-10 Modif the splunk input.conf file with Actual hostname'

  become: yes
  become_method: sudo
  become_user: root
  shell: |
    /splunk/splunkforwarder/bin/splunk enable boot-start --accept-license --answer-yes --no-prompt -user splunk
    declare wfqdn 
    wfqdn=$(uname -n)
    sed -i "s/$wfqdn/"{{ inventory_hostname }}"/g" /splunk/splunkforwarder/etc/system/local/inputs.conf
  tags:
    - always

The Main play is :

sed -i "s/$wfqdn/"{{ inventory_hostname }}"/g" /splunk/splunkforwarder/etc/system/local/inputs.conf