循环任务中有条件

问题描述 投票:0回答:1

我想创建以下任务:

  • 创建群组
  • 创建用户
  • 在authorized_keys文件中提供默认条目
  • 如果定义了 ssh_pubkey 变量,则将其附加到authorized_keys 文件中

我的任务:

- 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 变量的用户。

variables ansible conditional-statements
1个回答
0
投票

看起来

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
© www.soinside.com 2019 - 2024. All rights reserved.