Working with playbooks


In this tutorial we will discuss on creating sample playbook to install httpd apache server on target machine.

1) Create hosts file in your project location. Add webserver group and add few target hosts to the hosts file.

cat hosts
[webserver]
localhost

2) Create index.html file in project root location and add some content to it.

cat index.html
<h1> Welcome World </h1>

3) Now create a file called httpd.yml in your project root location and add below content to it. In comment ection we have given full description for each line in this playbook.

cat httpd.yml
- name: Installing httpd on centos-7    # name of the play
  hosts: webserver                      # target hosts group 
  become: true                          # allowing current user to become sudo user 
  become_method: sudo                   # defining sudo method 
  become_user: root                     # defining sudo user on target machine  
  vars:                                 # assigning variables 
    project_root: /var/www/html         # sample key-value pair
  tasks:                                # tasks
  - name: Install Apache Webserver      # task name
    yum: pkg=httpd state=latest         # installing httpd package on remote machine. It will make sure if current installed httpd is not latest one.
  - name: Place the index file at project root        # copying index.html file to target machine
    copy: src=index.html dest={{ project_root }}/index.html owner=apache group=apache mode=0644
  - name: Enable Apache on system reboot               # enabling httpd service on target machine
    service: name=httpd enabled=yes                     
    notify: restart apache                              # invoking handlers 
  handlers:                             # defining handlers
  - name: restart apache                # restart apache - it will work only if caller task state got changed. no action if state didn't changed
    service: name=httpd state=restarted

4) Now run the playbook by invoking below command. It will prompt for password. remove extra arguments if you configured password less communication between ansible control machine and target machine.

ansible-playbook -i hosts httpd.yml -k -k -u <remote_username>

                                                                                                                     
 << Previous                                                                                                                                Next >>
                       
             

No comments:

Post a Comment