我有一个剧本,对于其中一台主机,我需要的连接方式根据之前是否成功完成某些任务而有所不同。
在这种特定情况下,其中两个之间有一条隧道,其中一个通过该隧道路由所有流量,因此配置完成后,我需要使用另一个作为跳线盒才能连接 - 但我可以想象许多其他情况您可能想在剧本中更改连接方法,就像修改用户/密码一样简单。
如何才能有条件连接方法?
我不能简单地使用 set_fact
进行更新,因为当我完成该任务时,ansible 已经尝试过,并且可能无法在开始时“收集事实”,并且不会继续。
最佳答案
当然,这个问题的问题在于细节,但总的来说,我认为使用 add_host
将是实现您想要的操作的最清晰的方法。您还可以根据每个任务更改连接
,或者有条件地更改针对该主机的整个剧本的连接
:
- hosts: all
connection: ssh # <-- or whatever bootstrap connection plugin
gather_facts: no
tasks:
- command: echo "do something here"
register: the_thing
# now, you can either switch to the alternate connection per task:
- command: echo "do the other thing"
connection: lxd # <-- or whatever
when: the_thing is success
# OR, you can make the alternate connection the default
# for the rest of the current playbook
- name: switch the rest of the playbook
set_fact:
ansible_connection: chroot
when: the_thing is success
# OR, perhaps run another playbook using the alternate connection
# by adding the newly configured host to a special group
- add_host:
name: '{{ ansible_host }}'
groups:
- configured_hosts
when: the_thing is success
# and then running the other playbook against configured hosts
- hosts: configured_hosts
connection: docker # <-- or whatever connection you want
tasks:
- setup:
关于ssh - 根据给定条件设置不同的ansible连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56208668/