如何在 ansible 角色中使用 vars

Nit*_*rma 1 ansible yaml

我想创建一个 ansible 角色来使用 ssh_keys 添加用户

\n\n
\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 ansible.cfg\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 hosts\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 playbooks\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 add_user.yml\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 roles\n    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 add-user\n        \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 files\n        \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 ansible.pub\n        \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 dhirendra.pub\n        \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 nitigyas.pub\n        \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 vinayaks.pub\n        \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 tasks\n        \xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.yml\n        \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 vars\n            \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.yml\n
Run Code Online (Sandbox Code Playgroud)\n\n

tasks/main.yml 文件是:

\n\n
---\n- name: AddUser in the server\n  user: \n   name: ansible\n   password: $6$sHQAZJ32E$ujHauabN7ZTbOQ/zhT5899EIaFErOecXYvTEyhekexy4dydsAXTGdUpaB8M4fQf2UGpZgX/Zg2Uv6areeuv/r0\n   comment: Ansible Configuration Mgmt\n   shell: /bin/bash\n\n- name: Add SSH key to users home direcotory\n  authorized_key: \n   user: "{{ item.name }}"\n   key: "{{ item.file }}"\n   state: present\n  with_items: \n   - ssh_vars\n...\n
Run Code Online (Sandbox Code Playgroud)\n\n

vars/main.yml 文件是:

\n\n
---\nssh_vars:    \n - { name: "ansible" , file: \'ansible.pub\' }\n
Run Code Online (Sandbox Code Playgroud)\n\n

当我运行这个角色时,我收到以下错误

\n\n
PLAY [backend1.greengst.com] *************************************************************************************************************\n\nTASK [add-user : AddUser in the server] **************************************************************************************************\nok: [backend1.greengst.com]\n\nTASK [add-user : Add SSH key to users home direcotory] ***********************************************************************************\nfatal: [backend1.greengst.com]: FAILED! => {"failed": true, "msg": "the field \'args\' has an invalid value, which appears to include a variable that is undefined. The error was: \'ansible.vars.unsafe_proxy.AnsibleUnsafeText object\' has no attribute \'name\'\\n\\nThe error appears to have been in \'/etc/ansible/roles/add-user/tasks/main.yml\': line 9, column 3, but may\\nbe elsewhere in the file depending on the exact syntax problem.\\n\\nThe offending line appears to be:\\n\\n\\n- name: Add SSH key to users home direcotory\\n  ^ here\\n"}\nDebugger invoked\n
Run Code Online (Sandbox Code Playgroud)\n

Kon*_*rov 5

问题在于您使用的方式with_items:裸变量已经很长一段时间不受支持了。

像这样纠正你的循环:with_items: "{{ ssh_vars }}"