ANSIBLE9: Conditional statement "Go"

Source: Internet
Author: User
Tags vars

In some cases, the result of play depends on the result of a variable, fact, or the execution of the previous task, thus requiring the use of a conditional statement. First, when
Sometimes the specific host needs to skip specific steps, such as when installing the package, you need to specify the host operating system type, or when the operating system's hard disk is full, you need to clear the file, you can use the When statement to make judgments. When the keyword is followed by a Python expression, you can use any variable or fact in the expression, and when the result of the expression returns false, the task is skipped.

1. Basic usage, Example:

---
-Name:install VIM
Hosts:all tasks:
-Name:install VIM via Yum
yum:name=vim-enhanced state=installed
when:ansible_os_family = = "RedHat"
-Name:install VIM via apt
Apt:name=vim state=installed
when:ansible_os_family = = "Debian"
-Name:unexpected OS Family
Debug:msg= "OS Family {{ansible_os_family}} is not supported" Fail=yes
When:not ansible_os_family = = "RedHat" or ansible_os_family = = "Debian"

The conditional statement also has a usage that allows you to pause when you reach a certain condition and wait for your input to be confirmed. In general, when Ansible encounters an error, it will end up running directly. You can actually use the pause module when you encounter a situation that is not expected, which allows the user to decide whether to continue running the task themselves:

-Name:pause for unexpected conditions
pause:prompt= "Unexpected OS"
When:ansible_os_family! = "RedHat"
2. Use JINJA2 syntax in when, example:
Tasks:-command:/bin/false register:result #将命令执行的结果传递给result变量 ignore_errors:true #忽略错误-command: /bin/something when:result|failed #如果注册变量的值 is the task failed return True-command:/bin/something_else when:result|succes S #如果注册变量的值是任务success则返回true-command:/bin/still/something_else when:result|skipped #如果注册变量的值是任务skipped则返回tru E-command:/bin/foo when:result|changed #如果注册变量的值是任务changed则返回true
-Hosts:all user:root vars:epic:true tasks:-Shell:echo "This certainly is epic!"      When:epic-shell:echo "This certainly isn't epic!" When:not Epic
4. If the variable does not exist, it can be skipped by jinja2 ' defined ' command, example:
Tasks:-Shell:echo "I ' ve got ' {{foo}} ' and am not afraid to use it!" When:foo is defined-fail:msg= "bailing out. This play requires ' bar ' "When:bar are not defined
5. When to use in a looping statement, example:
Tasks:-Command:echo {{Item}} With_items: [0, 2, 4, 6, 8, ten] When:item > 56, using when in include and roles:
Examples used in the include:-Include:tasks/sometasks.yml When: ' ' reticulating splines ' in output '
Examples used in roles:-hosts:webservers roles:-{role:debian_stock_config, when:ansible_os_family = = ' Debian '}
Second, conditional import
Sometimes you might want to work in a different way in a playbook, like installing Apache,apache on Debian and CentOS, except when statements, you can use the following example to solve:
----Hosts:all remote_user:root vars_files:-"vars/common.yml"-["vars/{{ansible_os_family}}.yml", "Vars/os _defaults.yml "] tasks:-name:make sure Apache is running service:name={{Apache}} state=running many different yml files just contain keys and values As follows:
---# for vars/centos.ymlapache:httpdsomethingelse:42

If the operating system is ' CentOS ', the first file to be imported by ansible will be ' vars/centos.yml ', followed by '/var/os_defaults.yml ' If this file does not exist. And if you don't find it in the list, you'll get an error. In the Debian system, the first view will be ' vars/debian.yml ' instead of ' vars/centos.yml ', if not found, then look for the default file ' Vars/os_defaults.yml '.

Third, With_first_found
Sometimes, we want to choose different configuration files based on different operating systems, and the location of configuration files can be solved by With_first_found:
-Name:template a file template:src={{item}} dest=/etc/myapp/foo.conf With_first_found:-Files:-{A Nsible_distribution}}.conf-default.conf paths:-search_location_one/somedir/-/opt/other_l ocation/somedir/
Iv. Failed_when
Failed_when is actually a ansible error handling mechanism, which is the combination effect of the When conditional statement used by the Fail module. Examples are as follows:
-name:this command Prints FAILED when it fails command:/usr/bin/example-command-x-y-z register:command_result FA Iled_when: "' FAILED ' in Command_result.stderr" we can also directly pass the Fail module and the When condition statement, written as follows:
-name:this command Prints FAILED when it fails command:/usr/bin/example-command-x-y-z register:command_result IG Nore_errors:true-name:fail the play if the previous command did not succeed Fail:msg= "the command failed" when: "' FA Iled ' in Command_result.stderr ' five, Changed_when
When we control some remote hosts performing certain tasks, when the task executes successfully on the remote host, the state changes, the changed status response is returned, the status is not changed, an OK state response is returned, and when the task is skipped, the skipped status response is returned. We can manually change the changed response status through Changed_when. Examples are as follows:
-Shell:/usr/bin/billybass--mode= "Take Me to the river" Register:bass_result changed_when: "Bass_result.rc! = 2" #只有该条task执行以后, the value of bass_result.rc is not 2 o'clock to return changed status # This would never report ' changed ' status-shell:wall ' beep ' ch Anged_when:false #当changed_when为false时, the task will never return to the changed state after execution

ANSIBLE9: Conditional statement "Go"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.