Description: Here I have explained, what is Ansible Variable and how to use Variable in the playbook
What is Ansible Variable
Ansible supports variables that can be used to store values that can then be reused throughout files in an Ansible project. This can simplify the creation and maintenance of a project and reduce the number of errors
Example: Here I have created a playbook to install different services and start them using variables. Below is the playbook for the same
In this example I have created below variables
web_pkg: httpd
firewall_pkg: firewalld
web_service: httpd
firewall_service: firewalld service
python_pkg: python3-PyMySQL
rule: http
--- - name: Deploy and start Apache HTTPD service hosts: webserver vars: web_pkg: httpd firewall_pkg: firewalld web_service: httpd firewall_service: firewalld rule: http tasks: - name: Required packages are installed and up to date yum: name: - "{{ web_pkg }}" - "{{ firewall_pkg }}" state: latest - name: The {{ firewall_service }} service is started and enabled service: name: "{{ firewall_service }}" enabled: true state: started - name: The {{ web_service }} service is started and enabled service: name: "{{ web_service }}" enabled: true state: started - name: Web content is in place copy: content: "This is test Webserver" dest: /var/www/html/index.html - name: The firewall port for {{ rule }} is open firewalld: service: "{{ rule }}" permanent: true immediate: true state: enabled - name: Verify the Apache service hosts: localhost become: false tasks: - name: Ensure the webserver is reachable uri: url: http://testwebserver.local status_code: 200
- Now run playbook using below command
- You can also browse URL and verify
No comments:
Post a Comment