Wednesday, May 17, 2017

YMLS of Me

1) Yaml file to create an empty file

---
- hosts: host1
  tasks:
  - name : create file
    file : path=/root/ansibl_test_file state=touch
...

2) File to check ping  

---
- hosts: host1
  tasks:
  - name:  test ping
    ping:
...

3) Yaml file to perform sync between folders

---
- hosts: host1
  tasks:
  - name: perform rync between folders
    synchronize: src=/mnt/radio_prompts dest=/mnt/
...

4)  Compare the file in remote with template and modify file if any changes

---
- hosts: host1
  tasks:
   - name: compare with template and modify file if any changes
     template: src=/root/ymls/template/exports.jn2 dest=/etc/exports
...

5) Yaml file to add a single user

---
- hosts: host1
  tasks:
  - name : add user and ensure present
    user: name=lukman comment=test_user uid=500
...

6) To redirect remote server cat output to a file on master server

---
- hosts: ss
  tasks:

   - name: Sample play for a command
     command: cat /etc/motd
     register: mymotd

   - name: redirect motd output to std out
     debug: var=mymotd

  - name: copy variable value to a file on a local server
     local_action: copy content="{{ mymotd }}"        dest="/home/bhr_moham607/ymls/l0210_motd"

Note : Local action is used to redirect to local master node and redirect the output in the remote server only use below syntax



   - name: copy variable value to a file on remote server
     copy: content="{{ mymotd }}" dest=/home/bhr_moham607/ymls/l0210_motd
.. 

7) To execute  script from master and redirect output to remote server itself



---
- hosts: ss
  tasks:
  - name: use script module to execute local script on remote
    script: /home/user/ymls/SERVER_INFO_OUTPUT_U.sh >  /home/user/ymls/one

...

8)  To execute  script from master and redirect output to Master server 
---
- hosts: ss
  tasks:
  - name: use script module to execute local script on remote
    script: /home/bhr_moham607/ymls/SERVER_INFO_OUTPUT_U.sh
    register: scoutput
  - name: local copy
    local_action: copy content="{{ scoutput.stdout }}" dest=/home/bhr_moham607/ymls/local_l0210

...

Note: If the output of a variable is redirected to a file it is better to use .stdout for formatting


8)  Using Ansible fact's as variable

- name: create directory with ansible fact
  file: dest=/home/bhr_moham607/ymls/testD/{{ ansible_hostname }} state=touch
..


9) Example for Command, register and Debug module
---
- hosts: ss
  tasks:

   - name: Sample play for a command
     command: cat /etc/motd
     register: mymotd

   - name: redirect motd output to std out
     debug: var=mymotd
...

10) Roles

a) Creating directory with the help of Roles
---
- hosts: ss
  roles:
  - { role: test }

---
- name: create directory
  file: dest=/home/bhr_mohamXXX/ymls/testD state=directory

- name: touch file
  file: dest=/home/bhr_mohamXXX/ymls/testD/testfile1 state=touch
...
[bhr_mohamXXX@l0202 tasks]$ pwd
/home/bhr_moham607/ymls/roles/test/tasks

# cat /home/bhr_moham607/ymls/roles/test/vars/main.yml
---
dirname:
 one:
 two:
 three:

cat /home/bhr_moham607/ymls/roles/test/tasks/main.yml
---
- name: create directory
  file: dest=/home/bhr_moham607/ymls/testD state=directory

- name: touch file
  file: dest=/home/bhr_moham607/ymls/testD/testfile1 state=touch

- name: create directroy from variable
  file: dest=/home/bhr_moham607/ymls/testD/{{ item }} state=directory
  with_items: "{{ dirname }}"
...

11) With_items: Create empty files

---
- hosts: ss
  tasks:
  - name: To test and invoke with_items module and create file
    file: path=/home/bhr_moham607/{{item}} state=touch
    with_items:
      - test1
      - test2
      - test3
      - test4
...

12) A Simple yaml file with when condition

---
 - hosts: ss
   tasks:
     - name: Create file when OS version is 6
       file: path=/home/moham607/rhel6test state=touch
       when: facter_operatingsystemrelease == "6.8"

     - name: Create file when OS version is NOT 6
       file: path=/home/moham607/rhelothertest state=touch
       when: facter_operatingsystemrelease != "6.8"
...

Above YAML will create file named rhel6test  when the OS version is 6.8 when the OS version is NOT 6.8 then it will create a file named rhelothertest 

13) When With AND, OR Condition


---
 - hosts: ss
   tasks:
     - name: Create file when OS version is 6.8 and OS is Redhat
       file: path=/home/bhr_moham607/rhel6.8file state=touch
       when:
         - facter_operatingsystemrelease == "6.8"
         - facter_osfamily == "RedHat"
     - name: Create file when OS version is 6.8 and OS is not Readht
       file: path=/home/bhr_moham607/otherostestfile state=touch
       when:
         - facter_operatingsystemrelease == "6.8"
         - facter_osfamily != "RedHat"

...


Note: And condition need to be mentioned like list items tasks or like below also

   - name: Create file when OS version is 6.8 and OS is Redhat
       file: path=/home/bhr_moham607/rhel6.8file state=touch
       when: ( facter_operatingsystemrelease == "6.8" and facter_osfamily == "RedHat" )

Example for AND and OR condition

---
 - hosts: ss
   tasks:
     - name: Create file when OS version is 6.8 and OS is Redhat
       file: path=/home/bhr_moham607/Simpletestfile state=touch
       when: ( facter_osfamily == "RedHat" and (facter_operatingsystemrelease == "6.8" or facter_operatingsystemrelease == "6.6"))

In the above Example OS should be Redhat but version can either 6.8 or 6.6 in version any of the condtion has to be true and OS has true then in that case it will create a file called Simpletestfile

14) When condition with filter option

     - name: Create file when OS version is 6.8 and OS is not Readht
       file: path=/home/bhr_moham607/otherostestfile state=touch
       when: ( facter_operatingsystemrelease|int >= 6 )

In the above example task will create a file when the OS releease is greater than 6

Note : using this filter method we can't compare folating point values. Like eg: 6.8

15) Testing when and with item 

---
 - hosts: ss
   tasks:
    - name: check when and with item
      debug: msg={{ item }}
      with_items: [ 0, 2, 4, 6, 8, 10 ]
      when: item > 5
...

skipping: [l0210] => (item=0)
skipping: [l0210] => (item=2)
skipping: [l0210] => (item=4)
ok: [ansic1] => (item=6) => {
    "item": 6,
    "msg": 6
}
ok: [ansic1] => (item=8) => {
    "item": 8,
    "msg": 8
}
ok: [ansic1] => (item=10) => {
    "item": 10,
    "msg": 10

}

Debug command will be executed only when the item value is greater than 5. We can see the difference in the above output.

Note : using this filter method we can't compare floating point values. Like eg: 6.8

when with Custom Facts

tasks:
     - name: Check value from custom fact and create a file
       file: path=/home/moham607/factright state=touch
       when: ansible_local.serverinfo.info.servertype == "vm-esx5"


As like normal facts comparision we can use custom facts also to compare with When and execute as per result.

16) Ansible lineinfile Syntax


---
 - hosts: test
   tasks:
   - name: To check lineinfile syntax
     lineinfile: name="/root/ymls/testlnfile" state=present regexp='i love' line='i love india'

...


The regular expression to look for in every line of the file. For state=present, the pattern to replace if found; only the last line found will be replaced. For state=absent, the pattern of the line to remove. Uses Python regular expressions; see

Before Running

[root@ansic1 ymls]# cat /root/ymls/testlnfile
i love
i love ece
i love briyani
i love IT

After running 1st time

[root@ansic1 ymls]# cat /root/ymls/testlnfile
i love
i love ece
i love briyani
i love india

After running 2nd time

[root@ansic1 ymls]# cat /root/ymls/testlnfile
i love
i love ece
i love briyani
i love india

16) failed_when Syntax
---
 - hosts: ss
   tasks:
    - name: check failed when
      command: rm /tmp/file1
      register: testoutput
      failed_when: "'Operation not permitted' in testoutput.stderr"
    - name:
      command: echo hi
...

17) ipfilter
---
 - hosts: ss
   tasks:
     - name: Take the IP of server using facts and check with the help of IP filter and print
       debug: var="IP address of server is ({{facter_fqdn}} | type_debug)"
#       when: facter_fqdn
     # when: (ansible_eth3.ipv4.address | ipv4)
...

Mandatory
---
 - hosts: ss
   tasks:
   - name: Check Mandotry filter setting
     debug: msg={{ variable | mandatory }}

...

18) Replace module example


---
- hosts: test
  tasks:
   - name: Testting replace module
     copy: src=/etc/passwd dest=/root/TEST_PASSWD
   - name: use replace module to find and replace bash
     replace: dest=/root/TEST_PASSWD regexp='/bin/bash' replace='/sbin/nologin' backup=yes

...

19) Replace with validate option

replace with validate will update option will update the file only if the Syntax is correct. In below example replace will search # and replace with test and checks the syntax with validate option. Only if the syntax is OK changes from file in tmp will be updated to the original file

---
- hosts: ss
  tasks:
  - replace:
      dest: /home/bhr_moham607/sudoers
      regexp: '#'
      replace: 'Test'
      backup: yes
      validate: '/usr/sbin/visudo -cf %s'

...

Tuesday, May 16, 2017

Where to use Hyphen and colon

Hyphen is used to specify list items, and colon : is used to specify dictionary items or key-value pair. A comparable example with another language (e.g. Python) will make this clear. 

Let's say we have a list my_list like this in Python

my_list = ['foo', 'bar']

In Ansible you will specify this list items with hyphen (Space should be there between hyphen and list items:

my_list:
  - foo
  - bar

Now let's say you have a key-value pair or dictionary like this:

my_dict = {
    'key_foo': 'value_foo',
    'key_bar': 'value_bar'
}

In Ansible, you will use colon instead of hyphen for key-value pair or dictionary:

my_dict:
  key_foo: value_foo
  key_bar: value_bar

Inside a playbook you have a list of plays and inside each play you have a list of tasks. 

Since tasks is a list, each task item is started with a hyphen like this:

tasks:
  - task_1
  - task_2

Now each task itself is a dictionary or key value pair. Your example task contains two keys, name and yum. yum itself is another dictionary with keys name, state etc.

So to specify task list you use hyphen, but since every task is dictionary they contain colon.

Example 

---
- hosts: ss
  tasks:
    - name: test connection
      ping:
      remote_user: bhr_moham607
    - name : test connectin2
      ping:

That's what tasks is. Each hyphen starts a new list item (a task), and each list item may have multiple key-value pairs (properties of the task).

In the above example, name is the word which defines the list of items, so we are adding hyphen to all  list of items as per above example.

Thursday, May 11, 2017

My Commands list


1) Command to check the list of hosts

# ansible-playbook file.yml --list-hosts

2)  To run a playbook yml file

# ansible-playbook <file2.yml>

3) to run adhoc command

# ansible ss -u bhr_moham607 --key-file=/home/bhr_moham607/.ssh/id_rsa -m ping

4) To list plays in a file


#  ansible-playbook --list-tasks file.yml

Tuesday, May 9, 2017

What is Task

Here is what a basic task looks like. As with most modules, the service module takes key=value arguments:

tasks:
  - name: make sure apache is running
    service: name=httpd state=started

The command and shell modules are the only modules that just take a list of arguments and don’t use the key=value form. This makes them work as simply as you would expect:

tasks:
  - name: enable selinux
    command: /sbin/setenforce 1

The command and shell module care about return codes, so if you have a command whose successful exit code is not zero, you may wish to do this:

tasks:
  - name: run this command and ignore the result
    shell: /usr/bin/somecommand || /bin/true
Or this:

tasks:
  - name: run this command and ignore the result
    shell: /usr/bin/somecommand
    ignore_errors: True

If the action line is getting too long for comfort you can break it on a space and indent any continuation lines:

tasks:
  - name: Copy ansible inventory file to client
    copy: src=/etc/ansible/hosts dest=/etc/ansible/hosts
            owner=root group=root mode=0644

Variables can be used in action lines. Suppose you defined a variable called vhost in the vars section, you could do this:

tasks:
  - name: create a virtual host file for {{ vhost }}
    template: src=somefile.j2 dest=/etc/httpd/conf.d/{{ vhost }}

To check the syntax of a playbook, use ansible-playbook with the --syntax-check flag. This will run the playbook file through the parser to ensure its included files, roles, etc. have no syntax problems.

Look at the bottom of the playbook execution for a summary of the nodes that were targeted and how they performed. General failures and fatal “unreachable” communication attempts are kept separate in the counts.


If you ever want to see detailed output from successful modules as well as unsuccessful ones, use the --verbose flag. This is available in Ansible 0.5 and later.