Ansible 在某些任务填充密码后通过 ssh 连接



在 Ansible 中,我需要执行一组任务并从第三方获取密码(这部分已处理),然后使用这些 SSH 凭据进行连接。

问题是,当我这样做时,似乎循环浏览库存的最佳方法是包含任务列表,这很棒。主要问题是,只有当我在我的 main.yml 剧本中将主机指定给本地主机时,我才能获得这个。(或设置为服务器组的名称并指定连接:local)这使得命令模块在本地执行,这违背了目的。

我尝试查看SSH模块,但看起来它没有注册以给我检测到no_action。我知道我可能忽略了一些刺眼的东西。

我稍后会发布更接近确切的代码,但我现在拥有的是

main.yml 
---
- hosts: localhost
tasks:
- name: subplay
include: secondary.yml
vars:
user:myUser
address:"{{hostvars[item].address}}"
with_items: hostvars['mygroup']

secondary.yml
---
- name: fetch password
[...fethchMyPassword, it works]
register: password
- name: 
[...Need to connect with fetched user for this task and this task only..]
command: /my/local/usr/task.sh

我想在那里连接并执行脚本,但似乎无论我尝试什么,它要么根本无法执行,要么在本地执行。

此外,我可能会注意到我签出了 https://docs.ansible.com/ansible/latest/plugins/connection/paramiko_ssh.html https://docs.ansible.com/ansible/latest/plugins/connection/ssh.html 但一定是做错了什么

在我看来,只有您的获取任务需要委派给 localhost,其余的my_group,当您拥有所有连接信息时,通过将值设置为 ansible_{用户、ssh_pass、密码} 来设置与set_facts的连接,试试这个:

main.yml 
---
- hosts: mygroup # inventory_hostname will loop through all your hosts in my_group
tasks:
- name: subplay
include: secondary.yml
vars:
user:myUser
address:"{{hostvars[inventory_hostname].address}}"
secondary.yml
---
- name: fetch password 
[...fethchMyPassword, it works]
delegate_to: localhost # this task is only run on localhost
register: password    
- set_fact: # use registered password and vars to setup connection
ansible_user: "{{ user}}"
ansible_ssh_pass: "{{ password }}"
ansible_host: "{{ address }}"

- name: Launch task # this task is run on each hosts of my_group
[...Need to connect with fetched user for this task and this task only..]
command: /my/local/usr/task.sh

启动此

ansible-playbook main.yml

尝试用你的 secondary.yml 编写一个角色,用你的 main.yml 编写一个剧本

最新更新