木偶中具有位置的数组迭代

Array iteration with position in puppet

我打算实现为每个用户添加多个 ssh 密钥的可能性。 对于单个密钥,我使用了:

  if ($sshkey) {
    ssh_authorized_key { $resourcename:
      ensure  => 'present',
      type    => 'ssh-rsa',
      key     => '$sshkey',
      user    => $title,
      require => User[$title],
    }
  }

对于多个键,我认为这可能有效:

  if ($sshkeyarray != []) {
    $sshkeyarray.each |String $singlesshkey| {
      ssh_authorized_key { $resourcename:
        ensure  => 'present',
        type    => 'ssh-rsa',
        key     => '$singlesshkey',
        user    => $title,
        require => User[$title],
      }
    }
  }

但是资源名称只能使用一次,所以我想为第一个 ssh 密钥命名为 "resourcename_1",为第 n 个密钥命名为 "resourcename_n"。

我该怎么做?我可以从数组中获取 singlesshkey 的位置并将其添加到资源名称吗?

如文档中所述here,您可以这样做:

  $sshkeyarray.each |$index, String $singlesshkey| {
    ssh_authorized_key { "${resourcename}_${index}":
      ensure  => 'present',
      type    => 'ssh-rsa',
      key     => $singlesshkey,
      user    => $title,
      require => User[$title],
    }
  }

请注意,也无需测试空数组。遍历一个空数组无论如何都不会发生任何事情。