当前位置:网站首页>Ansible learning summary (9) -- ansible loop, condition judgment, trigger, processing failure and other task control use summary

Ansible learning summary (9) -- ansible loop, condition judgment, trigger, processing failure and other task control use summary

2022-07-07 17:40:00 Technology d life

One 、 Simple cycle

Use loop Format of assignment list :

loop:  ## Assignment list 
- value1
- value2
- ...
{
   {item}}  ## Iteration variable name 

stay playbook Use in

vim user.yml

---
- name: create user
  hosts: server2
  tasks:
    - name: create user
      user:
        name: "{
   {item}}"  ## Iteration variable name 
        state: present
      loop:  ## Assignment list 
        - user1
        - user2
        - user3

User setup succeeded  

  Defining variables

vim user_list.yml

---
USERS:  ## Defining variables 
  - user1
  - user2
  - user3

To write yaml file

vim user.yml

---
- name: create user
  hosts: server2
  vars_files: ./user_list.yml
  tasks:
    - name: create user
      user:
        name: "{
   {item}}"
        state: absent
        remove: yes
      loop:
        "{
   {USERS}}"  ## There is no need to add... When assigning values here -

Delete user succeeded

Two 、 Circular hash or dictionary list

Give different services different states

Example : by server3 Host setup user , And give the password ( The password here must be encrypted , Use  rhel8  Of  openssl passwd -6  Encrypt the password ).

vim user.yml

---
- name: create user
  hosts: server3
  tasks:
    - name: create user
      user:
        name: "{
   { item.user }}"
        password: "{
   { item.passwd }}"
        state: present
      loop:
        - user: user1
          passwd: "$6$P2MmG.dGe59uEe0R$SVmq6oojHWvYVK.BZhmL7pWjb7zVKRkUM.Rp2kFbLtl7jS570ZClaVPRZkX9BtfkqlLLCbTrlG7a04YRi/wz3."
        - user: user2
          passwd: "$6$YZcSU4GwSVBnw.ro$wQ0fAO9lB2M1Nwu9tVyBoGiEV/qOzQGBY.UHw2pQiq0GEjYpNW3c2FtG/wWZ0iVpqZi.iCo1x18LjpJg9tGTK/"
        - user: user3
          passwd: "$6$lqv/hz7ynndCR9NR$BmhKzFUsW4XzP9x9eAXv782gYBnxWUGFnh1qYExYwof5PSPk36GnlDKjjeygCSohM0cpncmk.1mkljEAgX3FQ1"

Test connection : 

3、 ... and 、 conditional

Both conditions are met at the same time

when:
-  Conditions 1
-  Conditions 2

One of the conditions

when:
-  Conditions 1 or  Conditions 2

#  It can also be expressed as 
when:
-  Conditions 1
  or
   Conditions 2

  Example : Check whether the file exists (ignore_errors: yes: When the file does not exist , The system will determine the failure , no return value , Add this parameter to ignore the error ).

vim exist.yml

---
- name: test
  hosts: demo
  tasks:
    - name: test
      shell: test -e /mnt/file  ## Use shell The module detects whether the file exists 
      ignore_errors: yes
      register: OUTPUT  ## Register the results to OUTPUT Variable 
      
    - name: show message
      debug:
        msg: /mnt/file is exist
      when: OUTPUT.rc == 0  ## Output result rc Part of it is 0, File exists 
      
    - name: show message
      debug:
        msg: /mnt/file is not exist
      when: OUTPUT.rc == 1  ## Output result rc Part of it is 1, file does not exist 

stay server4 Create... On the host  /mnt/file, stay server2 and server3 Do not create , perform yaml file

Definition of condition judgment

  Example : Add disks , Use conditional statements to detect the disk ( by server2 Add disk to host

adopt ansible Statement can detect

ansible server2 -m shell -a "fdisk -l /dev/vdb"

To write yaml file , Detect the presence of vdb disk

vim vdb.yml

---
- name: test
  hosts: demo
  tasks:
    - name: show message
      debug:
        msg: /dev/vdb is exist
      when:
        - ansible_facts['devices']['vdb'] is defined  ##vdb In existence 
        - inventory_hostname in "server2"  ##hostname by server2 when , The above conditions must be met at the same time 
        
    - name: show message
      debug:
        msg: /dev/vdb is not find
      when:
        - ansible_facts['devices']['vdb'] is not defined
          or
          inventory_hostname not in "server2"  ##vdb Does not exist or hostname Not for server2 when , You can also write a line 

perform yaml file , Get the results

3、 ... and 、 trigger

  • notify: Trigger triggers when a change is encountered  handlers
  • handlers: The action performed after the trigger is triggered

Example : Installation and downloading vsftpd And modify the access home directory ( To write yaml file

vim vsftpd.yml

---
- name: vsftpd
  hosts: server4
  tasks:
    - name: install vsftpd
      yum:
        name: vsftpd
        state: present
    - name: start vsftpd
      service:
        name: vsftpd
        state: started
        enabled: yes
      notify:
        - firewalld  ## When vsftpd The service is set to start automatically , Trigger firewalld modular 

    - name: vsftpd.conf
      lineinfile:
        path: /etc/vsftpd/vsftpd.conf
        line: "anon_root=/mnt"  ## Modify access home directory 
        regexp: "^anon_root"  ## Replaced line 
        backrefs: no  ## Replace when matching , No match, then , Add a line at the end of the file 
      notify:
        - restart vsftpd  ## When the file is replaced , Trigger the module to restart the service 

  handlers:  ## Triggered module , Pay attention to the relationship between here and tasks alignment 
   - name: firewalld
     firewalld:
       service: ftp
       state: enabled
       permanent: yes
       immediate: yes
   - name: restart vsftpd
     service:
       name: vsftpd
       state: restarted

perform yaml file

stay server4 Of  /mnt/file  Add content to , Anonymous access testing  

Four 、 Handling failed tasks

ignore_errors

effect : When play When a task fails, it will terminate (ignore_errors: yes  The task failure will be ignored and the following tasks will continue to run )

Example : Install a non-existent service

vim ignore.yml

---
- name: ignore_errors
  hosts: server3
  tasks:
    - name: install haha
      yum:
        name: haha
        state: present
      ignore_errors: yes  ## Ignore mistakes 
        
    - name: debug
      debug:
        msg: heloo lll

force_handlers

effect : When the task fails play If terminated, the trigger process will also be called

Example : Install a non-existent service , Task failed play There will still be triggers after termination ( Pay attention to removal ignore_errors: yes Interference of

vim force.yml

---
- name: force_handlers
  hosts: server3
  force_handlers: yes  ## After the task fails, it still triggers 
  tasks:
    - name: hostname
      shell:
        hostname
      register: info  ## Use registered variables 
      notify:
        - debug

    - name: install haha
      yum:
        name: haha
        state: present

  handlers:
    - name: debug
      debug:
        msg: "{
   { info['stdout'] }}"  ## Show variables info The output variable of 

changed_when

effect : Controls when a task reports that it has made changes , Suppress changes

Example : test  changed_when: true

vim changed.yml

---
- name: test
  hosts: server4
  tasks:
    - name: install vsftpd
      yum:
        name: vsftpd
        state: present
      changed_when: true  ## When detected vsftpd After installation ( Whether just installed or previously installed ), The report has changed 

server4 Of vsftpd Has been installed before , Should be displayed in green , But it's yellow here

Example : test  changed_when: false

vim changed.yml

---
- name: test
  hosts: server4
  tasks:
    - name: remove vsftpd
      yum:
        name: vsftpd
        state: absent
      changed_when: false  ## When detected vsftpd When uninstalled , The report does not change 

Uninstall... Here vsftpd, There should be a change to yellow , But it's green

failed_when

effect : When the conditions are met, the mandatory task fails , But it doesn't change the behavior of the task itself

Example : create file , Report errors , But the essence has been established

vim failed.yml

---
- name: test
  hosts: server2
  tasks:
    - name: touch file
      file:
        path: /mnt/failedfile
        state: touch
      failed_when: true  ## An error is reported after the file is created 

But the actual file was created successfully

example : Create a file in a directory that does not exist , But report success  

vim failed.yml

---
- name: test
  hosts: server2
  tasks:
    - name: touch file
      file:
        path: /mnt/haha/linuxfile
        state: touch
      failed_when: false  ## No error is reported when the file is not created 

Naturally, the file was not created

block

  • block: Define the tasks to run
  • rescue: Define when block The task that runs after a failed task appears in the sentence
  • always: Define the tasks that will eventually run independently

Example 1: here  /mnt/file  There is

vim block.yml

---
- name: test
  hosts: server4
  tasks:
    - name: check file
      block:
        - name: test
          shell: test -e /mnt/file
        - name: debug
          debug:
            msg: /mnt/file is exist
            
      rescue:
        - name: debug
          debug:
            msg: /mnt/file is not exist
            
      always:
        - name:
          debug:
            msg: good night!

therefore block There is no failure in the sentence , So it won't execute rescue modular  

Example 2: here  /mnt/file  non-existent , Re execution  block.yml, because block There is a failure in the sentence , So execute rescue modular

 

原网站

版权声明
本文为[Technology d life]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071533360935.html