代码之家  ›  专栏  ›  技术社区  ›  lonix

使用Ansible管理远程生成的API密钥

  •  0
  • lonix  · 技术社区  · 2 年前

    我使用ansible来提供特定的服务,在与它交互之前,我必须首先生成一个API密钥。但我无法在我的剧本中预定义该密钥(作为秘密)-它由服务器生成,返回给我一次,并且永远不会再被公开(典型的API密钥scnenario)。

    我可以要求服务器在每次运行该剧本或剧本中的标记时生成一个新的API密钥,但这非常慢。理想情况下,我应该在本地保存该API密钥并重用它。

    我的方法是简单地将其写入用户目录中的本地文件( ~/.ansible/custom/api_key.txt )所以它有一些保护作用。这很管用,但感觉有点脏。

    ansible是否有官方/稳健的方式来处理这种情况?

    1 回复  |  直到 2 年前
        1
  •  1
  •   larsks    2 年前

    这是一个宽泛的问题。在你的剧本中,有多种处理秘密的方法; this article 描述了几个选项,并且有各种在线文章涵盖了类似的主题。

    一个简单的选项可能是将API密钥加密为GPG公钥,只有当您登录并能够提供密码短语时,私钥才可用。

    下面是一个简单(即不是特别健壮)的示例:

    - hosts: localhost
      gather_facts: false
    
      tasks:
        # Check if the file in which we cache the API key exists.
        # If not, fetch the API key from the API and store it in
        # a GPG-encrypted file.
        - when: apikey_file is not file
          block:
            # This is just a dummy task to give us a string; you would of
            # course replace this with the logic to acquire an API key.
            - name: Get key from API
              command: echo secret.key
              register: apikey
    
            # Encrypt the key using the public key for the identity
            # stored in apikey_gpg_id.
            - name: Write API key to file
              command: >-
                gpg -o "{{ apikey_file }}" -e -r "{{ apikey_gpg_id }}"
              args:
                stdin: "{{ apikey.stdout }}"
    
    - hosts: localhost
      gather_facts: false
    
      tasks:
        # Decrypt the API key file to stdout. This requires us to type in
        # the passphrase (which may be cached for some amount of time in your
        # GPG agent).
        - name: Read API key from file
          command: >-
            gpg -d "{{ apikey_file }}"
          register: apikey
    
        # Show what we got from the previous task.
        - debug:
            var: apikey.stdout
    

    这假设变量 apikey_file apikey_gpg_id 是预先定义的--我已经把它们放进去了 group_vars/all.yaml ,但它们也可以根据项目的结构在您的库存或其他地方进行定义。

    推荐文章