├── .DS_Store
├── Ansible Code Reuse - Ansible Roles and Collections
├── Roles_example.yml
├── collections_example.yml
├── collections_requirements.yml
└── roles_requirements.yml
├── Ansible Inventories
├── Work with Dynamic Inventory Script AWS
│ ├── ansible.cfg
│ └── demo.aws_ec2.yml
└── Work with Dynamic Inventory Script Google Cloud
│ └── demo.gcp.yml
├── Ansible Machine Specific Execution
├── delegate_to.yml
└── local_action.yml
├── Ansible Playbooks For Linux : Practical Labs
├── blockinfile_example.yml
├── copy_example.yml
├── cron_example.yml
├── fetch_example.yml
├── git_example.yml
├── lineinfile_example.yml
├── loops_template_example.yml
├── nginx.conf
├── reboot_example.yml
├── sample.conf
├── service_facts_example.yml
├── slurp_example.yml
├── template_example.yml
└── templates
│ ├── nginx.conf.j2
│ ├── sample_inventory.cfg
│ └── vhost.j2
├── Ansible with Docker Containers
├── Building Docker Images with Ansible
│ ├── myapp
│ │ ├── app.py
│ │ ├── dockerfile
│ │ └── requirements.txt
│ └── playbook.yml
├── Install Docker Using Ansible
├── Managing Docker Containers with Ansible
└── Networking and Storage for Docker Container
├── Ansible with Kubernetes
├── Deploy Application Workload
│ ├── Deploy Application via Ansible
│ └── Deploy using Kubernetes Config
│ │ ├── Ansible Playbook
│ │ ├── Ansible Playbook copy
│ │ ├── nginx-deployment.yaml
│ │ └── nginx-service.yaml
├── Introduction to Kubernetes and Ansible Integration
│ ├── Access Managed K8s Cluster
│ ├── Configure and Install Kubectl
│ └── Install Cloud CLI for K8s Cluster
└── Monitoring and Scaling Kubernetes with Ansible Dir
│ ├── Ansible Playbook
│ ├── Install HELM
│ └── prometheus.yaml
├── Ansible_Tips_and_Tricks_Practical_Demos
├── ansible_command_shell_module.yml
├── ansible_date_strftime_filtter.yml
├── ansible_date_time_format.yml
├── ansible_dry_run.yml
├── ansible_pause.yml
├── environment_varaible.yml
├── execute_script_on_remote_machine.yml
├── execution_on_ansible_host.yml
├── hello_world.py
├── inventory_ansible_hostname.yml
└── pass_variable.yml
├── Basic Concepts of Ansible PlayBooks
├── ansible_datacollection.yml
├── ansible_debug.yml
├── ansible_var.yml
├── arithmetic_operations.yml
├── filter_methods_ansible.yml
├── pratice_arithmetic.yml
└── register_ansible.yml
├── Basic of Ansible Playbook
├── Install_https.yml
└── intro_playbook.yml
├── Concept of Template in Ansible
├── index.html.j2
├── install_httpd.yml
├── install_tomcat.yml
└── server.xml.j2
├── Error Handling in Ansible
├── block_ansible.yml
├── demo_block_rescue.yml
├── error_handling_1.yml
├── rescue_block.yml
└── vsftpd.j2
├── Handlers in Ansible
├── handler_imp.yml
└── handler_req.yml
├── Interact with Web Service APIs using Ansible
├── Submit a GET request to a REST API Endpoint
└── Token Based Authentication in REST API
├── Loops in Ansible Playbook
├── loops_example.yml
├── loops_exampleII.yml
└── loops_exampleIII.yml
├── Manage Remote Machine File System via Ansible
├── Managefile_example1.yml
├── Managefile_example2.yml
├── archive_example.yml
├── downloadfile_example.yml
├── hardlink_example.yml
└── symlink_example.yml
├── Operators and Conditional Statement in Ansible Playbook
├── comparision_operator.yml
├── condition_statement.yml
├── install_webserver.yml
├── logical_operator.yml
└── memebership_tests.yml
├── README.md
├── Secure Your Infra : Ansible Vault
├── secrets.yml
└── use_secrets.yml
├── Tags in Ansible
└── tags_ansible.yml
├── Working with include and import module in Ansible
├── import_playbook.yml
├── include_playbook.yml
├── include_tasks.yml
├── include_tasks_module.yml
├── play2.yml
└── tasks-1.yml
└── ansible_automation.code-workspace
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/anshulc55/ansible_automation/9306e33ce3ff7257a574fb65095f59eec8dd4d36/.DS_Store
--------------------------------------------------------------------------------
/Ansible Code Reuse - Ansible Roles and Collections/Roles_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Install, configure, and verify Nginx and MySQL
3 | hosts: webservers
4 | become: yes
5 | roles:
6 | - geerlingguy.nginx
7 | - geerlingguy.mysql
8 | # Roles installed via Requirement.txt
9 |
10 | tasks:
11 | - name: Verify Nginx is installed
12 | command: nginx -v
13 | register: nginx_version
14 | ignore_errors: yes
15 |
16 | - name: Check Nginx installation
17 | debug:
18 | msg: "Nginx version: {{ nginx_version.stderr }}"
19 | when: nginx_version.rc == 0
20 | # displays the Nginx version if the previous command succeeds
21 |
22 | - name: Verify Nginx service is running
23 | systemd:
24 | name: nginx
25 | state: started
26 | register: nginx_service
27 | ignore_errors: yes
28 |
29 | - name: Check Nginx service status
30 | debug:
31 | msg: "Nginx service is running"
32 | when: nginx_service.state == 'started'
33 | # confirms the service status if it is in the 'started' state.
34 |
35 | - name: Verify MySQL is installed
36 | command: mysql --version
37 | register: mysql_version
38 | ignore_errors: yes
39 |
40 | - name: Check MySQL installation
41 | debug:
42 | msg: "MySQL version: {{ mysql_version.stdout }}"
43 | when: mysql_version.rc == 0
44 | # displays the MySQL version if the previous command succeeds
45 |
46 | - name: Verify MySQL service is running
47 | systemd:
48 | name: mysql
49 | state: started
50 | register: mysql_service
51 | ignore_errors: yes
52 |
53 | - name: Check MySQL service status
54 | debug:
55 | msg: "MySQL service is running"
56 | when: mysql_service.state == 'started'
57 | # task confirms the service status if it is in the 'started' state.
58 |
--------------------------------------------------------------------------------
/Ansible Code Reuse - Ansible Roles and Collections/collections_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Use community.general collection on Ubuntu
3 | hosts: webservers
4 | become: yes # Required for package installation
5 |
6 | tasks:
7 | - name: Display system information
8 | community.general.content:
9 | # Direct module parameters without variables
10 | path: /etc/os-release
11 | register: content_output
12 |
13 | - name: Print OS name and version
14 | debug:
15 | msg: "OS Name: {{ content_output.stdout.split('=')[1].strip() }}\nOS Version: {{ content_output.stdout.split('=')[1].split()[0] }}"
16 |
17 | - name: Download content from URL
18 | community.general.content:
19 | src: https://raw.githubusercontent.com/ansible/ansible/devel/docsite/en_US/intro/getting_started.rst
20 | dest: /tmp/getting_started.rst
21 | mode: 0644 # Set file permissions
22 |
23 |
24 |
25 | - name: Install Docker and run Nginx container
26 | hosts: webservers
27 | become: yes
28 | tasks:
29 | - name: Install Docker
30 | community.general.package:
31 | name: docker.io
32 | state: present
33 | # module to install Docker
34 |
35 | - name: Ensure Docker service is started
36 | service:
37 | name: docker
38 | state: started
39 | enabled: yes
40 | # Ensure the Docker service is started and enabled to manage Docker containers.
41 |
42 | - name: Run Nginx container
43 | community.docker.docker_container:
44 | name: nginx-1.1
45 | image: nginx
46 | ports:
47 | - "80:80"
48 | state: started
49 | # module to run an Nginx container named nginx
50 |
51 | - name: Verify Nginx container status
52 | community.docker.docker_container_info:
53 | name: nginx-1.1
54 | register: nginx_container_info
55 |
56 | - name: Check if Nginx container is running
57 | assert:
58 | that:
59 | - nginx_container_info.State == 'running'
60 |
61 | - name: Verify connection to Nginx
62 | uri:
63 | url: "http://localhost:80"
64 | status_code: 200
65 | register: nginx_response
66 |
67 | - name: Print Nginx response
68 | debug:
69 | var: nginx_response
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/Ansible Code Reuse - Ansible Roles and Collections/collections_requirements.yml:
--------------------------------------------------------------------------------
1 | ---
2 | collections:
3 | - name: community.general
4 | - name: ansible.posix
5 | - name: community.docker
--------------------------------------------------------------------------------
/Ansible Code Reuse - Ansible Roles and Collections/roles_requirements.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - src: geerlingguy.nginx
3 | version: 3.2.0 # Specify the version if needed
4 |
5 | - src: geerlingguy.mysql
6 | version: 4.3.4
7 |
8 | # ansible-galaxy install -r requirements.yml
9 |
10 | # Check that the roles have been installed in the appropriate
11 | # directory (typically ~/.ansible/roles or /etc/ansible/roles).
--------------------------------------------------------------------------------
/Ansible Inventories/Work with Dynamic Inventory Script AWS/ansible.cfg:
--------------------------------------------------------------------------------
1 | [defaults]
2 | host_key_checking = False
3 | inventory = /root/ansible/inventory/dev/dev_host
4 |
5 | [inventory]
6 | enable_plugins = host_list, script, auto, yaml, ini, toml
--------------------------------------------------------------------------------
/Ansible Inventories/Work with Dynamic Inventory Script AWS/demo.aws_ec2.yml:
--------------------------------------------------------------------------------
1 | plugin: amazon.aws.aws_ec2
2 | filters:
3 | instance-state-name: running
--------------------------------------------------------------------------------
/Ansible Inventories/Work with Dynamic Inventory Script Google Cloud/demo.gcp.yml:
--------------------------------------------------------------------------------
1 | plugin: gcp_compute
2 | projects:
3 | - velvety-castle-269006
4 | auth_kind: serviceaccount
5 | service_account_file: /root/ansible/ansible-gcp-service-account.json
6 | keyed_groups:
7 | - key: labels
8 | prefix: label
9 | - key: zone
10 | prefix: zone
--------------------------------------------------------------------------------
/Ansible Machine Specific Execution/delegate_to.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playboo
2 |
3 | - name: Ansible Delegate_to examples
4 | hosts: all
5 | remote_user: ec2-user
6 | become: 'yes'
7 | become_user: root
8 |
9 | vars:
10 | tmplog: /tmp/connection.log
11 |
12 | tasks:
13 | - name: create tmplog
14 | shell: test ! -f {{ tmplog }} && touch {{ tmplog }}
15 | failed_when: false
16 |
17 | - name: delegate_to
18 | shell: echo "delegate_to . {{ inventory_hostname }} $(hostname) ." >> {{ tmplog }}
19 | delegate_to: ec2-13-59-156-142.us-east-2.compute.amazonaws.com
--------------------------------------------------------------------------------
/Ansible Machine Specific Execution/local_action.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Local Action in Ansible
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | tasks:
9 | - name: This will create a local file /tmp/local_file.ini
10 | local_action: command touch /tmp/"{{ ansible_hostname }}"_local_file.ini
11 |
12 | - name: Here we copy the local file to remote
13 | copy:
14 | src: /tmp/{{ ansible_hostname }}_local_file.ini
15 | dest: /var/tmp/
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/blockinfile_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Manage Nginx Configuration File
3 | hosts: localhost
4 | tasks:
5 | - name: Add a new block of text after a marker
6 | blockinfile:
7 | path: /etc/nginx/nginx.conf
8 | marker: "# START OF NEW BLOCK"
9 | block: |
10 | # New block of text
11 | location /api {
12 | proxy_pass http://backend_servers;
13 | proxy_set_header Host $host;
14 | proxy_set_header X-Real-IP $remote_addr;
15 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
16 | }
17 | register: block_result
18 |
19 | - name: Print the blockinfile result
20 | debug:
21 | var: block_result
22 |
23 | - name: Replace a block of text between markers
24 | blockinfile:
25 | path: /etc/nginx/nginx.conf
26 | marker: "# START OF NEW BLOCK"
27 | block: |
28 | # Updated block of text
29 | location /api {
30 | proxy_pass http://new_backend_servers;
31 | proxy_set_header Host $host;
32 | proxy_set_header X-Real-IP $remote_addr;
33 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
34 | }
35 | when: "'# START OF NEW BLOCK' in block_result.changed"
36 |
37 | - name: Remove a block of text between markers
38 | blockinfile:
39 | path: /etc/nginx/nginx.conf
40 | marker: "# START OF NEW BLOCK"
41 | state: absent
42 | when: "'# START OF NEW BLOCK' in block_result.changed"
43 |
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/copy_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Copy nginx.conf to remote host
3 | hosts: all
4 | tasks:
5 | - name: Copy nginx.conf
6 | copy:
7 | src: /etc/nginx/nginx.conf # Local path of the file
8 | dest: /root/ansible/nginx.conf # Destination path on remote host
9 | owner: root
10 | group: root
11 | mode: '0644'
12 | become: yes
13 |
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/cron_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Schedule a weekly log cleanup
3 | hosts: all
4 | become: yes
5 |
6 | tasks:
7 | - name: Ensure the log cleanup script exists
8 | copy:
9 | src: cleanup_logs.sh
10 | dest: /usr/local/bin/cleanup_logs.sh
11 | mode: '0755'
12 |
13 | # Every Monday at 3:30 AM
14 | - name: Schedule a weekly log cleanup
15 | cron:
16 | name: "Weekly Log Cleanup"
17 | minute: "30"
18 | hour: "3"
19 | day: "*"
20 | month: "*"
21 | weekday: "1"
22 | job: "/usr/local/bin/cleanup_logs.sh"
23 | user: "root"
24 |
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/fetch_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Generate example logs on remote hosts
3 | hosts: all
4 | tasks:
5 | - name: Create log directory if it doesn't exist
6 | file:
7 | path: /var/log/
8 | state: directory
9 |
10 | - name: Generate example log file
11 | ansible.builtin.shell: |
12 | echo "This is a sample log file." > /var/log/example.log
13 |
14 | ---
15 | - name: Fetch example logs from remote hosts
16 | hosts: all
17 | tasks:
18 | - name: Fetch example log file from remote host
19 | fetch:
20 | src: /var/log/example.log
21 | dest: /tmp/logs/
22 | flat: no
23 |
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/git_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Clone GitHub repository and perform tasks
3 | hosts: all
4 | become: yes
5 | tasks:
6 | - name: Ensure Git is installed
7 | ansible.builtin.package:
8 | name: git
9 | state: present
10 |
11 | - name: Clone the GitHub repository
12 | ansible.builtin.git:
13 | repo: https://github.com/ansible/ansible-examples.git
14 | dest: /tmp/ansible-examples
15 | update: yes
16 | version: master
17 |
18 | - name: Print the contents of a file from the repository
19 | ansible.builtin.shell: cat /tmp/ansible-examples/README.md
20 | register: readme_contents
21 |
22 | - name: Display the contents of the file
23 | debug:
24 | msg: "{{ readme_contents.stdout }}"
25 |
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/lineinfile_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Manage lines in a text file
3 | hosts: localhost
4 | tasks:
5 | - name: Ensure the file exists
6 | file:
7 | path: sample.conf
8 | state: touch
9 |
10 | - name: Add a line if it doesn't exist
11 | lineinfile:
12 | path: sample.conf
13 | line: 'timeout 60'
14 | insertafter: '^port'
15 | state: present
16 |
17 | - name: Replace a line if it exists
18 | lineinfile:
19 | path: sample.conf
20 | regexp: '^ssl_enabled.*'
21 | line: 'ssl_enabled false'
22 |
23 | - name: Add a line at the beginning of the file
24 | lineinfile:
25 | path: sample.conf
26 | line: '# This is a comment'
27 | insertbefore: BOF
28 |
29 | - name: Read file content using cat
30 | command: cat sample.conf
31 | register: file_content
32 |
33 | - name: Print file content
34 | debug:
35 | msg: "{{ file_content.stdout }}"
36 |
37 | - name: Remove a line if it exists
38 | lineinfile:
39 | path: sample.conf
40 | state: absent
41 | regexp: '^server_name.*'
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/loops_template_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Install and configure Nginx with dynamic server_name
3 | hosts: webservers
4 | become: yes # Ensure the tasks run with root privileges
5 | vars:
6 | nginx_servers:
7 | - { server_name: '{{ ansible_hostname }}', port: 80, proxy_pass: 'backend1' }
8 | - { server_name: '{{ ansible_hostname }}', port: 80, proxy_pass: 'backend2' }
9 | - { server_name: '{{ ansible_hostname }}', port: 80, proxy_pass: 'backend3' }
10 | - { server_name: '{{ ansible_hostname }}', port: 80, proxy_pass: 'backend4' }
11 | tasks:
12 | - name: Ensure Nginx is installed
13 | apt:
14 | name: nginx
15 | state: present
16 | when: ansible_os_family == "Debian"
17 |
18 | - name: Create Nginx configuration from template
19 | template:
20 | src: nginx.conf.j2
21 | dest: /etc/nginx/nginx.conf
22 | notify:
23 | - reload nginx
24 |
25 | - name: Ensure Nginx is running and enabled
26 | service:
27 | name: nginx
28 | state: started
29 | enabled: yes
30 | when: ansible_os_family == "Debian"
31 |
32 | handlers:
33 | - name: reload nginx
34 | service:
35 | name: nginx
36 | state: reloaded
37 | when: ansible_os_family == "Debian"
38 |
39 | # Template content: nginx.conf.j2
40 |
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/nginx.conf:
--------------------------------------------------------------------------------
1 | user nginx;
2 | worker_processes 1;
3 |
4 | error_log /var/log/nginx/error.log warn;
5 | pid /var/run/nginx.pid;
6 |
7 | events {
8 | worker_connections 1024;
9 | }
10 |
11 | http {
12 | include /etc/nginx/mime.types;
13 | default_type application/octet-stream;
14 |
15 | log_format main '$remote_addr - $remote_user [$time_local] "$request" '
16 | '$status $body_bytes_sent "$http_referer" '
17 | '"$http_user_agent" "$http_x_forwarded_for"';
18 |
19 | access_log /var/log/nginx/access.log main;
20 |
21 | sendfile on;
22 | #tcp_nopush on;
23 |
24 | keepalive_timeout 65;
25 |
26 | #gzip on;
27 |
28 | include /etc/nginx/conf.d/*.conf;
29 |
30 | server {
31 | listen 80;
32 | server_name localhost;
33 |
34 | # Sample location block for serving static files
35 | location / {
36 | root /usr/share/nginx/html;
37 | index index.html index.htm;
38 | }
39 |
40 | # This is where the playbook will add or modify blocks
41 | # START OF NEW BLOCK
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/reboot_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Gather and display OS family
3 | hosts: all
4 | gather_facts: yes
5 | tasks:
6 | - name: Display the OS family
7 | debug:
8 | msg: "The OS family is {{ ansible_os_family }}"
9 |
10 |
11 | - name: Reboot Servers Example
12 | hosts: all
13 | become: yes # Ensure that the playbook runs with elevated privileges
14 | tasks:
15 | - name: Apply updates and reboot
16 | block:
17 | - name: Update all packages
18 | apt:
19 | update_cache: yes
20 | upgrade: dist
21 | when: ansible_os_family == 'Debian'
22 |
23 | - name: Reboot the server
24 | reboot:
25 | msg: "Reboot initiated by Ansible for updates"
26 | reboot_timeout: 300
27 | post_reboot_delay: 30
28 |
29 | - name: Ensure the server is up and running
30 | command: uptime
31 | register: uptime_result
32 |
33 | - name: Print uptime
34 | debug:
35 | var: uptime_result.stdout
36 |
37 | when: ansible_os_family == 'Debian' # Adjust this condition as needed for your environment
38 |
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/sample.conf:
--------------------------------------------------------------------------------
1 | # Sample Configuration File
2 | server_name example.com
3 | port 80
4 | ssl_enabled true
5 |
6 |
7 |
8 | # This is a comment
9 | # Sample Configuration File
10 | port 80
11 | timeout 60
12 | ssl_enabled false
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/service_facts_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Install and manage Nginx and Apache services
3 | hosts: all
4 | become: yes
5 | tasks:
6 | - name: Update the apt package index
7 | apt:
8 | update_cache: yes
9 |
10 | - name: Install Nginx
11 | apt:
12 | name: nginx
13 | state: present
14 |
15 | - name: Install Apache
16 | apt:
17 | name: apache2
18 | state: present
19 |
20 | - name: Start and enable Nginx service
21 | service:
22 | name: nginx
23 | state: started
24 | enabled: yes
25 |
26 |
27 | - name: Gather and use service facts
28 | hosts: all
29 | tasks:
30 | - name: Gather service facts
31 | service_facts:
32 |
33 | - name: Print all service facts
34 | debug:
35 | var: ansible_facts.services
36 |
37 | - name: Ensure Nginx service is running
38 | service:
39 | name: nginx
40 | state: started
41 | when: ansible_facts.services['nginx'].state != 'running'
42 |
43 | - name: Ensure Apache service is stopped
44 | service:
45 | name: apache2
46 | state: stopped
47 | when: ansible_facts.services['apache2'].state != 'stopped'
48 |
49 | - name: Print status of Nginx service
50 | debug:
51 | msg: "Nginx is {{ ansible_facts.services['nginx'].state }}"
52 |
53 | - name: Print status of Apache service
54 | debug:
55 | msg: "Apache2 is {{ ansible_facts.services['apache2'].state }}"
56 |
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/slurp_example.yml:
--------------------------------------------------------------------------------
1 | - name: Fetch configuration file from remote server
2 | hosts: webservers
3 | tasks:
4 | - name: Fetch nginx configuration
5 | ansible.builtin.slurp:
6 | src: /etc/nginx/nginx.conf
7 | register: nginx_conf
8 |
9 | - name: Display fetched content
10 | debug:
11 | msg: "Fetched content: {{ nginx_conf.content | b64decode }}"
12 |
13 | # You can further process the content as needed, for example:
14 | - name: Save content to a local file
15 | copy:
16 | content: "{{ nginx_conf.content | b64decode }}"
17 | dest: /tmp/nginx.conf
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/template_example.yml:
--------------------------------------------------------------------------------
1 | - name: Deploy Apache virtual hosts
2 | hosts: webservers
3 | become: yes
4 |
5 | tasks:
6 | - name: Install Apache
7 | yum:
8 | name: httpd
9 | state: present
10 | notify:
11 | - Restart Apache
12 |
13 | - name: Ensure Apache is enabled and started
14 | service:
15 | name: httpd
16 | state: started
17 | enabled: yes
18 |
19 | - name: Deploy virtual host configuration file
20 | template:
21 | src: templates/vhost.j2
22 | dest: /etc/httpd/conf.d/{{ domain }}.conf
23 | notify:
24 | - Restart Apache
25 |
26 | handlers:
27 | - name: Restart Apache
28 | service:
29 | name: httpd
30 | state: restarted
31 |
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/templates/nginx.conf.j2:
--------------------------------------------------------------------------------
1 | worker_processes 1;
2 | events {
3 | worker_connections 1024;
4 | }
5 | http {
6 | {% for server in nginx_servers %}
7 | server {
8 | listen {{ server.port }};
9 | server_name {{ server.server_name }};
10 |
11 | location / {
12 | proxy_pass http://{{ server.proxy_pass }};
13 | proxy_set_header Host $host;
14 | proxy_set_header X-Real-IP $remote_addr;
15 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
16 | proxy_set_header X-Forwarded-Proto $scheme;
17 | }
18 | }
19 | {% endfor %}
20 | }
21 |
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/templates/sample_inventory.cfg:
--------------------------------------------------------------------------------
1 | [webservers]
2 | webserver1.example.com domain=example1.com docroot=/var/www/example1
3 | webserver2.example.com domain=example2.com docroot=/var/www/example2
4 |
5 | [webservers:vars]
6 | error_log=/var/log/httpd/error.log
7 | custom_log=/var/log/httpd/access.log
--------------------------------------------------------------------------------
/Ansible Playbooks For Linux : Practical Labs/templates/vhost.j2:
--------------------------------------------------------------------------------
1 |
2 | ServerAdmin webmaster@{{ domain }}
3 | ServerName {{ domain }}
4 | DocumentRoot {{ docroot }}
5 | ErrorLog {{ error_log }}
6 | CustomLog {{ custom_log }} common
7 |
--------------------------------------------------------------------------------
/Ansible with Docker Containers/Building Docker Images with Ansible/myapp/app.py:
--------------------------------------------------------------------------------
1 | # app.py
2 | from flask import Flask
3 |
4 | app = Flask(__name__)
5 |
6 | @app.route('/')
7 | def hello():
8 | return "Hello, World!"
9 |
10 | if __name__ == "__main__":
11 | app.run(host='0.0.0.0')
--------------------------------------------------------------------------------
/Ansible with Docker Containers/Building Docker Images with Ansible/myapp/dockerfile:
--------------------------------------------------------------------------------
1 | # Dockerfile
2 | FROM python:3.9-slim
3 |
4 | WORKDIR /app
5 | COPY requirements.txt requirements.txt
6 | RUN pip install -r requirements.txt
7 | COPY . .
8 |
9 | CMD ["python", "app.py"]
--------------------------------------------------------------------------------
/Ansible with Docker Containers/Building Docker Images with Ansible/myapp/requirements.txt:
--------------------------------------------------------------------------------
1 | # requirements.txt
2 | Flask==2.0.2
--------------------------------------------------------------------------------
/Ansible with Docker Containers/Building Docker Images with Ansible/playbook.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Build Docker image for Python web app and manage container
3 | hosts: webservers
4 | become: yes
5 |
6 | tasks:
7 |
8 | - name: Copy application files to target machine
9 | copy:
10 | src: ./myapp/
11 | dest: /tmp/myapp/
12 |
13 | - name: Build Docker image
14 | docker_image:
15 | name: my_python_app
16 | build:
17 | path: /tmp/myapp/
18 | tag: latest
19 | # Add source parameter with path to your application directory
20 | source: build
21 |
22 | - name: Remove application files from target machine (optional)
23 | file:
24 | path: /tmp/myapp/
25 | state: absent
26 |
27 | - name: Create Docker container from the built image
28 | docker_container:
29 | name: my_python_container
30 | image: my_python_app:latest
31 | state: started
32 | command: sleep infinity
33 | ports:
34 | - "8080:80" # Example port mapping
35 |
36 | - name: Ensure my_python_container container is running
37 | community.docker.docker_container_info:
38 | name: my_python_container
39 | register: my_python_container_info
40 |
41 | - name: Debug my_python_container container status
42 | debug:
43 | msg: "my_python_container container status: {{ my_python_container_info.container.State.Status }}"
44 |
45 | - name: Stop the container
46 | docker_container:
47 | name: my_python_container
48 | state: stopped
49 |
50 | - name: Remove the container (optional)
51 | docker_container:
52 | name: my_python_container
53 | state: absent
54 |
55 | - name: Show all running containers after termination
56 | command: docker ps --format "{{'{{'}}.Names{{'}}'}}"
57 | register: all_containers_after
58 |
59 | - name: Debug all running containers after termination
60 | debug:
61 | msg: "All running containers after termination: {{ all_containers_after.stdout_lines }}"
--------------------------------------------------------------------------------
/Ansible with Docker Containers/Install Docker Using Ansible:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Install Docker
3 | hosts: webservers
4 | become: yes
5 |
6 | tasks:
7 | - name: Update apt cache
8 | apt:
9 | update_cache: yes
10 | # Update apt cache: Ensures that the local APT package cache is up to date.
11 |
12 | - name: Install packages to allow apt to use a repository over HTTPS
13 | apt:
14 | name: "{{ item }}"
15 | state: present
16 | cache_valid_time: 3600
17 | with_items:
18 | - apt-transport-https
19 | - ca-certificates
20 | - curl
21 | - gnupg
22 | - lsb-release
23 | # Install prerequisite packages: Installs packages required for APT to use repositories over HTTPS,
24 | #which is necessary for Docker's repository.
25 |
26 | - name: Add Docker's official GPG key
27 | apt_key:
28 | url: https://download.docker.com/linux/{{ ansible_distribution|lower }}/gpg
29 | state: present
30 | # Add Docker's GPG key: Adds Docker's official GPG key to ensure the
31 | # integrity and authenticity of the Docker packages.
32 |
33 |
34 | - name: Add Docker APT repository
35 | apt_repository:
36 | repo: deb [arch=amd64] https://download.docker.com/linux/{{ ansible_distribution|lower }} {{ ansible_distribution_release }} stable
37 | state: present
38 |
39 | - name: Install Docker and Docker Compose
40 | apt:
41 | name:
42 | - docker-ce
43 | - docker-ce-cli
44 | - containerd.io
45 | - docker-compose
46 | state: present
47 | # Install Docker and Docker Compose: Installs Docker packages (docker-ce, docker-ce-cli, containerd.io)
48 | # and Docker Compose from the Docker APT repository.
49 |
50 | - name: Ensure Docker service is started and enabled
51 | service:
52 | name: docker
53 | state: started
54 | enabled: yes
55 |
56 | - name: Check Docker service status
57 | command: systemctl status docker --no-pager
58 | register: docker_status
59 | changed_when: false
60 |
61 | - name: Print Docker service status
62 | debug:
63 | msg: "Docker service status: {{ docker_status.stdout }}"
64 | when: docker_status.rc == 0
65 |
--------------------------------------------------------------------------------
/Ansible with Docker Containers/Managing Docker Containers with Ansible:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Manage Docker Containers
3 | hosts: webservers
4 | become: yes
5 |
6 | tasks:
7 |
8 | - name: Start Docker service
9 | service:
10 | name: docker
11 | state: started
12 | enabled: yes
13 |
14 | - name: Pull Nginx image
15 | community.docker.docker_image:
16 | name: nginx
17 | source: pull
18 |
19 | - name: Pull Redis image
20 | community.docker.docker_image:
21 | name: redis
22 | source: pull
23 |
24 | - name: Create and start Nginx container
25 | community.docker.docker_container:
26 | name: nginx_container
27 | image: nginx
28 | state: started
29 | ports:
30 | - "80:80"
31 |
32 | - name: Create and start Redis container
33 | community.docker.docker_container:
34 | name: redis_container
35 | image: redis
36 | state: started
37 | ports:
38 | - "6379:6379"
39 |
40 | - name: Ensure Nginx container is running
41 | community.docker.docker_container_info:
42 | name: nginx_container
43 | register: nginx_info
44 |
45 | - name: Debug Nginx container status
46 | debug:
47 | msg: "Nginx container status: {{ nginx_info.container.State.Status }}"
48 |
49 | - name: Ensure Redis container is running
50 | community.docker.docker_container_info:
51 | name: redis_container
52 | register: redis_info
53 |
54 | - name: Debug Redis container status
55 | debug:
56 | msg: "Redis container status: {{ redis_info.container.State.Status }}"
57 |
58 | - name: Show all running containers before termination
59 | command: docker ps --format "{{'{{'}}.Names{{'}}'}}"
60 | register: all_containers_before
61 |
62 | - name: Debug all running containers before termination
63 | debug:
64 | msg: "All running containers before termination: {{ all_containers_before.stdout_lines }}"
65 |
66 | - name: Terminate Nginx container
67 | community.docker.docker_container:
68 | name: nginx_container
69 | state: absent
70 |
71 | - name: Terminate Redis container
72 | community.docker.docker_container:
73 | name: redis_container
74 | state: absent
75 |
76 | - name: Show all running containers after termination
77 | command: docker ps --format "{{'{{'}}.Names{{'}}'}}"
78 | register: all_containers_after
79 |
80 | - name: Debug all running containers after termination
81 | debug:
82 | msg: "All running containers after termination: {{ all_containers_after.stdout_lines }}"
--------------------------------------------------------------------------------
/Ansible with Docker Containers/Networking and Storage for Docker Container:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Configure Docker Network and Containers
3 | hosts: webservers
4 | become: yes
5 | tasks:
6 |
7 | - name: Terminate all running containers
8 | shell: docker rm -f $(docker ps -aq)
9 | ignore_errors: yes
10 | changed_when: False
11 |
12 | - name: Delete Docker network if it exists
13 | command: docker network rm my_network
14 | ignore_errors: yes
15 | register: network_removal_result
16 | changed_when: network_removal_result.rc == 0
17 |
18 | - name: Create Docker network with specific subnet
19 | command: docker network create --subnet=172.18.0.0/16 my_network
20 | register: network_creation_result
21 | changed_when: "'already exists' not in network_creation_result.stderr"
22 |
23 | - name: Run nginx container with specific IP
24 | docker_container:
25 | name: web_server
26 | image: nginx
27 | state: started
28 | networks:
29 | - name: my_network
30 | ipv4_address: 172.18.0.2
31 | env:
32 | MYSQL_ROOT_PASSWORD: example
33 |
34 | - name: Run MySQL container with specific IP
35 | docker_container:
36 | name: db_server
37 | image: mysql
38 | state: started
39 | networks:
40 | - name: my_network
41 | ipv4_address: 172.18.0.3
42 | env:
43 | MYSQL_ROOT_PASSWORD: example
44 |
45 | - name: Show all running containers before termination
46 | command: docker ps --format "{{'{{'}}.Names{{'}}'}}"
47 | register: all_containers_before
48 |
49 | - name: Debug all running containers before termination
50 | debug:
51 | msg: "All running containers before termination: {{ all_containers_before.stdout_lines }}"
52 |
53 | - name: Terminate all running containers
54 | shell: docker rm -f $(docker ps -aq)
55 | ignore_errors: yes
56 | changed_when: False
57 |
58 | - name: Show all running containers after termination
59 | command: docker ps --format "{{'{{'}}.Names{{'}}'}}"
60 | register: all_containers_after
61 |
62 | - name: Debug all running containers after termination
63 | debug:
64 | msg: "All running containers after termination: {{ all_containers_after.stdout_lines }}"
--------------------------------------------------------------------------------
/Ansible with Kubernetes/Deploy Application Workload/Deploy Application via Ansible:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Deploy Workload to DigitalOcean Managed Kubernetes
3 | hosts: localhost
4 | become: yes
5 | vars:
6 | ansible_python_interpreter: "/root/ansible/myansible/bin/python"
7 |
8 | tasks:
9 | - name: Ensure Python dependencies are installed
10 | pip:
11 | name: kubernetes
12 | executable: pip3
13 |
14 | - name: Create Namespace
15 | k8s:
16 | state: present
17 | definition:
18 | apiVersion: v1
19 | kind: Namespace
20 | metadata:
21 | name: my-app
22 |
23 | - name: Deploy Nginx Deployment
24 | k8s:
25 | state: present
26 | definition:
27 | apiVersion: apps/v1
28 | kind: Deployment
29 | metadata:
30 | name: nginx-deployment
31 | namespace: my-app
32 | spec:
33 | replicas: 3
34 | selector:
35 | matchLabels:
36 | app: nginx
37 | template:
38 | metadata:
39 | labels:
40 | app: nginx
41 | spec:
42 | containers:
43 | - name: nginx
44 | image: nginx:latest
45 | ports:
46 | - containerPort: 80
47 |
48 | - name: Get the Pods in my-app namespace
49 | kubernetes.core.k8s_info:
50 | api_version: v1
51 | kind: Pod
52 | namespace: my-app
53 | register: pods_info
54 |
55 | - name: Display Pods Info
56 | debug:
57 | msg: "{{ pods_info.resources | map(attribute='metadata.name') | list }}"
--------------------------------------------------------------------------------
/Ansible with Kubernetes/Deploy Application Workload/Deploy using Kubernetes Config/Ansible Playbook:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Deploy Nginx to DigitalOcean Managed Kubernetes
3 | hosts: localhost
4 | become: yes
5 | tasks:
6 | - name: Create Namespace
7 | command: kubectl create namespace my-nginx
8 | ignore_errors: yes
9 |
10 | - name: Deploy Nginx Deployment
11 | command: kubectl apply -f nginx-deployment.yaml
12 |
13 | - name: Expose Nginx Service
14 | command: kubectl apply -f nginx-service.yaml
15 |
16 | - name: Get all pods in my-nginx namespace
17 | command: kubectl get pods -n my-nginx -o jsonpath='{.items[*].metadata.name}'
18 | register: pod_list
19 |
20 | - name: Display pods info
21 | debug:
22 | msg: "Pods: {{ pod_list.stdout.split() }}"
23 |
24 | - name: Get nginx service details
25 | command: kubectl get service nginx-service -n my-nginx -o json
26 | register: service_info
27 |
28 | - name: Display service info
29 | debug:
30 | var: service_info.stdout
--------------------------------------------------------------------------------
/Ansible with Kubernetes/Deploy Application Workload/Deploy using Kubernetes Config/Ansible Playbook copy:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Deploy Nginx to DigitalOcean Managed Kubernetes
3 | hosts: localhost
4 | become: yes
5 | tasks:
6 |
7 | - name: Wait for the service to become available
8 | shell: |
9 | SERVICE_IP=$(kubectl get service nginx-service -n my-nginx -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
10 | if [ -z "$SERVICE_IP" ]; then
11 | SERVICE_IP=$(kubectl get service nginx-service -n my-nginx -o jsonpath='{.spec.clusterIP}')
12 | fi
13 | for i in {1..30}; do
14 | curl -s http://$SERVICE_IP && break || sleep 10
15 | done
16 | register: service_response
17 | retries: 6
18 | delay: 10
19 |
20 | - name: Display service endpoint response
21 | debug:
22 | var: service_response.stdout
--------------------------------------------------------------------------------
/Ansible with Kubernetes/Deploy Application Workload/Deploy using Kubernetes Config/nginx-deployment.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | name: nginx-deployment
5 | namespace: my-nginx
6 | spec:
7 | replicas: 5
8 | selector:
9 | matchLabels:
10 | app: nginx
11 | template:
12 | metadata:
13 | labels:
14 | app: nginx
15 | spec:
16 | containers:
17 | - name: nginx
18 | image: nginx:latest
19 | ports:
20 | - containerPort: 80
21 |
--------------------------------------------------------------------------------
/Ansible with Kubernetes/Deploy Application Workload/Deploy using Kubernetes Config/nginx-service.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: Service
3 | metadata:
4 | name: nginx-service
5 | namespace: my-nginx
6 | spec:
7 | selector:
8 | app: nginx
9 | ports:
10 | - protocol: TCP
11 | port: 80
12 | targetPort: 80
13 |
--------------------------------------------------------------------------------
/Ansible with Kubernetes/Introduction to Kubernetes and Ansible Integration/Access Managed K8s Cluster:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Configure kubectl for DigitalOcean Kubernetes Cluster
3 | hosts: webservers
4 | become: yes
5 | vars:
6 | do_token: "TOKEN"
7 | cluster_name: "k8s-ansible-cluster"
8 |
9 | tasks:
10 | - name: Initialize doctl authentication (if not already authenticated)
11 | command: doctl auth init --access-token {{ do_token }}
12 | args:
13 | creates: ~/.config/doctl/config.yaml # Check if already authenticated
14 | environment:
15 | HOME: "{{ ansible_env.HOME }}"
16 | register: auth_result
17 | changed_when: auth_result.rc != 0
18 |
19 | - name: Set kubectl context for DigitalOcean cluster
20 | command: doctl kubernetes cluster kubeconfig save {{ cluster_name }}
21 | environment:
22 | DOCTL_API_TOKEN: "{{ do_token }}"
23 | when: not auth_result.changed
24 | become: yes
25 |
26 | - name: Verify kubectl configuration
27 | command: kubectl get nodes
28 | register: kubectl_output
29 | become: yes
30 |
31 | - name: Display worker nodes
32 | debug:
33 | msg: "{{ kubectl_output.stdout }}"
34 |
--------------------------------------------------------------------------------
/Ansible with Kubernetes/Introduction to Kubernetes and Ansible Integration/Configure and Install Kubectl:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Configure kubectl for DigitalOcean Kubernetes Cluster
3 | hosts: webservers
4 | become: yes
5 |
6 | tasks:
7 | - name: Ensure /tmp directory exists with correct permissions
8 | ansible.builtin.file:
9 | path: /tmp
10 | state: directory
11 | mode: '1777' # Ensure correct permissions on /tmp
12 | ignore_errors: yes # Ignore errors if /tmp already exists
13 |
14 | - name: Install apt-transport-https, ca-certificates, curl, and gnupg
15 | ansible.builtin.package:
16 | name: "{{ item }}"
17 | state: present
18 | loop:
19 | - apt-transport-https
20 | - ca-certificates
21 | - curl
22 | - gnupg
23 | register: install_packages_result
24 |
25 | - name: Verify packages installation
26 | ansible.builtin.debug:
27 | msg: "Package {{ item.item }} {{ 'installed' if item.changed else 'already installed' }}"
28 | loop: "{{ install_packages_result.results }}"
29 | when: item.changed
30 |
31 | - name: Create /etc/apt/keyrings directory if it doesn't exist
32 | ansible.builtin.file:
33 | path: /etc/apt/keyrings
34 | state: directory
35 | mode: '0755'
36 |
37 | - name: Download Kubernetes APT key and install to /etc/apt/keyrings
38 | ansible.builtin.shell: |
39 | curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.30/deb/Release.key | sudo gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
40 | sudo chmod 644 /etc/apt/keyrings/kubernetes-apt-keyring.gpg
41 | register: download_key_result
42 |
43 | - name: Verify Kubernetes APT key download and installation
44 | ansible.builtin.debug:
45 | msg: "Kubernetes APT key {{ 'downloaded and installed' if download_key_result.rc == 0 else 'not downloaded or installed' }}"
46 | when: download_key_result.rc == 0
47 |
48 | - name: Add Kubernetes apt repository configuration
49 | ansible.builtin.copy:
50 | content: |
51 | deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.30/deb/ /
52 | dest: /etc/apt/sources.list.d/kubernetes.list
53 | owner: root
54 | group: root
55 | mode: '0644'
56 |
57 | - name: Update apt cache
58 | ansible.builtin.apt:
59 | update_cache: yes
60 |
61 | - name: Install kubectl
62 | ansible.builtin.package:
63 | name: kubectl
64 | state: present
65 |
66 | - name: Verify kubectl installation
67 | ansible.builtin.command: kubectl version --client
68 | register: kubectl_version_output
69 |
70 | - name: Display kubectl version
71 | ansible.builtin.debug:
72 | msg: "kubectl version is {{ kubectl_version_output.stdout }}"
73 |
74 | # Optionally, you can add tasks to set up kubeconfig or other configurations
--------------------------------------------------------------------------------
/Ansible with Kubernetes/Introduction to Kubernetes and Ansible Integration/Install Cloud CLI for K8s Cluster:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Install doctl on Unix system
3 | hosts: webservers # Replace with your target host or group of hosts
4 | become: yes # This allows Ansible to escalate privileges if necessary
5 |
6 | tasks:
7 | - name: Ensure unzip is installed (required to extract doctl)
8 | ansible.builtin.package:
9 | name: unzip
10 | state: present
11 |
12 | - name: Download doctl binary from DigitalOcean releases
13 | ansible.builtin.get_url:
14 | url: https://github.com/digitalocean/doctl/releases/download/v1.73.0/doctl-1.73.0-linux-amd64.tar.gz
15 | dest: /tmp/doctl.tar.gz
16 |
17 | - name: Extract doctl binary
18 | ansible.builtin.unarchive:
19 | src: /tmp/doctl.tar.gz
20 | dest: /usr/local/bin
21 | remote_src: yes
22 | notify: Add doctl to PATH
23 |
24 | - name: Verify doctl installation
25 | ansible.builtin.command: doctl version
26 | register: doctl_version_output
27 | ignore_errors: yes
28 |
29 | - name: Debug doctl version output
30 | ansible.builtin.debug:
31 | msg: "doctl version is {{ doctl_version_output.stdout }}"
32 |
33 | handlers:
34 | - name: Add doctl to PATH
35 | ansible.builtin.lineinfile:
36 | path: "{{ ansible_env.HOME }}/.profile"
37 | line: 'export PATH=$PATH:/usr/local/bin'
38 | create: yes
39 | become: yes
40 |
--------------------------------------------------------------------------------
/Ansible with Kubernetes/Monitoring and Scaling Kubernetes with Ansible Dir/Ansible Playbook:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Kubernetes Monitoring and Scaling
3 | hosts: localhost
4 | gather_facts: no
5 | tasks:
6 | - name: Create monitoring namespace
7 | kubernetes.core.k8s:
8 | state: present
9 | definition:
10 | apiVersion: v1
11 | kind: Namespace
12 | metadata:
13 | name: monitoring
14 |
15 | - name: Add Prometheus Community repository
16 | command: helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
17 | ignore_errors: yes
18 | changed_when: false
19 |
20 | - name: Add Grafana repository
21 | command: helm repo add grafana https://grafana.github.io/helm-charts
22 | ignore_errors: yes
23 | changed_when: false
24 |
25 | - name: Update Helm repositories
26 | command: helm repo update
27 | ignore_errors: yes
28 | changed_when: false
29 |
30 | - name: Install Prometheus using Helm
31 | kubernetes.core.helm:
32 | name: prometheus
33 | chart_ref: prometheus-community/kube-prometheus-stack
34 | release_name: prometheus
35 | namespace: monitoring
36 | state: present
37 |
38 | - name: Install Grafana using Helm
39 | kubernetes.core.helm:
40 | name: grafana
41 | chart_ref: grafana/grafana
42 | release_name: grafana
43 | namespace: monitoring
44 | state: present
45 | values:
46 | adminPassword: "yourpassword"
47 | service:
48 | type: LoadBalancer
49 |
50 | - name: Deploy a sample application
51 | kubernetes.core.k8s:
52 | state: present
53 | definition:
54 | apiVersion: apps/v1
55 | kind: Deployment
56 | metadata:
57 | name: sample-app
58 | namespace: default
59 | spec:
60 | replicas: 10
61 | selector:
62 | matchLabels:
63 | app: sample-app
64 | template:
65 | metadata:
66 | labels:
67 | app: sample-app
68 | spec:
69 | containers:
70 | - name: sample-app
71 | image: nginx:latest
72 | ports:
73 | - containerPort: 80
74 |
75 | - name: Define Prometheus scrape_configs
76 | command: kubectl apply -f prometheus.yaml
77 |
78 | - name: Find All Running Services in Monitoring Namespace
79 | command: kubectl get service -n monitoring
80 | register: kubectl_output
81 | changed_when: false
82 |
83 | - name: Display kubectl output
84 | debug:
85 | var: kubectl_output.stdout
--------------------------------------------------------------------------------
/Ansible with Kubernetes/Monitoring and Scaling Kubernetes with Ansible Dir/Install HELM:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Install Helm and Verify Version
3 | hosts: localhost # Assuming running on localhost
4 | become: yes # To elevate privileges with sudo
5 |
6 | tasks:
7 | - name: Add Helm GPG key
8 | shell: curl -fsSL https://baltocdn.com/helm/signing.asc | gpg --dearmor | sudo tee /usr/share/keyrings/helm.gpg > /dev/null
9 |
10 | - name: Install apt-transport-https
11 | apt:
12 | name: apt-transport-https
13 | state: present
14 | become: yes # Ensure sudo privileges for apt installation
15 |
16 | - name: Add Helm repository
17 | blockinfile:
18 | path: /etc/apt/sources.list.d/helm-stable-debian.list
19 | block: |
20 | deb [arch={{ ansible_architecture }} signed-by=/usr/share/keyrings/helm.gpg] https://baltocdn.com/helm/stable/debian/ all main
21 | become: yes # Ensure sudo privileges for file modification
22 |
23 | - name: Update apt cache
24 | apt:
25 | update_cache: yes
26 | become: yes # Ensure sudo privileges for apt update
27 |
28 | - name: Install Helm using script
29 | shell: curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
30 |
31 | - name: Check installed Helm version
32 | command: helm version --short
33 | register: helm_version_output
34 | ignore_errors: yes # Ignore errors temporarily to print message even if helm is not installed
35 |
36 | - debug:
37 | msg: "Installed Helm version: {{ helm_version_output.stdout | default('Helm is not installed') }}"
38 |
--------------------------------------------------------------------------------
/Ansible with Kubernetes/Monitoring and Scaling Kubernetes with Ansible Dir/prometheus.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: ConfigMap
3 | metadata:
4 | name: prometheus-config
5 | namespace: monitoring
6 |
7 | data:
8 | prometheus.yml: |-
9 | global:
10 | scrape_interval: 15s
11 | evaluation_interval: 15s
12 |
13 | scrape_configs:
14 | - job_name: 'kubernetes-nodes'
15 | kubernetes_sd_configs:
16 | - role: node
17 |
18 | - job_name: 'kubernetes-pods'
19 | kubernetes_sd_configs:
20 | - role: pod
21 |
22 | - job_name: 'kubernetes-services'
23 | kubernetes_sd_configs:
24 | - role: service
25 |
--------------------------------------------------------------------------------
/Ansible_Tips_and_Tricks_Practical_Demos/ansible_command_shell_module.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - hosts: all
3 | tasks:
4 | - name: Using command module to list files
5 | command: ls /usr/bin
6 | register: command_output
7 |
8 | - name: Display command output
9 | debug:
10 | msg: "{{ command_output.stdout_lines }}"
11 |
12 | - name: Using shell module to list files and filter with grep
13 | shell: ls /usr/bin | grep 'vim'
14 | register: shell_output
15 |
16 | - name: Display shell output
17 | debug:
18 | var: shell_output.stdout
19 |
20 |
--------------------------------------------------------------------------------
/Ansible_Tips_and_Tricks_Practical_Demos/ansible_date_strftime_filtter.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | # Generating Human-Readable Timestamps
4 | - hosts: all
5 | tasks:
6 | - name: Generate a human-readable timestamp
7 | debug:
8 | msg: "The current time is {{ ansible_date_time.iso8601 | strftime('%A, %B %d, %Y %I:%M %p') }}"
9 |
10 |
11 | # File Naming with Custom Date Formats
12 | - hosts: all
13 | tasks:
14 | - name: Create a file with a custom formatted timestamp
15 | file:
16 | path: "/tmp/file_{{ ansible_date_time.iso8601 | strftime('%Y%m%d_%H%M%S') }}"
17 | state: touch
18 |
19 |
--------------------------------------------------------------------------------
/Ansible_Tips_and_Tricks_Practical_Demos/ansible_date_time_format.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - hosts: all
3 | gather_facts: yes
4 | tasks:
5 | - name: Print Default Ansible date
6 | debug:
7 | msg: "Default date is {{ ansible_date_time }}"
8 |
9 | - name: Print current date
10 | debug:
11 | msg: "Current date is {{ ansible_date_time.date }}"
12 |
13 | - name: Print current time
14 | debug:
15 | msg: "Current time is {{ ansible_date_time.time }}"
16 |
17 | - name: Print current timestamp
18 | debug:
19 | msg: "Current timestamp is {{ ansible_date_time.iso8601 }}"
20 |
21 | - name: Print Unix timestamp
22 | debug:
23 | msg: "Unix timestamp is {{ ansible_date_time.unix }}"
24 |
25 | - name: Create a file with a timestamp
26 | file:
27 | path: "/tmp/file_{{ ansible_date_time.iso8601 | regex_replace(':', '-') }}"
28 | state: touch
29 |
30 |
31 | # Conditional Execution Based on Time
32 | - hosts: all
33 | tasks:
34 | - name: Run task only at night
35 | debug:
36 | msg: "This task runs only at night"
37 | when: ansible_date_time.hour | int >= 20 or ansible_date_time.hour | int < 6
38 |
39 |
--------------------------------------------------------------------------------
/Ansible_Tips_and_Tricks_Practical_Demos/ansible_dry_run.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - hosts: all
3 | tasks:
4 | - name: Ensure a file exists with specific content
5 | copy:
6 | dest: /tmp/ansible_test_file.txt
7 | content: |
8 | This is a test file.
9 | Managed by Ansible.
10 | owner: root
11 | group: root
12 | mode: '0644'
13 |
14 | - name: Ensure a line is present in a configuration file
15 | lineinfile:
16 | path: /tmp/ansible_test_config.conf
17 | line: 'ConfigOption=True'
18 |
--------------------------------------------------------------------------------
/Ansible_Tips_and_Tricks_Practical_Demos/ansible_pause.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Example Playbook for Pausing for Manual Maintenance
3 | hosts: all
4 | become: yes # Use sudo to perform operations that require root privileges
5 |
6 | tasks:
7 | - name: Notify about maintenance
8 | debug:
9 | msg: "Maintenance window: Please perform the required checks."
10 |
11 | - name: Pause for maintenance
12 | pause:
13 | prompt: "Press 'Enter' to continue after maintenance is completed"
14 |
15 | - name: Resume operations post-maintenance
16 | shell: echo "Maintenance completed, resuming operations"
17 |
18 | tags: scenario1
19 |
20 |
21 | - name: Install and Start Apache HTTP Server on Ubuntu
22 | hosts: all
23 | become: yes # Use sudo to perform operations that require root privileges
24 | tasks:
25 | - name: Update apt package index
26 | apt:
27 | update_cache: yes
28 |
29 | - name: Install Apache HTTP Server
30 | apt:
31 | name: apache2
32 | state: present
33 |
34 | - name: Start and enable Apache service
35 | systemd:
36 | name: apache2
37 | state: started
38 | enabled: yes
39 |
40 | - name: Pause to allow the web service to start
41 | pause:
42 | seconds: 30
43 |
44 | - name: Ensure Apache is running
45 | systemd:
46 | name: apache2
47 | state: started
48 | register: httpd_status
49 |
50 | - name: Display Apache status
51 | debug:
52 | msg: "Apache is {{ httpd_status.state }} and enabled."
53 |
54 | tags: scenario2
55 |
56 |
57 | - name: Ansible Pause Parameters
58 | hosts: all
59 | become: yes # Use sudo to perform operations that require root privileges
60 | tasks:
61 | - name: Pause for 30 seconds
62 | pause:
63 | seconds: 30
64 |
65 | - name: Pause for user confirmation
66 | pause:
67 | prompt: "Press 'Enter' to continue after verifying the backup"
68 |
69 | - name: Pause for UserName input
70 | pause:
71 | prompt: "Enter your UserName: "
72 | echo: yes
73 |
74 | - name: Pause for password input without echoing
75 | pause:
76 | prompt: "Enter your password: "
77 | echo: no
78 |
79 | tags: scenario3
80 |
81 |
--------------------------------------------------------------------------------
/Ansible_Tips_and_Tricks_Practical_Demos/environment_varaible.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Demonstrate various use cases of environment variables in Ansible
3 | hosts: localhost
4 | gather_facts: no
5 | environment:
6 | PLAY_LEVEL_VAR: "This is a play-level environment variable"
7 |
8 | tasks:
9 | - name: Print a statement without environment variables
10 | debug:
11 | msg: "This is a statement without any environment variables."
12 |
13 | - name: Print system environment variables
14 | command: env
15 | register: system_env
16 |
17 | - name: Print system environment variables debug
18 | debug:
19 | msg: "{{ system_env.stdout }}"
20 |
21 | - name: Print play-level environment variable
22 | shell: "env | grep PLAY_LEVEL_VAR"
23 | register: play_level_env
24 |
25 | - name: Print play-level environment variable debug
26 | debug:
27 | msg: "{{ play_level_env.stdout }}"
28 |
29 | - name: Set and print task-level environment variable
30 | shell: "env | grep TASK_LEVEL_VAR"
31 | environment:
32 | TASK_LEVEL_VAR: "This is a task-level environment variable"
33 | register: task_level_env
34 |
35 | - name: Print task-level environment variable debug
36 | debug:
37 | msg: "{{ task_level_env.stdout }}"
38 |
39 | - name: Override play-level environment variable at task level
40 | shell: "env | grep PLAY_LEVEL_VAR"
41 | environment:
42 | PLAY_LEVEL_VAR: "This play-level environment variable has been overridden at task level"
43 | register: overridden_play_level_env
44 |
45 | - name: Print overridden play-level environment variable debug
46 | debug:
47 | msg: "{{ overridden_play_level_env.stdout }}"
48 |
49 | - name: Combine system and custom environment variables
50 | shell: "echo \"HOME=$HOME, CUSTOM_VAR=$CUSTOM_VAR\""
51 | args:
52 | chdir: /tmp
53 | environment:
54 | CUSTOM_VAR: "This is a custom variable combined with system variables"
55 | register: combined_env
56 |
57 | - name: Print combined environment variables debug
58 | debug:
59 | msg: "{{ combined_env.stdout }}"
60 |
61 | - name: Use environment variable in a shell command
62 | shell: "echo \"The value of SHELL_COMMAND_VAR is $SHELL_COMMAND_VAR\""
63 | environment:
64 | SHELL_COMMAND_VAR: "Value set for shell command"
65 | register: shell_command_env
66 |
67 | - name: Print shell command environment variable debug
68 | debug:
69 | msg: "{{ shell_command_env.stdout }}"
70 |
--------------------------------------------------------------------------------
/Ansible_Tips_and_Tricks_Practical_Demos/execute_script_on_remote_machine.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | # Using Scripts Module
4 | - name: Run Python script using script module
5 | hosts: all
6 | tasks:
7 | - name: Execute hello_world.py script
8 | script: hello_world.py
9 | tags: scenario1
10 |
11 |
12 | # Copying and Executing the Script
13 | - hosts: all
14 | tasks:
15 | - name: Ensure Python 3 is installed
16 | apt:
17 | name: python3
18 | state: present
19 | become: yes
20 |
21 | - name: Copy the Python script to remote hosts
22 | copy:
23 | src: hello_world.py
24 | dest: /tmp/hello_world.py
25 | mode: '0755'
26 |
27 | - name: Execute hello_world.py script
28 | command: python3 /tmp/hello_world.py Ansible Automation
29 | register: script_output
30 |
31 | - name: Display script output
32 | debug:
33 | var: script_output.stdout
34 | tags: scenario2
--------------------------------------------------------------------------------
/Ansible_Tips_and_Tricks_Practical_Demos/execution_on_ansible_host.yml:
--------------------------------------------------------------------------------
1 | - hosts: localhost
2 | tasks:
3 | - name: Run a command on the local machine
4 | command: echo "Running on the local host"
5 | tags: scenario1
6 |
7 |
8 | - hosts: all
9 | tasks:
10 | - name: Run a command on the remote hosts
11 | command: echo "Running on remote host"
12 |
13 | - name: Run a command on the local machine
14 | command: echo "Running on the local host"
15 | delegate_to: localhost
16 | tags: scenario2
17 |
18 |
19 | - hosts: all
20 | tasks:
21 | - name: Run a command on the remote hosts
22 | command: echo "Running on remote host"
23 |
24 | - name: Run a command on the local machine
25 | local_action: command echo "Running on the local host"
26 | tags: scenario3
--------------------------------------------------------------------------------
/Ansible_Tips_and_Tricks_Practical_Demos/hello_world.py:
--------------------------------------------------------------------------------
1 | # hello_world.py
2 | #import sys
3 |
4 | def main():
5 | print("Hello, World!")
6 | #print(f"Arguments passed: {sys.argv[1:]}")
7 |
8 | if __name__ == "__main__":
9 | main()
10 |
--------------------------------------------------------------------------------
/Ansible_Tips_and_Tricks_Practical_Demos/inventory_ansible_hostname.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Example playbook to demonstrate ansible_hostname vs inventory_hostname
3 | hosts: webservers
4 | gather_facts: yes
5 |
6 | tasks:
7 | - name: Display inventory_hostname
8 | debug:
9 | msg: "inventory_hostname: {{ inventory_hostname }}"
10 |
11 | - name: Display ansible_hostname
12 | debug:
13 | msg: "ansible_hostname: {{ ansible_hostname }}"
14 |
--------------------------------------------------------------------------------
/Ansible_Tips_and_Tricks_Practical_Demos/pass_variable.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Pass Variable to Playbook from Command Line
3 | hosts: all
4 | vars:
5 | var1: value_1
6 | var2: value_2
7 | tasks:
8 | - name: Print variables
9 | debug:
10 | msg: "var1={{ var1 }} var2={{ var2 }}"
11 |
--------------------------------------------------------------------------------
/Basic Concepts of Ansible PlayBooks/ansible_datacollection.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This is Overview of Ansible Data Collection
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | vars:
9 | xyz: Hello this is XYZ
10 | packages: ['wget', 'unzip', 'curl', 'vim']
11 | cities:
12 | - New York
13 | - London
14 | - Tokyo
15 | - Dubai
16 | web_server: {'Linux': 'httpd', 'Unix': 'apache2'}
17 |
18 | tasks:
19 | - name: This is Data Collection Retrieval
20 | debug:
21 | var: xyz
22 |
23 | - name: Getting Sequence Data Collection F 1
24 | debug:
25 | var: packages
26 |
27 | - name: Getting Sequence Data Collection F 2
28 | debug:
29 | var: cities
30 |
31 | - name: Getting Sequence Data Collection F 3
32 | debug:
33 | var: web_server
34 |
--------------------------------------------------------------------------------
/Basic Concepts of Ansible PlayBooks/ansible_debug.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This is Overview of Ansible Debug Module
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | tasks:
9 | - name: Task for Debug Module Messaging
10 | debug:
11 | msg: "Hi, this is Custom message for Debug Module {{ ansible_os_family }}"
12 |
13 | - name: Prints two lines of messages
14 | debug:
15 | msg:
16 | - "Hi This is multiline message."
17 | - "And I am line number 2..."
18 |
19 | - name: Print Varaible in messages
20 | debug:
21 | msg:
22 | - "Host IP is - {{ inventory_hostname }}"
23 | - Host IP is - {{ inventory_hostname }}
24 | - System {{ inventory_hostname }} has gateway {{ ansible_default_ipv4.gateway }}
25 |
26 | - name: debug module var parameter
27 | debug:
28 | var: inventory_hostname
29 |
30 | - name: verbocity in debug module
31 | debug:
32 | msg: "Hi this is deep logging at deub level 2"
33 | verbocity: 2
--------------------------------------------------------------------------------
/Basic Concepts of Ansible PlayBooks/ansible_var.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This is Overview of Ansible Debug Module
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | vars:
9 | test: hello, this is dummy value
10 | my_name: Anshul Chauhan
11 | my_age: 31
12 | my_height: 5.11
13 | is_male: true
14 |
15 | tasks:
16 | - name: Reading Ansible Playbook varaible
17 | debug:
18 | var: test
19 |
20 | - name: Reading Ansible Playbook varaibles
21 | debug:
22 | msg:
23 | - My name is {{ my_name }}
24 | - I am {{ my_age }} years old.
25 | - And I am {{ my_height }} long, my gender is male - {{ is_male }}
--------------------------------------------------------------------------------
/Basic Concepts of Ansible PlayBooks/arithmetic_operations.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This is to Display Arithmetic Opeations on Varaibles
3 | hosts: localhost
4 | gather_facts: false
5 |
6 | vars:
7 | a : 10
8 | b : 20
9 |
10 | tasks:
11 | - name: Operations on variables
12 | debug:
13 | msg:
14 | - "value of a is : {{a}}"
15 | - "value of b is : {{b}}"
16 | - "Addtion of a & b : {{a + b}}"
17 | - "Subs of a & b : {{a - b}}"
18 | - "Multi of a & b : {{a * b}}"
19 | - "Devide of a & b : {{a/b}}"
--------------------------------------------------------------------------------
/Basic Concepts of Ansible PlayBooks/filter_methods_ansible.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This is to Display filter and method Opeations on Varaibles
3 | hosts: localhost
4 | gather_facts: false
5 |
6 | vars:
7 | a : "HeLLo tHiS is ANSHUL and i aM a SoftWARE enginEER"
8 | b : 10
9 | c : "20"
10 |
11 | tasks:
12 | - name: Operations on variables
13 | debug:
14 | msg:
15 | - "value of a is : {{a}}"
16 | - "value of b + c is : {{b+c|int}}"
17 | - "Small case value of a : {{a|lower}}"
18 | - "Capital case Value of a: {{a|upper}}"
19 | - "Title Case value of a : {{a|title}}"
20 | - "Small case value of a : {{a.lower()}}"
21 | - "Capital case Value of a: {{a.upper()}}"
22 | - " Split of String a : {{a.split()}} "
--------------------------------------------------------------------------------
/Basic Concepts of Ansible PlayBooks/pratice_arithmetic.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This is to Display Arithmetic Opeations on Varaibles
3 | hosts: localhost
4 | gather_facts: false
5 |
6 | vars:
7 | a : 10
8 | b : "{{a*10}}"
9 |
10 | vars_prompt:
11 | - name : x
12 | prompt: Please enter Value of x
13 | private: no
14 |
15 | - name : y
16 | prompt: Please eneter value of y
17 | private: no
18 |
19 | tasks:
20 | - name: Operations on variables
21 | debug:
22 | msg:
23 | - "value of a is : {{a}}"
24 | - "value of b is : {{b}}"
25 | - "Addition of User Defined Values x, y is : {{x+y}}"
26 | - "Addition of User Defined Values x, y is : {{x|int + y|int}}"
27 | - "Multiple of User Defined Values x, y is : {{x|int * y|int}}"
--------------------------------------------------------------------------------
/Basic Concepts of Ansible PlayBooks/register_ansible.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This is Overview of Ansible Register and Set_Fact
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | tasks:
9 | - name: Retrive Installed Shell Version
10 | shell: "bash --version"
11 | register: bash_ver
12 |
13 | - set_fact:
14 | bash_version: "{{bash_ver.stdout_lines[0].split()[3]}}"
15 |
16 | - debug:
17 | var: bash_version
--------------------------------------------------------------------------------
/Basic of Ansible Playbook/Install_https.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Installing WebServer
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | tasks:
9 | - name: Ensure Apache is at the Latest Version
10 | yum:
11 | name: httpd
12 | state: latest
13 | - name: Ensure Apache is Running
14 | service:
15 | name: httpd
16 | state: started
--------------------------------------------------------------------------------
/Basic of Ansible Playbook/intro_playbook.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Introduction Ansible Playbooks
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | tasks:
9 | - name: Checking Connection via Ping
10 | ping:
11 |
12 | - name: Uninstall Apache WebServer
13 | yum:
14 | name: httpd
15 | state: absent
--------------------------------------------------------------------------------
/Concept of Template in Ansible/index.html.j2:
--------------------------------------------------------------------------------
1 | Hi, This is Custom Index File.
2 |
3 | Executing on Machine IP : {{ ansible_all_ipv4_addresses }}
4 |
5 | This is OS Family : {{ ansible_os_family }}
6 |
7 | This Machine FQDN is : {{ ansible_fqdn }}
8 |
9 | This is Distro : {{ ansible_distribution }} and BIOS : {{ ansible_bios_version }}
10 |
11 | Hard Coded Varaiable : {{ custom_var }}
--------------------------------------------------------------------------------
/Concept of Template in Ansible/install_httpd.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Installing WebServer
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | vars:
9 | custom_var : 123abc
10 |
11 | tasks:
12 | - name: Ensure Apache is at the Latest Version
13 | yum:
14 | name: httpd
15 | state: present
16 | notify:
17 | - Ensure Apache is Running
18 |
19 | - name: Updating Index HTML file
20 | template:
21 | src: index.html.j2
22 | dest: /usr/share/httpd/noindex/index.html
23 | notify:
24 | - Ensure Apache restart
25 |
26 | handlers:
27 | - name: Ensure Apache is Running
28 | service:
29 | name: httpd
30 | state: started
31 |
32 | - name: Ensure Apache restart
33 | service:
34 | name: httpd
35 | state: restarted
--------------------------------------------------------------------------------
/Concept of Template in Ansible/install_tomcat.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playboo
2 |
3 | - name: Install and Configure Tomcat using Ansible
4 | hosts: all
5 | remote_user: ec2-user
6 | become: 'yes'
7 | become_user: root
8 |
9 | vars:
10 | java_version: java-1.8.0-openjdk
11 | alternative_path: java-1.8.0-openjdk-1.8.0.302.b08-0.amzn2.0.1.x86_64
12 | tomcat_version: 9.0.56
13 | tomcat_port: 8090
14 |
15 | tasks:
16 | - name: Update All Packages on Machine
17 | yum:
18 | name: "*"
19 | state: latest
20 |
21 | - name: Install Java on Machine
22 | yum:
23 | name: "{{ java_version }}"
24 | state: present
25 |
26 | - name: Set Java 8 Alternative on Machine
27 | alternatives:
28 | name: java
29 | link: /bin/java
30 | path: /usr/lib/jvm/{{alternative_path}}/jre/bin/java
31 |
32 | - name: Download Tomcat Tar file
33 | get_url:
34 | url: https://dlcdn.apache.org/tomcat/tomcat-9/v{{tomcat_version}}/bin/apache-tomcat-{{tomcat_version}}.tar.gz
35 | dest: /usr/local
36 |
37 | - name: Extract Tomcat file
38 | unarchive:
39 | src: /usr/local/apache-tomcat-{{tomcat_version}}.tar.gz
40 | dest: /usr/local
41 | remote_src: yes
42 |
43 | - name: Rename Tomcat dir
44 | command: mv /usr/local/apache-tomcat-{{tomcat_version}} /usr/local/tomcat
45 |
46 | - name: Replacing default port with required port
47 | template:
48 | src: server.xml.j2
49 | dest: /usr/local/tomcat/conf/server.xml
50 |
51 | - name: Starting Tomcat process
52 | shell: nohup /usr/local/tomcat/bin/startup.sh &
--------------------------------------------------------------------------------
/Concept of Template in Ansible/server.xml.j2:
--------------------------------------------------------------------------------
1 |
2 |
18 |
22 |
23 |
24 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
37 |
38 |
41 |
46 |
47 |
48 |
53 |
54 |
55 |
56 |
60 |
61 |
62 |
69 |
72 |
73 |
79 |
86 |
95 |
101 |
113 |
114 |
115 |
121 |
122 |
127 |
128 |
131 |
132 |
133 |
136 |
139 |
140 |
142 |
143 |
147 |
149 |
150 |
151 |
153 |
154 |
156 |
159 |
160 |
163 |
166 |
167 |
168 |
169 |
170 |
171 |
--------------------------------------------------------------------------------
/Error Handling in Ansible/block_ansible.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Ansible Blocks
3 | hosts: all
4 | remote_user: ec2-user
5 |
6 | tasks:
7 | - block:
8 | - name: List usr directory content
9 | command: "ls -l /usr/"
10 | register: usr_out
11 |
12 | - name: List root partition content
13 | command: "ls -l /roott/"
14 | register: root_out
15 |
16 | - name: List bin diretcory content
17 | command: "ls -l /bin/"
18 | register: bin_out
19 | become: 'yes'
20 | ignore_errors: yes
21 |
22 | - name: List ansible user's home directory content
23 | command: "ls -l ~/"
24 | register: userhome_out
25 |
26 | - debug: var=usr_out
27 | - debug: var=root_out
28 | - debug: var=userhome_out
29 | #- debug: var=bin_out
--------------------------------------------------------------------------------
/Error Handling in Ansible/demo_block_rescue.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Error Handling Part I
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | vars:
9 | anonymous_enable: yes
10 | local_enable: yes
11 | write_enable: yes
12 | anon_upload_enable: yes
13 |
14 | tasks:
15 | - block:
16 | - name: install vsftp
17 | yum:
18 | name: vsftpd
19 |
20 | - name: take backup of existing config
21 | copy:
22 | src: /etc/vsftpd/vsftpd.conf
23 | dest: /etc/vsftpd/vsftpd.conf.bkp
24 | remote_src: yes
25 |
26 | - name: use Jinja2 template to configure vsftpd
27 | template:
28 | src: vsftpd.j2
29 | dest: /etc/vsftpd/vsftpd.conf
30 |
31 | - name: View Custom Jinja Teamplate values
32 | command: "cat /etc/vsftpd/vsftpd.conf"
33 | register: jinja_out
34 | - debug: var=jinja_out
35 |
36 | - name: This will fail
37 | command: "ls -l /tmp/does-not-exist"
38 |
39 |
40 | rescue:
41 | - name: Recovery block
42 | debug:
43 | msg: "something failed, restoring vsftpd.conf from backup"
44 |
45 | - name:
46 | copy:
47 | src: /etc/vsftpd/vsftpd.conf.bkp
48 | dest: /etc/vsftpd/vsftpd.conf
49 | remote_src: yes
50 |
51 | - name: View vsftd.conf values
52 | command: "cat /etc/vsftpd/vsftpd.conf"
53 | register: conf_out
54 | - debug: var=conf_out
55 |
56 |
57 | always:
58 | - name: Restarting vsftpd
59 | service:
60 | name: vsftpd
61 | state: restarted
62 |
--------------------------------------------------------------------------------
/Error Handling in Ansible/error_handling_1.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Error Handling Part I
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | tasks:
9 | - name: List all files/dirs in /etc location
10 | command: "ls /etcc/"
11 | register: home_out
12 | ignore_errors: yes
13 | - debug: var=home_out
14 |
15 | - name: List all files/dirs in /tmp location
16 | command: "ls /tmp/"
17 | register: tmp_out
18 | - debug: var=tmp_out
19 |
20 | - name: List all files/dirs in /etc location
21 | command: "ls /etcc/"
22 | register: home1_out
23 | ignore_errors: yes
24 | - debug: var=home1_out
25 | failed_when: home1_out.rc==2
--------------------------------------------------------------------------------
/Error Handling in Ansible/rescue_block.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Ansible Blocks
3 | hosts: all
4 | remote_user: ec2-user
5 |
6 | tasks:
7 | - block:
8 | - name: List home directory content
9 | command: ls -l ~/
10 |
11 | - name: Failing intentionally
12 | command: ls -l /tmp/
13 | become: 'yes'
14 | #ignore_errors: yes
15 |
16 | rescue:
17 | - name: Rescue block (perform recovery)
18 | debug:
19 | msg: 'Something went wrong, cleaning up..'
20 |
21 | always:
22 | - name: This will execute always
23 | debug:
24 | msg: I will execute even in failure scenario
--------------------------------------------------------------------------------
/Error Handling in Ansible/vsftpd.j2:
--------------------------------------------------------------------------------
1 | anonymous_enable={{ anonymous_enable }}
2 | local_enable={{ local_enable }}
3 | write_enable={{ write_enable }}
4 | anon_upload_enable={{ anon_upload_enable }}
5 | dirmessage_enable=YES
6 | xferlog_enable=YES
7 | connect_from_port_20=YES
8 | pam_service_name=vsftpd
9 | userlist_enable=YES
10 | # MY IP Address={{ ansible_facts['default_ipv4']['address'] }}
--------------------------------------------------------------------------------
/Handlers in Ansible/handler_imp.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Installing WebServer
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | tasks:
9 | - name: Ensure Apache is at the Latest Version
10 | yum:
11 | name: httpd
12 | state: present
13 | notify:
14 | - Ensure Apache is Running
15 | - Ensure Apache restart
16 |
17 | handlers:
18 | - name: Ensure Apache is Running
19 | service:
20 | name: httpd
21 | state: started
22 |
23 | - name: Ensure Apache restart
24 | service:
25 | name: httpd
26 | state: restarted
--------------------------------------------------------------------------------
/Handlers in Ansible/handler_req.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Installing WebServer
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | tasks:
9 | - name: Ensure Apache is at the Latest Version
10 | yum:
11 | name: httpd
12 | state: present
13 | register: httpd_installation_status
14 |
15 |
16 | - name: Ensure Apache is Running
17 | service:
18 | name: httpd
19 | state: started
20 | when: httpd_installation_status.changed == True
--------------------------------------------------------------------------------
/Interact with Web Service APIs using Ansible/Submit a GET request to a REST API Endpoint:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Submit GET request to a REST API endpoint
3 | hosts: webservers
4 | gather_facts: no
5 |
6 | tasks:
7 | - name: Send GET request to JSONPlaceholder API
8 | uri:
9 | url: https://jsonplaceholder.typicode.com/posts
10 | method: GET
11 | return_content: yes
12 | register: response
13 |
14 | - name: Display response content
15 | debug:
16 | var: response.json
17 |
18 | - name: Process response
19 | debug:
20 | msg: "Total posts received: {{ response.json | length }}"
21 |
--------------------------------------------------------------------------------
/Interact with Web Service APIs using Ansible/Token Based Authentication in REST API:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Interact with Reqres API using token-based authentication
3 | hosts: webservers
4 | gather_facts: no
5 |
6 | vars:
7 | login_url: "https://reqres.in/api/login"
8 | post_url: "https://reqres.in/api/users"
9 | username: "eve.holt@reqres.in"
10 | password: "cityslicka"
11 | new_user:
12 | name: "morpheus"
13 | job: "leader"
14 |
15 | tasks:
16 | - name: Login to Reqres API to obtain token
17 | uri:
18 | url: "{{ login_url }}"
19 | method: POST
20 | body:
21 | email: "{{ username }}"
22 | password: "{{ password }}"
23 | body_format: json
24 | headers:
25 | Content-Type: "application/json"
26 | return_content: yes
27 | status_code: 200
28 | register: auth_response
29 |
30 | - name: Display Login response content
31 | debug:
32 | var: auth_response.json
33 |
34 | - name: Extract token from login response
35 | set_fact:
36 | auth_token: "{{ auth_response.json.token }}"
37 |
38 | - name: Ensure token was obtained
39 | debug:
40 | var: auth_token
41 |
42 | - name: Use token to create a new user
43 | uri:
44 | url: "{{ post_url }}"
45 | method: POST
46 | body: "{{ new_user }}"
47 | body_format: json
48 | headers:
49 | Content-Type: "application/json"
50 | Authorization: "Bearer {{ auth_token }}"
51 | return_content: yes
52 | status_code: 201
53 | register: create_user_response
54 |
55 | - name: Display create user response content
56 | debug:
57 | var: create_user_response.content
58 |
--------------------------------------------------------------------------------
/Loops in Ansible Playbook/loops_example.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Loops in Ansible Playbook Part I
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | vars:
9 | alpha: [ 'a', 'b', 'c', 'd' ]
10 | numbers: [ 1, 2, 3, 4 ]
11 |
12 | tasks:
13 | # Add Multiple User's in one go
14 | - name: add several users in one go
15 | user:
16 | name: "{{ item }}"
17 | state: present
18 | groups: "games"
19 | with_items:
20 | - testuser1
21 | - testuser2
22 | - testuser3
23 | - testuser4
24 | - testuser5
25 |
26 |
27 | - name: add several users
28 | user:
29 | name: "{{ item.name }}"
30 | state: present
31 | groups: "{{ item.groups }}"
32 | with_items:
33 | - { name: 'testuser6', groups: 'nobody' }
34 | - { name: 'testuser7', groups: 'nobody' }
35 | - { name: 'testuser8', groups: 'postfix' }
36 | - { name: 'testuser9', groups: 'postfix' }
37 |
38 |
39 | - name: Loop Over Set of Collection variable
40 | debug:
41 | msg: "{{ item.0 }} and {{ item.1 }}"
42 | with_together:
43 | - "{{ alpha }}"
44 | - "{{ numbers }}"
--------------------------------------------------------------------------------
/Loops in Ansible Playbook/loops_exampleII.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Loops in Ansible Playbook Part II
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | vars:
9 | alpha: [ 'a', 'b', 'c', 'd' ]
10 | numbers: [ 1, 2, 3, 4 ]
11 |
12 | tasks:
13 | # Add Multiple User's in one go
14 | - name : Random Looping Example
15 | debug:
16 | msg: "{{ item }}"
17 | with_random_choice:
18 | - "go through the door"
19 | - "drink from the goblet"
20 | - "press the red button"
21 | - "do nothing"
22 |
23 | # Looping Over A List With An Index
24 | - name: Looping over a List
25 | debug:
26 | msg: "At array position {{ item.0 }} there is a value {{ item.1 }}"
27 | with_indexed_items:
28 | - "{{ alpha }}"
29 |
30 | # Do Until Loop
31 | - name: Ensure Apache is Running
32 | service:
33 | name: httpd
34 | state: started
35 | register: result
36 | until: result.changed == True
37 | retries: 10
38 | delay: 4
39 |
40 |
--------------------------------------------------------------------------------
/Loops in Ansible Playbook/loops_exampleIII.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Loops in Ansible Playbook Part III
3 | hosts: all
4 | remote_user: ec2-user
5 | become: 'yes'
6 | become_user: root
7 |
8 | vars:
9 | packages: [ 'gettext-devel', 'openssl-devel', 'perl-CPAN', 'perl-devel', 'zlib-devel', 'unzip', 'curl', 'wget' ]
10 | tasks:
11 | - name: Install Multiple Packages using Loop
12 | yum:
13 | name: '{{ item }}'
14 | state: present
15 | loop:
16 | - gettext-devel
17 | - openssl-devel
18 | - perl-CPAN
19 | - perl-devel
20 | - zlib-devel
21 | - unzip
22 | - curl
23 | - wget
24 |
25 |
26 | - name: UnInstall Multiple Packages using Index Loop
27 | yum:
28 | name: '{{ item.1 }}'
29 | state: absent
30 | with_indexed_items:
31 | - "{{ packages }}"
32 |
33 |
34 | - name: Install Multiple Packages using Index Loop
35 | yum:
36 | name: '{{ item.0 }}'
37 | state: present
38 | with_together:
39 | - "{{ packages }}"
40 |
--------------------------------------------------------------------------------
/Manage Remote Machine File System via Ansible/Managefile_example1.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: File Management Playbook
3 | hosts: webservers # Replace with your target hosts or group
4 |
5 | tasks:
6 | - name: Create an Empty File
7 | ansible.builtin.file:
8 | path: /tmp/empty_file.txt
9 | state: touch
10 | register: result_empty_file
11 |
12 | - debug:
13 | msg: "Empty file created successfully"
14 | when: result_empty_file.changed
15 |
16 | - name: Create a Text File
17 | copy:
18 | content: |
19 | This is the content
20 | of the file.
21 | It can span multiple lines.
22 | dest: /tmp/text_file.txt
23 | register: result_text_file
24 |
25 | - debug:
26 | msg: "Text file created successfully"
27 | when: result_text_file.changed
28 |
29 | - name: Check if File Exists
30 | ansible.builtin.stat:
31 | path: /tmp/text_file.txt
32 | register: file_stat
33 |
34 | - debug:
35 | msg: "Text file exists"
36 | when: file_stat.stat.exists
37 |
38 | - name: Change File Permissions
39 | ansible.builtin.file:
40 | path: /tmp/text_file.txt
41 | mode: '0600'
42 | register: result_change_permissions
43 |
44 | - debug:
45 | msg: "File permissions changed successfully"
46 | when: result_change_permissions.changed
47 |
48 | - name: Delete File if Exists
49 | ansible.builtin.file:
50 | path: /tmp/text_file.txt
51 | state: absent
52 | register: result_delete_file
53 |
54 | - debug:
55 | msg: "File deleted successfully"
56 | when: result_delete_file.changed
57 |
--------------------------------------------------------------------------------
/Manage Remote Machine File System via Ansible/Managefile_example2.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Manage Directory Operations
3 | hosts: webservers
4 | become: yes
5 | tasks:
6 | - name: Create a Directory
7 | ansible.builtin.file:
8 | path: /tmp/example_dir
9 | state: directory
10 | register: dir_created
11 |
12 | - debug:
13 | msg: "Directory created successfully"
14 | when: dir_created.changed
15 |
16 | - name: Check if Directory Exists
17 | ansible.builtin.stat:
18 | path: /tmp/example_dir
19 | register: dir_stat
20 |
21 | - debug:
22 | msg: "Directory exists"
23 | when: dir_stat.stat.exists
24 |
25 | - name: Rename a Directory
26 | command: mv /tmp/example_dir /tmp/renamed_dir
27 | args:
28 | removes: /tmp/example_dir
29 | register: dir_renamed
30 |
31 | - debug:
32 | msg: "Directory renamed successfully"
33 | when: dir_renamed.changed
34 |
35 | - name: Provide Recursive Permissions to Directory Content
36 | ansible.builtin.file:
37 | path: /tmp/renamed_dir
38 | recurse: yes
39 | mode: '0755'
40 | register: dir_permissions
41 |
42 | - debug:
43 | msg: "Recursive permissions set successfully"
44 | when: dir_permissions.changed
45 |
46 | - name: Delete a Directory
47 | ansible.builtin.file:
48 | path: /tmp/renamed_dir
49 | state: absent
50 | register: dir_deleted
51 |
52 | - debug:
53 | msg: "Directory deleted successfully"
54 | when: dir_deleted.changed
55 |
--------------------------------------------------------------------------------
/Manage Remote Machine File System via Ansible/archive_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Deploy web application
3 | hosts: webservers
4 | become: yes # To run tasks with sudo privileges
5 |
6 | tasks:
7 | - name: Ensure the destination directory exists
8 | file:
9 | path: /var/www/html
10 | state: directory
11 |
12 | - name: Download the web application archive
13 | get_url:
14 | url: https://github.com/brettz9/webappfind-demos-samples/archive/refs/tags/v0.7.0.tar.gz
15 | dest: /tmp/v0.7.0.tar.gz
16 |
17 | - name: Extract the web application archive
18 | unarchive:
19 | src: /tmp/v0.7.0.tar.gz
20 | dest: /var/www/html
21 | remote_src: yes # Indicates that the src path is on the remote machine
22 |
23 | - name: Clean up the archive file from the remote server
24 | file:
25 | path: /tmp/webapp.tar.gz
26 | state: absent
27 |
--------------------------------------------------------------------------------
/Manage Remote Machine File System via Ansible/downloadfile_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: Download a file using get_url
4 | hosts: webservers
5 | tasks:
6 | - name: Download jq utility
7 | get_url:
8 | url: https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
9 | dest: /usr/local/bin/jq
10 | mode: '0755'
11 |
12 | - name: Download jq utility with checksum validation
13 | get_url:
14 | url: https://github.com/jqlang/jq/releases/download/jq-1.7.1/jq-linux64
15 | dest: /usr/local/bin/jq-1.7
16 | checksum: 'sha256:5942c9b0934e510ee61eb3e30273f1b3fe2590df93933a93d7c58b81d19c8ff5'
17 | mode: '0755'
18 |
19 |
20 | - name: Download POM file
21 | get_url:
22 | url: https://repo1.maven.org/maven2/org/slf4j/slf4j-api/2.0.13/slf4j-api-2.0.13.pom
23 | dest: "/etc/slf4j.pom"
24 | mode: '0644'
25 |
26 |
27 | - name: Download files
28 | get_url:
29 | url: "{{ item.url }}"
30 | dest: "{{ item.dest }}"
31 | mode: '0644'
32 | loop:
33 | - { url: 'https://maven.google.com/androidx/appcompat/appcompat/1.6.1/appcompat-1.6.1.aar', dest: '/tmp/andriod.aar' }
34 | - { url: 'https://repo1.maven.org/maven2/com/squareup/retrofit2/retrofit/2.8.2/retrofit-2.8.2.jar', dest: '/tmp/retrofit.jar' }
35 |
--------------------------------------------------------------------------------
/Manage Remote Machine File System via Ansible/hardlink_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Demonstrate Hardlink with Ansible
3 | hosts: webservers
4 | become: yes
5 |
6 | tasks:
7 | - name: Create a file
8 | ansible.builtin.file:
9 | path: /tmp/source_file.txt
10 | state: touch
11 | mode: '0644'
12 | # Optionally, set initial content
13 | # content: "This is the source file.\n"
14 |
15 | - name: Create a hard link to the file
16 | ansible.builtin.file:
17 | src: /tmp/source_file.txt
18 | dest: /tmp/hardlink_to_source
19 | state: link
20 |
21 | - name: Verify existence of the hard link
22 | ansible.builtin.stat:
23 | path: /tmp/hardlink_to_source
24 | register: hardlink_info
25 |
26 | - debug:
27 | msg: "Hard link exists: {{ hardlink_info.stat.exists }}"
28 |
29 | - name: Remove the hard link
30 | ansible.builtin.file:
31 | path: /tmp/hardlink_to_source
32 | state: absent
33 |
34 | - name: Verify removal of the hard link
35 | ansible.builtin.stat:
36 | path: /tmp/hardlink_to_source
37 | register: removed_link_info
38 |
39 | - debug:
40 | msg: "Hard link removed: {{ not removed_link_info.stat.exists }}"
41 |
--------------------------------------------------------------------------------
/Manage Remote Machine File System via Ansible/symlink_example.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Create and Verify Soft Link for CPU/Memory Usage
3 | hosts: webservers
4 |
5 | tasks:
6 | - name: Create a symbolic link to /proc/cpuinfo
7 | ansible.builtin.file:
8 | src: /proc/cpuinfo
9 | dest: /tmp/cpuinfo_link
10 | state: link
11 |
12 | - name: Verify symbolic link creation
13 | ansible.builtin.stat:
14 | path: /tmp/cpuinfo_link
15 | register: link_stats
16 |
17 | - name: Print symbolic link verification result
18 | ansible.builtin.debug:
19 | msg: "Symbolic link exists: {{ link_stats.stat.islnk }}"
20 |
21 | - name: Read content of the symbolic link (CPU info)
22 | ansible.builtin.shell: cat /tmp/cpuinfo_link
23 | register: cpuinfo_content
24 |
25 | - name: Print CPU info
26 | ansible.builtin.debug:
27 | msg: "{{ cpuinfo_content.stdout }}"
28 |
29 | - name: Create a symbolic link to /proc/meminfo
30 | ansible.builtin.file:
31 | src: /proc/meminfo
32 | dest: /tmp/meminfo_link
33 | state: link
34 |
35 | - name: Verify symbolic link creation for memory info
36 | ansible.builtin.stat:
37 | path: /tmp/meminfo_link
38 | register: meminfo_link_stats
39 |
40 | - name: Print symbolic link verification result for memory info
41 | ansible.builtin.debug:
42 | msg: "Symbolic link exists: {{ meminfo_link_stats.stat.islnk }}"
43 |
44 | - name: Read content of the symbolic link (Memory info)
45 | ansible.builtin.shell: cat /tmp/meminfo_link
46 | register: meminfo_content
47 |
48 | - name: Print Memory info
49 | ansible.builtin.debug:
50 | msg: "{{ meminfo_content.stdout }}"
51 |
--------------------------------------------------------------------------------
/Operators and Conditional Statement in Ansible Playbook/comparision_operator.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This will show the Use of Comparision Operators
3 | hosts: localhost
4 | gather_facts: false
5 |
6 | vars:
7 | a : "HELLO"
8 | d : "hello"
9 | b : 10
10 | c : 20
11 |
12 | tasks:
13 | - name: Operations on variables
14 | debug:
15 | msg:
16 | - "The value of b is - {{ b }}, and Value of c is - {{ c }}"
17 | - "Is b greater than c : {{ b > c }}"
18 | - "Is b less than c : {{ b < c }}"
19 | - "Is b equals to c : {{ b == c }}"
20 | - "Is b not equal to c : {{ b != c }}"
21 | - "Is b greater than or equal to c : {{ b >= c }}"
22 | - "Is b less than or equal to c : {{ b <= c }}"
23 | - "Below Comparision is for String"
24 | - "The value of a is - {{ a }}, and Value of d is - {{ d }}"
25 | - "Is a greater than d : {{ a > d }}"
26 | - "Is a less than d : {{ a < d }}"
27 | - "Is a equals to d : {{ a == d }}"
28 | - "Is a not equal to d : {{ a != d }}"
29 | - "Is a equals to d : {{ a|lower == d }}"
--------------------------------------------------------------------------------
/Operators and Conditional Statement in Ansible Playbook/condition_statement.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This is for Conditional Statement
3 | hosts: localhost
4 | gather_facts: false
5 |
6 | vars:
7 | x : 20
8 | y : 10
9 |
10 | tasks:
11 | - name: Operation for Conditional Statement
12 | debug:
13 | msg:
14 | - "Value of x : {{ x }}, Value of y: {{ y }}"
15 |
16 | - name: Operation for Conditional Statement I
17 | debug:
18 | msg:
19 | - "x is Small of y"
20 | when: x < y
21 |
22 | - name: Operation for Conditional Statement II
23 | debug:
24 | msg:
25 | - "x is not Small then y"
26 | when: x > y
--------------------------------------------------------------------------------
/Operators and Conditional Statement in Ansible Playbook/install_webserver.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Installing Web-Serers on Production Machines
3 | hosts: all
4 | remote_user: "ec2-user if ( {{ansible_distribution}} == "Ubuntu" ) else (ubuntu)"
5 | become: 'yes'
6 | become_user: root
7 |
8 | tasks:
9 | - name: Installing Httpd Web-Serer
10 | yum:
11 | name: httpd
12 | state: present
13 |
--------------------------------------------------------------------------------
/Operators and Conditional Statement in Ansible Playbook/logical_operator.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This will show the Use of Comparision Operators
3 | hosts: localhost
4 | gather_facts: false
5 |
6 | vars:
7 | a : "HELLO"
8 | d : "hello"
9 | b : 10
10 | c : 20
11 | e : [1,5,9,10,15,109]
12 | x: true
13 | y: false
14 | z: false
15 | m: true
16 |
17 | tasks:
18 | - name: Operations on variables
19 | debug:
20 | msg:
21 | - "x and y : {{ x and y }}"
22 | - "x and m : {{ x and m }}"
23 | - "x or m : {{ x or m }}"
24 | - "y or z : {{ y or z}}"
25 | - "x and y or m: {{ x and y or m}}"
26 |
27 |
--------------------------------------------------------------------------------
/Operators and Conditional Statement in Ansible Playbook/memebership_tests.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This will show the Use of Comparision Operators
3 | hosts: localhost
4 | gather_facts: false
5 |
6 | vars:
7 | a : "HELLO"
8 | d : "hello"
9 | b : 10
10 | c : 20
11 | e : [1,5,9,10,15,109]
12 | x: "/root/ansible/operators_statement"
13 | y: "/root/ansible/operators_statement/comparision_operator.yml"
14 |
15 | tasks:
16 | - name: Operations on variables
17 | debug:
18 | msg:
19 | - "The List is - {{ e }}, Value of c is - {{ c }} and Value of b is - {{ b }}"
20 | - "Is b memeber of e : {{ b in e }}"
21 | - "Is c memeber of e : {{ c in e }}"
22 | - "Is 25 memeber of e : {{ 25 in e }}"
23 | - "Is c not a memeber of e : {{ c not in e }}"
24 |
25 | - name: Tests Operators
26 | debug:
27 | msg:
28 | - "a is defined? {{ a is defined }}"
29 | - "c is defined? {{ c is defined }}"
30 | - "a is Upper? {{ a is upper }}"
31 | - "b is Lower? {{ b is lower }}"
32 | - "e is String? {{ e is string }}"
33 | - "a is devisble by 7? {{ a is divisibleby 7 }}"
34 | - "y is file: {{ y is file }}"
35 | - "x is directory: {{ x is directory }}"
36 | - "y is directory: {{ y is directory }}"
37 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Ansible Automation
2 |
3 | Welcome to the Ansible Automation repository! This project contains various Ansible playbooks and roles designed to automate infrastructure management tasks. The goal is to provide a robust and reusable set of Ansible scripts to help streamline and standardize deployment and configuration processes.
4 |
5 | ## Table of Contents
6 |
7 | - [Getting Started](#getting-started)
8 | - [Prerequisites](#prerequisites)
9 | - [Installation](#installation)
10 | - [Usage](#usage)
11 | - [Project Structure](#project-structure)
12 | - [Contributing](#contributing)
13 | - [License](#license)
14 | - [Contact](#contact)
15 |
16 | ## Getting Started
17 |
18 | To get started with this project, clone the repository to your local machine and follow the instructions below to set up and run the Ansible playbooks.
19 |
20 | ## Prerequisites
21 |
22 | - Ansible 2.9 or higher
23 | - Python 3.6 or higher
24 | - SSH access to the target machines
25 | - Necessary permissions on the target machines to perform the tasks defined in the playbooks
26 |
27 | ## Installation
28 |
29 | 1. **Clone the repository:**
30 |
31 | ```bash
32 | git clone https://github.com/anshulc55/ansible_automation.git
33 | cd ansible_automation
34 | ```
35 |
36 | 2. **Install dependencies:**
37 |
38 | Ensure you have Ansible installed. If not, you can install it using pip:
39 |
40 | ```bash
41 | pip install ansible
42 | ```
43 |
44 | ## Usage
45 |
46 | 1. **Configure inventory:**
47 |
48 | Edit the `inventory.ini` file to define your target hosts and groups.
49 |
50 | ```ini
51 | [webservers]
52 | webserver1 ansible_host=192.168.1.10 ansible_user=your_username
53 |
54 | [dbservers]
55 | dbserver1 ansible_host=192.168.1.20 ansible_user=your_username
56 | ```
57 |
58 | 2. **Run a playbook:**
59 |
60 | Use the `ansible-playbook` command to run a specific playbook. For example, to run the `site.yml` playbook:
61 |
62 | ```bash
63 | ansible-playbook -i inventory.ini site.yml
64 | ```
65 |
66 | ## Project Structure
67 |
68 | The project is structured as follows:
69 |
70 | ```
71 | ansible_automation/
72 | ├── ansible.cfg # Ansible configuration file
73 | ├── inventory.ini # Inventory file for defining target hosts
74 | ├── playbooks/ # Directory containing Ansible playbooks
75 | │ ├── site.yml # Main playbook to run
76 | │ ├── webserver.yml # Playbook for setting up web servers
77 | │ └── dbserver.yml # Playbook for setting up database servers
78 | ├── roles/ # Directory containing Ansible roles
79 | │ ├── common/ # Common tasks for all servers
80 | │ ├── webserver/ # Tasks specific to web servers
81 | │ └── dbserver/ # Tasks specific to database servers
82 | └── README.md # This README file
83 | ```
84 |
85 | ## Contributing
86 |
87 | Contributions are welcome! If you find a bug or have a feature request, please open an issue. If you would like to contribute code, please fork the repository and submit a pull request.
88 |
89 | 1. **Fork the repository**
90 | 2. **Create a new branch** (`git checkout -b feature-branch`)
91 | 3. **Commit your changes** (`git commit -am 'Add new feature'`)
92 | 4. **Push to the branch** (`git push origin feature-branch`)
93 | 5. **Open a pull request**
94 |
95 | ## License
96 |
97 | This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
98 |
99 | ## Contact
100 |
101 | For any questions or inquiries, please contact Anshul Chauhan at anshulc55@gmail.com.
102 |
103 | ---
104 |
105 | Thank you for using Ansible Automation! Happy automating!
106 |
--------------------------------------------------------------------------------
/Secure Your Infra : Ansible Vault/secrets.yml:
--------------------------------------------------------------------------------
1 | ---
2 | db_username: 'admin'
3 | db_password: 'supersecretpassword'
4 |
5 | # ansible-vault encrypt secrets.yml
6 |
7 | # Encrypt Varaible
8 | # ansible-vault encrypt_string 'mysecretpassword' --name 'super_secret_password'
--------------------------------------------------------------------------------
/Secure Your Infra : Ansible Vault/use_secrets.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: Example playbook using Ansible vault
4 | hosts: localhost
5 | vars_files:
6 | - secrets.yml
7 | vars:
8 | app_name: "MyApp"
9 | app_version: "1.0.0"
10 | tasks:
11 | - name: Print the application name and version
12 | debug:
13 | msg: "Application Name: {{ app_name }}, Version: {{ app_version }}"
14 |
15 | - name: Print the database username and password
16 | debug:
17 | msg: "Database Username: {{ db_username }}, Password: {{ db_password }}"
18 | no_log: true
19 |
20 |
21 | - name: Example playbook Without Ansible Vault
22 | hosts: localhost
23 | vars:
24 | db_username: 'admin'
25 | db_password: 'supersecretpassword'
26 | tasks:
27 | - name: Print the database username and password
28 | debug:
29 | msg: "Database Username: {{ db_username }}, Password: {{ db_password }}"
30 |
31 |
32 | - name: Example playbook Without Ansible Vault
33 | hosts: localhost
34 | vars:
35 | db_username: !vault |
36 | $ANSIBLE_VAULT;1.1;AES256
37 | 35343332326135366661666636336162646138636663623463633039343766366565356236643061
38 | 3366326339653038663133376538663038613762326539610a393965663433313561623466383030
39 | 34343732343962616665636434323238373834386664343937393231353865386230323039333663
40 | 3462343336626162320a363566626635343933336136666265343132663730376236336632323532
41 | 3631
42 | db_password: !vault |
43 | $ANSIBLE_VAULT;1.1;AES256
44 | 66316132636664633932663465633066623266653836363863373662636634623661373939396466
45 | 3165626438356562346461326531333839376331326334350a656662346136356261663635396266
46 | 30333136336361613530626433613332613134323662303636336163323163373834633030613465
47 | 6131376339393231370a316562666466613566623830373137666163363766326333653065303731
48 | 32383162333231346166613230373139393434643037316663373539306438343166
49 | tasks:
50 | - name: Print the database username and password
51 | debug:
52 | msg: "Database Username: {{ db_username }}, Password: {{ db_password }}"
53 |
--------------------------------------------------------------------------------
/Tags in Ansible/tags_ansible.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This will show the Use of Tags
3 | hosts: localhost
4 | gather_facts: false
5 |
6 | tasks:
7 | - name: Operations using the Tags 1
8 | debug:
9 | msg:
10 | - "Hi, This is Debug Message 1 "
11 | tags:
12 | - first
13 |
14 | - name: Operations using the Tags 2
15 | debug:
16 | msg:
17 | - "Hi, This is Debug Message 2 "
18 | tags:
19 | - Second
20 | - Common
21 |
22 | - name: Operations using the Tags 3
23 | debug:
24 | msg:
25 | - "Hi, This is Debug Message 3 "
26 |
27 | - name: Operations using the Tags 4
28 | debug:
29 | msg:
30 | - "Hi, This is Debug Message 4 "
31 |
32 | - name: Operations using the Tags 5
33 | debug:
34 | msg:
35 | - "Hi, This is Debug Message 5 "
36 | tags:
37 | - first
38 |
39 | - name: Operations using the Tags 6
40 | debug:
41 | msg:
42 | - "Hi, This is Debug Message 6 "
--------------------------------------------------------------------------------
/Working with include and import module in Ansible/import_playbook.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Including Import Playbook
3 | hosts: localhost
4 | gather_facts: false
5 |
6 | tasks:
7 | - name: Play 1 - Task 1
8 | debug:
9 | msg: "Play 1 - Task 1"
10 |
11 | - import_playbook: play2.yml
--------------------------------------------------------------------------------
/Working with include and import module in Ansible/include_playbook.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Including Include Playbook
3 | hosts: localhost
4 | gather_facts: false
5 |
6 | tasks:
7 | - name: Play 1 - Task 1
8 | debug:
9 | msg: "Play 1 - Task 1"
10 |
11 | - include: play2.yml
--------------------------------------------------------------------------------
/Working with include and import module in Ansible/include_tasks.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This will show the use of include task
3 | hosts: localhost
4 | gather_facts: false
5 |
6 | tasks:
7 | - name: Play 1 - Task 1
8 | debug:
9 | msg: "Play 1 - Task 1"
10 | - include: tasks-1.yml
--------------------------------------------------------------------------------
/Working with include and import module in Ansible/include_tasks_module.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: This will show the use of include task
3 | hosts: localhost
4 | gather_facts: false
5 |
6 | tasks:
7 | - name: Play 1 - Task 1
8 | debug:
9 | msg: "Play 1 - Task 1"
10 | - include_tasks: tasks-1.yml
--------------------------------------------------------------------------------
/Working with include and import module in Ansible/play2.yml:
--------------------------------------------------------------------------------
1 | #!/root/ansible/myansible/bin/ansible-playbook
2 | - name: Play 2 from Include
3 | hosts: localhost
4 | gather_facts: false
5 |
6 | tasks:
7 | - name: Play 2 - Task 1
8 | debug:
9 | msg: "Play 2 - Task 1"
--------------------------------------------------------------------------------
/Working with include and import module in Ansible/tasks-1.yml:
--------------------------------------------------------------------------------
1 | - name: Play 1 - Task 2
2 | debug:
3 | msg: Play 1 - Task 2
--------------------------------------------------------------------------------
/ansible_automation.code-workspace:
--------------------------------------------------------------------------------
1 | {
2 | "folders": [
3 | {
4 | "path": "."
5 | },
6 | {
7 | "path": "../StockTradeAutomation"
8 | }
9 | ],
10 | "settings": {}
11 | }
--------------------------------------------------------------------------------