Ansible, copy script, then execute in remote machine - bash

I want to copy a script to a remote server and then execute it. I can copy it to the directory /home/user/scripts, but when I run ansible script, it returns Could not find or access '/home/user/scripts/servicios.sh'
The full error output is:
fatal: [192.168.1.142]: FAILED! => {"changed": false, "msg": "Could not find or access '/home/user/scripts/servicios.sh'"}
Here is the ansible playbook
- name: correr script
hosts: all
tasks:
- name: crear carpeta de scripts
file:
path: /home/user/scripts
state: directory
- name: copiar el script
copy:
src: /home/local/servicios.sh
dest: /home/user/scripts/servicios.sh
- name: ejecutar script como sudo
become: yes
script: /home/user/scripts/servicios.sh

You don’t need to create a directory and copy the script to target (remote node), the script module does that for you. It takes the script name followed by a list of space-delimited arguments. The local script at path will be transferred to the remote node and then executed. The script will be processed through the shell environment on the remote node. You were getting the error because script module expects the path /home/user/scripts/servicios.sh on your Ansible controller (the node where you are running the playbook from). To make it work you can specify correct path (/home/local/servicios.sh) in script task instead of /home/user/scripts/servicios.sh which is the path on the remote node. So you can change the playbook like this: You can also register the result of that command as a variable if you would like to see that.
---
- name: correr script
hosts: all
become: yes
tasks:
- name: ejecutar script como sudo
script: /home/local/servicios.sh
register: console
- debug: msg="{{ console.stdout }}"
- debug: msg="{{ console.stderr }}"
What if don’t want to go for script module and you are interested in creating a directory and copy the script to target (remote node) explicitly, and run it? No worries, you can still use the command module like this:
---
- name: correr script
hosts: all
become: yes
tasks:
- name: crear carpeta de scripts
file:
path: /home/user/scripts
state: directory
- name: copiar el script
copy:
src: /home/local/servicios.sh
dest: /home/user/scripts/servicios.sh
- name: ejecutar script como sudo
command: bash /home/user/scripts/servicios.sh
register: console
- debug: msg="{{ console.stdout }}"
- debug: msg="{{ console.stderr }}"
But I strongly recommend to go for script module.

The script tag itself transfers the script from the local machine to remote machine and executes it there.
So, the path specified in the script module is of the local machine and not the remote machine i.e., /home/local/servicios.sh instead of /home/user/scripts/servicios.sh
As you have specified the path which is supposed to be on the remote machine, ansible is unable to find that script on local machine at the given path which results in the given error.
Hence, update the path in the task to local path as shown below,
- name: ejecutar script como sudo
become: yes
script: /home/local/servicios.sh
So scripts cant be executed inside the remote server and should be
executed via local machine to the remote?
#thrash3d No, it is not like that. When you use script tag the script is transferred to the remote machine and then it is executed there. If there is a script which you don't want to put on your remote machine and just want to execute it then you can use script tag.
If you want that script on your remote machine then you can first copy your script on remote machine and then execute it there.
Both ways are correct and it is up to you which case suits you better.

Related

Ansible Restarting VMware vCenter Server Appliance

I would like to simply reboot the VCSA using Ansible as part of a development workflow. Does anybody have any ideas as to how to do so?
https://kb.vmware.com/s/article/2147152
This would normally be done by hitting 'shell' and then turning off/on the service and/or 'reboot'
I've been playing around with ansible.raw, but it seems to hang indefinitely.
A few of the attempts I have tried:
tasks:
- name: 'get into the shell'
raw: 'shell'
register: shell
- debug: msg="{{ shell }}"
- name: 'reboot'
raw: 'reboot'
register: reboot
- debug: msg="{{ reboot }}"
- name: Unconditionally reboot the machine with all defaults
reboot:
I resolved this by manually going into every system and changing the default shell to /bin/bash
https://communities.vmware.com/t5/vCenter-Server-Discussions/Access-to-VCSA-through-SSH-and-or-local-console-is-NOT-working/td-p/1816293
############
~# vi /etc/passwd
and change the appliancesh to /bin/bash
root:x:0:0:root:/root:/bin/bash
Also make sure that ssh access for root is enabled from /etc/ssh/sshd_config

Ansible execution using variables

hi I want to execute "java -jar xxxxxxx.war 172.xx.xxx.xx" command on a host.
I am able to execute in a single system through Ansible, but I want to execute that command in a multiple hosts and that execution needs to be done in their respective system IP's.
eg:
java -jar xxxxxxx.war 172.xx.xxx.01 needs to be executed on the system with the IP 172.xx.xxx.01
java -jar xxxxxxx.war 172.xx.xxx.02 needs to be executed on the system with the IP 172.xx.xxx.02
- name: Executing the jar file
win_shell: "CMD /C \"java -jar generateKeyStoreFiles.jar storeipTest.csv\""
args:
chdir: C:/Keystore_Pem_FileAutoGenerationOracle_allgoodthings/
- name: Copying of Xstore POS Installer
win_copy:
src: /root/Installers/Softwares/Xstore
dest: C:/Installers/Softwares/
- name: Copying of xstore_mobile.keystore file
win_copy:
src: C:/Keystore_Pem_FileAutoGenerationOracle_allgoodthings/finalcerts/cert/xstore_mobile.keystore
dest: C:/Installers/Softwares/Xstore/
remote_src: yes
- name: install Xstore POS
win_shell: "CMD /C \"java -jar xstore-18.0.0.0.654-0.0.0-0.0-XST-pos-install.jar\""
args:
chdir: C:/Installers/Softwares/Xstore/
how is that possible ?, I need to execute that on windows hosts.
I guess you could create an inventory and a playbook to achieve that.
inventory
[all]
13.48.139.217
13.48.139.218
playbook.yml
- hosts: all
tasks:
- name: run java command
command: java -jar xxxxxxx.war {{ansible_host}}
{{ansible_host}} is an Asnsible variable that will be replaced with an IP address mentioned in inventory.
Then execute it ansible-playbook -i inventory playbook.yml.

File created by ansible script module not present after running against remote node

I'm setting up some server in AWS, and want to use Ansible to do some shell in remote nodes. I write playbook as follow
- hosts: remote-nodes
tasks:
- name: Execute script
script: /home/ubuntu/FastBFT_ethereum/experiment/a.sh
remote nodes a.sh as follow
#!/usr/bin/env bash
echo "test">> test.txt
python writejson.py
But when I check the test.text, I find it doesn't work in remote nodes.help me please.
Assuming that you want test.txt to be created in the experiment directory, this should be changed to something like:
- hosts: remote-nodes
tasks:
- name: Execute script
script: /home/ubuntu/FastBFT_ethereum/experiment/a.sh
args:
chdir: /home/ubuntu/FastBFT_ethereum/experiment

Unable to run bashrc file using ansible

Unable to run bashrc file using ansible.
- name: Source Bashrc
action: shell source /local/apps/actional/.bash_profile
is not working.
source is a build-in, not command.
Try this:
---
- hosts: target-server
gather_facts: no
tasks:
- copy:
content: export MYVAR=123
dest: /tmp/source_test
- shell: /bin/bash -c 'source /tmp/source_test; echo $MYVAR'
Keep in mind that you can use sourced environment only within one Ansible task – each task is executed in new shell.

How to execute a shell script on a remote server using Ansible?

I am planning to execute a shell script on a remote server using Ansible playbook.
blank test.sh file:
touch test.sh
Playbook:
---
- name: Transfer and execute a script.
hosts: server
user: test_user
sudo: yes
tasks:
- name: Transfer the script
copy: src=test.sh dest=/home/test_user mode=0777
- name: Execute the script
local_action: command sudo sh /home/test_user/test.sh
When I run the playbook, the transfer successfully occurs but the script is not executed.
you can use script module
Example
- name: Transfer and execute a script.
hosts: all
tasks:
- name: Copy and Execute the script
script: /home/user/userScript.sh
local_action runs the command on the local server, not on the servers you specify in hosts parameter.
Change your "Execute the script" task to
- name: Execute the script
command: sh /home/test_user/test.sh
and it should do it.
You don't need to repeat sudo in the command line because you have defined it already in the playbook.
According to Ansible Intro to Playbooks user parameter was renamed to remote_user in Ansible 1.4 so you should change it, too
remote_user: test_user
So, the playbook will become:
---
- name: Transfer and execute a script.
hosts: server
remote_user: test_user
sudo: yes
tasks:
- name: Transfer the script
copy: src=test.sh dest=/home/test_user mode=0777
- name: Execute the script
command: sh /home/test_user/test.sh
It's better to use script module for that:
http://docs.ansible.com/script_module.html
For someone wants an ad-hoc command
ansible group_or_hostname -m script -a "/home/user/userScript.sh"
or use relative path
ansible group_or_hostname -m script -a "userScript.sh"
Contrary to all the other answers and comments, there are some downsides to using the script module. Especially when you are running it on a remote(not localhost) host. Here is a snippet from the official ansible documentation:
It is usually preferable to write Ansible modules rather than pushing
scripts. Convert your script to an Ansible module for bonus points!
The ssh connection plugin will force pseudo-tty allocation via -tt
when scripts are executed. Pseudo-ttys do not have a stderr channel
and all stderr is sent to stdout. If you depend on separated stdout
and stderr result keys, please switch to a copy+command set of tasks
instead of using script.
If the path to the local script contains spaces, it needs to be
quoted.
This module is also supported for Windows targets.
For example, run this script using script module for any host other than localhost and notice the stdout and stderr of the script.
#!/bin/bash
echo "Hello from the script"
nonoexistingcommand
echo "hello again"
You will get something like the below; notice the stdout has all the stderr merged.(ideally line 6: nonoexistingcommand: command not found should be in stderr) So, if you are searching for some substring in stdout in the script output. you may get incorrect results.:
ok: [192.168.122.83] => {
"script_out": {
"changed": true,
"failed": false,
"rc": 0,
"stderr": "Shared connection to 192.168.122.83 closed.\r\n",
"stderr_lines": [
"Shared connection to 192.168.122.83 closed."
],
"stdout": "Hello from the script\r\n/home/ps/.ansible/tmp/ansible-tmp-1660578527.4335434-35162-230921807808160/my_script.sh: line 6: nonoexistingcommand: command not found\r\nhello again\r\n",
"stdout_lines": [
"Hello from the script",
"/home/ps/.ansible/tmp/ansible-tmp-1660578527.4335434-35162-230921807808160/my_script.sh: line 6: nonoexistingcommand: command not found",
"hello again"
]
}
}
The documentation is not encouraging users to use the script module; consider converting your script into an ansible module; here is a simple post by me that explains how to convert your script into an ansible module.
You can use template module to copy if script exists on local machine to remote machine and execute it.
- name: Copy script from local to remote machine
hosts: remote_machine
tasks:
- name: Copy script to remote_machine
template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
- name: Execute script on remote_machine
script: sh <remote_machine path>/script.sh
Since nothing is defined about "the script", means complexity, content, runtime, runtime environment, size, tasks to perform, etc. are unknown, it might be possible to use an unrecommended approach like in "How to copy content provided in command prompt with special chars in a file using Ansible?"
---
- hosts: test
become: false
gather_facts: false
tasks:
- name: Exec sh script on Remote Node
shell:
cmd: |
date
ps -ef | grep ssh
echo "That's all folks"
register: result
- name: Show result
debug:
msg: "{{ result.stdout }}"
which is a multi-line shell command only (annot.: ... just inline code) and resulting into an output of
TASK [Show result] ****************************************************
ok: [test.example.com] =>
msg: |-
Sat Sep 3 21:00:00 CEST 2022
root 709 1 0 Aug11 ? 00:00:00 /usr/sbin/sshd -D
root 123456 709 14 21:00 ? 00:00:00 sshd: user [priv]
user 123456 123456 1 21:00 ? 00:00:00 sshd: user#pts/0
root 123456 123456 0 21:00 pts/0 00:00:00 grep ssh
That's all folks
One could just add more lines, complexity, necessary output, etc.
Because of script module – Runs a local script on a remote node after transferring it - Notes
It is usually preferable to write Ansible modules rather than pushing scripts.
I also recommend to get familar with writing an own module and as already mentioned in the answer of P....
You can execute local scripts at ansible without having to transfer the file to the remote server, this way:
ansible my_remote_server -m shell -a "`cat /localpath/to/script.sh`"

Resources