我想创建以下任务:
我的任务:
- name: Create groups
ansible.builtin.group:
name: "{{ item.group }}"
state: present
loop: "{{ role_users_user_details }}"
- name: Create users
ansible.builtin.user:
name: "{{ item.username }}"
groups: "{{ item.group }}"
password: "{{ password | password_hash('sha512') }}"
state: present
loop: "{{ role_users_user_details }}"
- name: Provide required entry authorized_keys
ansible.builtin.copy:
src: ../files/authorized_keys
dest: /home/{{ item.username }}/.ssh/
owner: "{{ item.username }}"
group: "{{ item.username }}"
mode: '0644'
backup: true
loop: "{{ role_users_user_details }}"
- name: Append user pubkey in authorized_keys
ansible.builtin.lineinfile:
dest: /home/{{ item.username }}/.ssh/authorized_keys
line: "{{ item.ssh_pubkey }}"
state: present
insertafter: EOF
loop: "{{ role_users_user_details }}"
when: item.ssh_pubkey is defined <<< Here is the issue
效果:
TASK [role_users : Append user pubkey in authorized_keys] *******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************
task path: <xxx>
skipping: [xxx] => (item={'username': 'xxx_user', 'group': 'xxx_user', 'ssh_pubkey': 'test'}) => {
"ansible_loop_var": "item",
"changed": false,
"false_condition": "item.username.ssh_pubkey is defined",
"item": {
"group": "xxx_user",
"ssh_pubkey": "test",
"username": "xxx_user"
},
"skip_reason": "Conditional result was False"
同时我的 vars.yml 结构如下所示:
role_users_remote_username: "{{ inventory_hostname + '_' + 'user' }}"
role_users_user_details:
- username: "{{ role_users_remote_username }}"
group: "{{ role_users_remote_username }}"
ssh_pubkey: "test-entry"
- username: ansible_usr
group: ansible_usr
目标是运行任务:在authorized_keys中附加用户公钥 - 仅适用于定义了 ssh_pubkey 变量的用户。
看起来
username: ansible_usr
缺少条目 ssh_pubkey:
。尝试像这样修改vars.yml
:
role_users_user_details:
- username: "{{ role_users_remote_username }}"
group: "{{ role_users_remote_username }}"
ssh_pubkey: "test-entry"
- username: ansible_usr
group: ansible_usr
ssh_pubkey: "another-test-entry"
# ^^^ this was missing