ansible:with_items的使用

本文详细介绍了如何在Ansible playbook中使用with_items进行循环操作,包括在playbook中定义循环、自定义值输出、通过item获取指定值、利用with_items创建文件以及与shell模块的结合使用,通过实例展示了每个用法。
摘要由CSDN通过智能技术生成


1. 在playbook中使用循环with_items

[root@server4 ~]# vim /etc/ansible/hosts
172.25.60.2
testB.westos.com ansible_host=172.25.60.1
testC ansible_host=172.25.60.6

[testA]
test1 ansible_host=172.25.60.5

[testB]
172.25.60.3

[test:children]
testA
testB

with_items:将groups.ungrouped中返回的信息,一条一条的放到item中,并一条一条输出

[root@server4 ~]# cat xh.yml 
---
- hosts: testB
  remote_user: root
  gather_facts: no  # 禁止testB这台主机的fact的信息
  tasks:
  - debug:
      msg: "{
   {item}}"
    with_items: "{
   {groups.ungrouped}}"  

测试:

[root@server4 ~]# ansible-playbook xh.yml 

PLAY [testB] *******************************************************************

TASK [debug] *******************************************************************
ok: [172.25.60.3] => (item=172.25.60.2) => {
   
    "msg": "172.25.60.2"
}
ok: [172.25.60.3] => (item=testB.westos.com) => {
   
    "msg": "testB.westos.com"
}
ok: [172.25.60.3] => (item=testC) => {
   
    "msg": "testC"
}

PLAY RECAP *********************************************************************
172.25.60.3                : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

2. 自定义with_items的值输出

[root@server4 ~]# cat xh.yml 
---
- hosts: testB
  remote_user: root
  gather_facts: no  # 禁止手机testB这台主机的fact的信息
  tasks:
  - debug:
      msg: "{
   {item}}"
    with_items:  # 或者[1,2,3]
    - 1
    - 2
    - 3

测试:

[root@server4 ~]# ansible-playbook xh.yml 

PLAY [testB] *******************************************************************

TASK [debug] *******************************************************************
ok: [172.25.60.3] => (item=1) => {
   
    "msg": 1
}
ok: [172.25.60.3] => (item=2) => {
   
    "msg": 2
}
ok: [172.25.60.3] => (item=3)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值