Wednesday, August 28, 2019

How to run ansible playbook with sudo command


#Following steps will cover how to run ansible playbook with sudo passwd saved

 1) Install Ansible (config EPEL repo)
 #yum install ansible -y

 2) Create inventory file
 #vi inventory
[cluster:vars]
k_ver="linux-image-4.13.0-26-generic"
ansible_user=<username>  # ssh login user
ansible_ssh_user=<username>
ansible_ssh_pass='{{ my_cluser_sudo_pass }}'
ansible_become_pass='{{ my_cluser_sudo_pass }}'

[cluster]
server1.example.com
server2.example.com

3) Create password valut file


#ansible-vault create passwd.yml

Give the valult password to create passwd.yml
then add below content my_cluser_sudo_pass: <passwd>

4) Create the playbook file 'test-playbook.yml' #vim test-playbook.yml
       
 
---
- hosts: genf
  tasks:
    - name: get hostname
      command: /usr/bin/sudo /usr/bin/sh -c ' dmidecode -t 1'
      changed_when: False
      register: hostname

    - name: get uptime
      become: yes
      become_method: sudo
      shell: |
       cat <
       `host $(hostname) | awk '{print $1}'`
       `host $(hostname) | awk '{print $4}'`
       EOF
      changed_when: False
      register: uptime

    - debug: var={{ item }}
      with_items:
        - hostname.stdout
        - uptime.stdout

 5) Now we can run ansible-playbook


#ansible-playbook -i inventory --ask-vault-pass --extra-vars '@passwd.yml' test-playbook.yml 

To save the output to output.txt file, run below command

 #ansible-playbook -i inventory --ask-vault-pass --extra-vars '@passwd.yml' test-playbook.yml  | tee output.txt 2>&1

No comments:

Post a Comment

Create rpm and deb using fpm

Create rpm and deb using fpm  fpm -s dir -t rpm -n unbound-exporter -v 1.0 --prefix /usr/bin unbound_exporter   fpm -s dir -t rpm -n unbound...