Ansible provides modules to copy files, deploy configurations, and execute scripts on remote machines.
This guide covers:
- name: Copy configuration file to target machines
hosts: all
tasks:
- name: Copy nginx config file
copy:
src: ./files/nginx.conf # Path to the config file on the Ansible control node
dest: /etc/nginx/nginx.conf # Destination path on the target machine
owner: root
group: root
mode: '0644'
notify: Restart nginx # Triggers a handler to restart nginx if the file changes
handlers:
- name: Restart nginx
service:
name: nginx
state: restarted
πΉ Key Points:
copy module transfers a file from the control node to managed hosts.notify directive calls a handler only when the file changes.- name: Copy and execute a script
hosts: all
tasks:
- name: Copy a setup script to remote servers
copy:
src: ./scripts/setup.sh # Local script path
dest: /tmp/setup.sh # Remote destination
mode: '0755' # Ensure the script is executable
- name: Execute the setup script
command: /tmp/setup.sh
register: script_output
- name: Show script output
debug:
msg: "{{ script_output.stdout }}"
πΉ Key Points:
mode: '0755' ensures it is executable.register and displayed with debug.- name: Execute a script directly on remote servers
hosts: all
tasks:
- name: Run a shell command remotely
shell: |
echo "Updating system..."
sudo apt update && sudo apt upgrade -y
πΉ Key Points:
shell or command to run a script directly without copying.shell unless necessary (e.g., using pipes |, redirections >, or multiple commands).β
Use copy for config files and scripts.
β
Use notify to restart services when configs change.
β
Use command or shell for direct execution.
π Next: Collecting logs and files from remote machines!