REQUIREMENT:
Write an ansible script ,that will
1. Copy the script collect_info.sh to all the hosts.
1. Run the shell script ( collect_info.sh ) , against the hosts mentioned in host file.
2. Script will be run as root user.
3. The output file of the script ( will be like collect*txt) need to be copied to local host.
Below is the ansible playbook script:
cat collect_info.yml
– hosts: all
strategy: free
user: bvunix
become: yes
become_method: sudo
become_user: root
tasks:
– name: Copy script collect_audit.sh
copy: src=collect_audit.sh dest=/home/bvunix mode=0777
– name: Run script for audit
command: sh /home/bvunix/collect_audit.sh
– name: find the output file
shell: (cd /home/bvunix; find collect*.txt)
register: files_to_copy
– debug:
var: files_to_copy
– name: Fetch the file from remote to local
fetch: src=/home/bvunix/{{ item }} dest=/home/bvunix/ mode=0777 flat=yes
with_items: “{{ files_to_copy.stdout_lines }}”
– Execute the playbook
Ansible-playbook collect_info.yml -f 10
-HOSTFILE :
— If password less ssh connectivity is established, then use the below simple hostfile
172.20.192.1
172.20.192.2
172.20.192.3
— If no passwordless ssh setup is there, then hardcode the credentials as below:
linux1 ansible_host=172.20.192.1 ansible_connection=ssh ansible_user=bvunix ansible_ssh_pass=classic123
linux2 ansible_host=172.20.192.3 ansible_connection=ssh ansible_user=bvunix ansible_ssh_pass=classic123
linux3 ansible_host=172.20.192.3 ansible_connection=ssh ansible_user=bvunix ansible_ssh_pass=classic123
In the later tutorial, we will explain how to use ansible-vault to encrypt the host file.
You should could use ansible.builtin.script, register the output to a var, and after that task is completed a new play that saves the output to a file on your local (control host) machine … instead of the multi-step process you have going on here. The ansible authors have said again and again that using “shell” or “command” is **VERY** costly and slows down your plays by a huge factor.
Just because you might be a dev and only have a lab to play with doesn’t mean you shouldn’t be coding to best-practices/standards. This is abhorrent in operations with thousands of servers.
Also, putting passwords to remote machines in static files is a huge security risk. Use -P to have ansible-playbook ask you for password once at beginning of play.
Thanks for your feedback . I will try to implement the builin.script component in this script.
Hello,
Someone please help me, I want to extract the hostname of a remote machine in task1 and use that hostname as targetted host in task2 in one ansible playbook.
Thank you.