What can be done if the module is not available?
Scenario: You want to automate certain deployment and couldn’t find the module for the command
If the module is not found, then ansible gives provision to directly run the linux/windows commands using command modules. But these modules are not idempotent. Ensuring idempotence is your responsibility
In Ansible we have following command modules Refer Here
- command: Execute command on targets
- expect: Executes a command & respond to prompts
- psexec: Runs commands on a remote Windows host based on PSExec model
- raw: Executes a low level command on machines where python is not installed.
- shell: Executes the shell command on nodes
- script: Executes a local script on remote node after transferring it.
- telnet: Executes a low level telnet command
Lets write a very simple playbook with command modules
--- - name: execute commands hosts: all tasks: - name: execute simple shell command shell: cmd: touch test.txt chdir: /home/ansible
- Now execute this twice and we can observe there is no idempotance by ansible since we used command modules
- One approach for making this idempotent is check if file exists and if the file doesnot exist then execute the task
- Now lets change the playbook to
--- - name: execute commands hosts: all tasks: - name: check for file existence stat: path: /home/ansible/test.txt register: stat_result - name: execute simple shell command shell: cmd: touch test.txt chdir: /home/ansible when: not stat_result.stat.exists
- Now execute the ansible playbook again
- How to make the commands which donot create a file idempotent
--- - name: execute commands hosts: all tasks: - name: check for file existence stat: path: /home/ansible/.pingexecution register: stat_result - name: execute simple shell command shell: cmd: ping -c 4 google.com when: not stat_result.stat.exists notify: - store ping execution handlers: - name: store ping execution file: path: /home/ansible/.pingexecution state: touch
- During the execution of playbook if i need to set the variable value for usage at the host level we have a module called as set_fact
Reusing others work
- Scenario: I have been asked to install mysql on centos and ubuntu nodes.
- Solution: Write your own ansible playbook or since we are not the first people to try mysql execution from ansible we can reuse others work
- Ansible makes it possible to share work(playbooks/roles/collection) done by users to community using Ansible-Galaxy
- Now lets search mysql in ansible galaxy
- We should understand how to reuse work shared by others i.e. understanding roles and collections.