Running Local Commands in Ansible
In certain scenarios, you may need to execute commands directly on the Ansible controller node. This can be particularly useful when you want to perform tasks like checking out code from a private git repository and then deploying it to an external production server.
Scenario Overview
Imagine you have a git server that is only accessible within your company’s firewall. You want to check out the code from this server, create a tarball of the checked-out code, and then upload it to a production server that is accessible over the internet. Instead of running separate scripts for each of these tasks, you can integrate them into an Ansible playbook.
Ansible Playbook Example
Here’s how you can structure your Ansible playbook to achieve this:
---
- name: Checkout code and deploy to production
hosts: localhost
connection: local
tasks:
- name: Checkout the git repository
git:
repo: 'git://internal.git.server/path/to/repo.git'
dest: '/tmp/my_project'
- name: Create a tarball of the checked-out code
command: tar -czf /tmp/my_project.tar.gz -C /tmp/my_project .
- name: Upload the tarball to the production server
copy:
src: /tmp/my_project.tar.gz
dest: /path/on/production/server/my_project.tar.gz
remote_src: yes
- name: Clean up local tarball
file:
path: /tmp/my_project.tar.gz
state: absent
Explanation of the Playbook
- hosts: localhost: This specifies that the playbook will run on the Ansible controller node.
- connection: local: This indicates that the tasks will be executed locally rather than on a remote host.
- git module: This checks out the code from the specified git repository into a local directory.
- command module: This creates a tarball of the checked-out code.
- copy module: This uploads the tarball to the specified path on the production server.
- file module: This cleans up the local tarball after the upload is complete.
Conclusion
By using Ansible to manage these tasks, you can streamline your deployment process and reduce the need for separate scripts. This approach not only saves time but also ensures consistency in your deployment workflow.