【问题标题】:Array iteration with position in puppet木偶中具有位置的数组迭代
【发布时间】:2017-04-26 07:57:25
【问题描述】:

我计划实现为每个用户添加多个 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 的位置并将其添加到资源名称中吗?

【问题讨论】:

    标签: puppet


    【解决方案1】:

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

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

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

    【讨论】:

    • 完美,谢谢!
    • 哇,这是我以前不知道的each() 函数的细节!我今天学到了一些新东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 2014-08-22
    • 2017-01-04
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多