ansible

yml文件中申明vars时需要用双引号包起来
- hosts: test
  vars:
      path: "{{ base_path }}/test"
      


-e EXTRA_VARS, --extra-vars=EXTRA_VARS   (优先级最高)
--extra-vars 实现vars替换、定义
--extra-vars  '{"xx":["a","b","c"]}' 
--extra-vars "hosts=test user=temp"
--extra-vars "@file.json"

cat file.json
host: test
user: temp

变量优先级:
1. extra vars(-e)
2. inventory
3. 系统发现的facts


yml中字符串转数字
tasks:
  - shell: echo "sas"
    when: start|int >= 6

满足条件,任务失败:
tasks:
- command: echo failed
register: command_result
failed_when: "'failed' in command_result.stdout"


task:
- command: echo failed
register: command_result
ignore_errors: true

- name: failed echo
fail: msg="echo failed"
when:
"'failed' in command_result.stdout"

with_first_found:

循环:
with_items:
- { name: 'testuser1', groups: 'wheel' }
- iter_test
- "{{ iter_tes }}"

嵌套循环:
- name: give users access to multiple databases
mysql_user: name={{ item[0] }} priv={{ item[1] }}.*:ALL append_privs=yes password=foo
with_nested:
- [ 'alice', 'bob' ]
- [ 'clientdb', 'employeedb', 'providerdb' ]

遍历字典:
tasks:
- name: Print phone records
debug: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
with_dict: {'alice':{'name':'Alice Appleworth', 'telephone':'123-456-789'},'bob':{'name':'Bob Bananarama', 'telephone':'987-654-3210'} }


并行遍历:如果列表数目不匹配,用None补全(a-1,b-2,c-3,d-4,e-None)
tasks:
  - debug: "msg={{ item.0 }} and {{ item.1 }}" 
with_together:
- [ 'a', 'b', 'c', 'd','e' ]
- [ 1, 2, 3, 4 ]


遍历列表和索引:
- name: indexed loop demo
debug: "msg='at array position {{ item.0 }} there is a value {{ item.1 }}'"
with_indexed_items: [1,2,3,4]


重试循环: "重试次数retries" 的默认值为3,"delay"为5。
- action: shell /usr/bin/foo
register: result
until: result.stdout.find("all systems go") != -1
retries: 5
delay: 10



with_first_found: 找到一个文件,找到返回,找不到报错
with_random_choice: 随机选一个

循环程序的结果:
tasks:
- debug: "msg={{ item }}"
with_lines: ps aux

序列循环: 创建4 个用户组分表是组group1 group2 group3 group4 // with_sequence: start=4 end=16 stride=2 4-16之间得偶数
tasks:
- group: name=group{{ item }} state=present
with_sequence: count=4

循环主机清单:
with_items: "{{ groups['all'] }}"
with_items: play_host 执行主机清单
with_inventory_hostnames: all
with_inventory_hostnames: all:!test 排除不在test的主机
原文地址:https://www.cnblogs.com/moonypog/p/11081871.html