-1

I am trying to emulate this behavior with Ansible raw command but I could not find any feature that achieve this

ssh user@host.com <<EOF
   command
   exit
EOF
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
soField
  • 2,536
  • 9
  • 36
  • 44
  • 1
    So it is just about [How to do multiline shell script in Ansible?](https://stackoverflow.com/a/40230416/6771046). – U880D Dec 20 '22 at 07:48

2 Answers2

2

You are simply sending the script:

command
exit

To the remote host. The <<EOF and EOF parts are parsed by your local shell and aren't part of the command. The equivalent ansible task would be:

- raw: |
    command
    exit

In most cases (if the remote target is running a semi-standard shell), you won't need the exit either; the script will exit after the last command completes.

larsks
  • 277,717
  • 41
  • 399
  • 399
0

You don't need to send a multiline commands via ssh, perhaps you have connected with ssh already with ansible when you set ansible_connection variable, e.g. in your inventory file:

[my_host_group]
host.com

[my_host_group:vars]
ansible_connection=ssh
ansible_become_user=root
ansible_ssh_user=user

Then execute a tasks with bash:

- name: Executing multiline command on host.com under user
  ansible.builtin.shell: command
  delegate_to: "{{ groups['my_host_group'][0] }}"
  become: False

Or just use ansible.builtin.command module instead of ansible.builtin.shell if your command is simple and not multi line.

You don't need an exit at the end of your script either (until you want to change an exit code and return them to ansible). 'Failed when' conditions is your firend:

- name: Executing multiline command on host.com under user
  ansible.builtin.shell: command
  delegate_to: "{{ groups['my_host_group'][0] }}"
  register: your_script_results
  ignore_errors: True
  become: False

- name: Print an exit code on script error
  ansible.builtin.debug:
    msg: "Script was failed with {{ your_script_results.rc }} exit code"
  when: your_script_results.failed
Alexander B
  • 36
  • 1
  • 3