我的目标是使用剧本中直接给出的凭据在不同的主机上执行shell命令。到目前为止,我已经尝试了两件事。
尝试:
- name: test
shell:
command: "whoami"
with_items: "{{lookup('file', '../files/deviceList.txt').splitlines()}}"
delegate_to: "{{item.split(';')[0]}}"
args:
ansible_connection: network_cli
ansible_network_os: ios
ansible_user: "{{ cred_ios_r_user }}"
ansible_password: "{{ cred_ios_r_pass }}"
尝试2:
- name: set default credentials
set_fact:
ansible_connection: network_cli
ansible_network_os: ios
ansible_user: "{{ cred_ios_r_user }}"
ansible_password: "{{ cred_ios_r_pass }}"
with_items: "{{lookup('file', '../files/deviceList.txt').splitlines()}}"
delegate_to: "{{item.split(';')[0]}}"
- name: test
shell:
command: "whoami"
with_items: "{{lookup('file', '../files/deviceList.txt').splitlines()}}"
delegate_to: "{{item.split(';')[0]}}"
变量{{cred_ios_r_user}}
中的Username为'User1'
。但是当我查看Ansible的输出时,它告诉我它使用了默认的ssh用户名为"SSH_User"
。
我需要改变什么,使Ansible采取给定的凭据?
首先要检查的是它的"remote_user"模块属性:
- name: DigitalOcean | Disallow root SSH access
remote_user: root
lineinfile: dest=/etc/ssh/sshd_config
regexp="^PermitRootLogin"
line="PermitRootLogin no"
state=present
notify: Restart ssh
接下来是ssh_keys。默认情况下,您的连接有自己的私钥,但您可以通过ansible-playbook命令、inventory-file或job-vars中的变量的额外参数来覆盖它:
vars:
ansible_ssh_user: "root"
ansible_ssh_private_key_file: "{{ role_path }}/files/ansible.key"
所以如果你愿意,你可以设置自定义键,你在var或文件:
- name: DigitalOcean | Add Pub key
remote_user: root
authorized_key:
user: "{{ do_user }}"
key: "{{ lookup('file', do_key_public) }}"
state: present
你在我的auto-drop -digitalocean-role中获取了更多信息
你的变量应该是…可用于任务的变量,而不是传递给shell
模块的参数。简而言之:
- name: test
vars:
ansible_connection: network_cli
ansible_network_os: ios
ansible_user: "{{ cred_ios_r_user }}"
ansible_password: "{{ cred_ios_r_pass }}"
shell:
command: "whoami"
with_items: "{{ lookup('file', '../files/deviceList.txt').splitlines() }}"
delegate_to: "{{ item.split(';')[0] }}"
同时,这看起来像一个坏的做法。您通常会使用add_host
使用正确的主机和凭据构建内存中库存,然后使用自然主机批处理播放循环运行任务。就像
- name: manage hosts
hosts: localhost
gather_facts: false
tasks:
- name: add hosts to inventory
add_host:
name: "{{ item.split(';')[0] }}"
groups:
- my_custom_group
ansible_connection: network_cli
ansible_network_os: ios
ansible_user: "{{ cred_ios_r_user }}"
ansible_password: "{{ cred_ios_r_pass }}"
with_items: "{{ lookup('file', '../files/deviceList.txt').splitlines() }}"
- name: run my command on all added hosts
hosts: my_custom_group
gather_facts: false
tasks:
- name: test command
shell: whoami
或者,你可以从你的csv文件中创建一个完整的库存,并直接使用它,或者使用/开发一个库存插件,将直接读取你的csv文件(如在这个例子中)