7

I know it's possible to run multiple adhoc commands one after the other for each module and using playbook.

Playbook:


- hosts: webservers
  tasks:
   - name: create .ssh dir
     file: path ~/.ssh state=directory
   - name: copy pub key
     copy: src:~/.ssh/id.rsa_pub dest=~/.ssh/authorized_keys

I want the above to execute using adhoc in one line. Is it possible to do so?

techraf
  • 64,883
  • 27
  • 193
  • 198
k_vishwanath
  • 1,326
  • 2
  • 20
  • 28

3 Answers3

9

No, it is not possible.

ansible command accepts only one set of arguments for a single module and its parameters.

-m MODULE_NAME, --module-name=MODULE_NAME
module name to execute (default=command)

techraf
  • 64,883
  • 27
  • 193
  • 198
2

Use ansible-console and heredoc instead:

ansible-console <<<"cd webservers"$'\n'"setup"$'\n'"file path=~/.ssh state=directory"$'\n'"copy src=~/.ssh/id.rsa_pub dest=~/.ssh/authorized_keys"

This is technically one hack of a line but has no error handling. And is pretty not readable.

ansible-console alone eventually could do the trick. It's a pretty neat tool.

Sprinterfreak
  • 504
  • 4
  • 10
-2

We can actually use the below single ad-hoc command using Ansible module and Linux command:

ansible clientvm -m shell -a "mkdir ~/.ssh" && scp ~/.ssh/id_rsa.pub root@clientvm:~/.ssh/authorized_keys

In the above command, clientvm is the hostname where we are creating the directory and copying the file into it as per above requirement from the Ansible controller node.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
  • 1
    This is not a single command, it is 2 commands where the 2nd depends on the exit code of the first. The OP asked for a single command. – Waddles Apr 08 '21 at 07:57