IBM Cloud Docs
为可部署体系结构创建脚本

为可部署体系结构创建脚本

您可以在验证,部署和取消部署之前或之后具有针对可部署体系结构运行的脚本。 脚本配置为特定版本的可部署体系结构,并且必须通过项目运行和验证。 有关项目的更多信息,请参阅 创建项目

将脚本用于可部署体系结构有几个优点和用例:

  • 执行定制验证,例如,如果要确保 tag 参数始终是有效的成本中心标识。 预验证脚本可能会调出到服务以检查成本中心标识是否有效。
  • 跟踪部署并添加资源,例如,通过提供可调用服务的部署后脚本来向库存系统添加资源,以跟踪已部署的资源。
  • 正在完成数据迁移。 部署前脚本可以备份数据。 然后,在可部署体系结构删除旧数据存储器并创建新数据存储器之后,部署后脚本可以将其复原到新数据存储器。
  • 安装或配置软件
  • 完成第二天的维护任务,例如手动备份,复原或密钥轮换。

添加前置和后置脚本

脚本对于产品是可选的,但如果使用了这些脚本,那么它们必须位于名为 scripts 的目录中的源存储库中。 脚本文件本身必须符合以下命名约定 <action>-<stage>-ansible-playbook.yamlaction 的选项包括 deployvalidateundeploystage include prepost 的选项。

当前仅支持运行手册格式的 Ansible 脚本。

您还必须在源存储库的 ibm_catalog.json 清单文件中引用脚本。 为 scripts 数组中每个可部署体系结构变体的脚本提供必需信息:

"scripts": [
   {
      "type": "ansible",
      "short_description": "Short description of what your script is intended to do.",
      "path": "Path to script location.",
      "stage": "The stage. For example, pre.",
      "action": "The action. For example, validate."
   }
],

在加载到 IBM Cloud之前,可以将此信息添加到源存储库中的目录清单文件,也可以在控制台中的加载工作流程期间手动添加脚本。 如果在加载期间手动添加脚本,请 下载清单文件 并将其添加到源存储库以保持信息同步,以供将来版本使用。

所有脚本都必须能够多次运行而不会失败。 例如,部署前或部署后脚本必须正确运行,即使它运行多次也是如此。 部署后脚本可能会将资源添加到目录管理数据库中,如果多次运行,那么必须确保不添加重复的资源。

脚本前和脚本后示例

以下是用于在验证可部署体系结构后显示消息的预脚本示例。 预脚本将传递到可部署体系结构中的所有输入,包括用于授权部署的凭证。

- name: Validate pre playbook
  hosts: localhost
  vars:
    ibmcloud_api_key: "{{ lookup(`ansible.builtin.env`, `ibmcloud_api_key`)}}"
    cos_instance_name: "{{ lookup(`ansible.builtin.env`, `cos_instance_name`)}}"
    workspace_id: "{{ lookup(`ansible.builtin.env`, `workspace_id`)}}"
  tasks:
  - name: Print message
    ansible.builtin.debug:
      msg: "The workspace id is {{ workspace_id }}"
    when: workspace_id is defined and workspace_id != ""
  - name: Print message
    ansible.builtin.debug:
      msg: "The cos instance name is {{ cos_instance_name }}"
    when: cos_instance_name is defined
  - name: Print result
    ansible.builtin.debug:
      msg: "Received api key"
    when: ibmcloud_api_key is defined

以下是发布脚本的示例。 将后置脚本传递到可部署体系结构的输出。

- name: Deploy post playbook
  hosts: localhost
  vars:
    ibmcloud_api_key: "{{ lookup(`ansible.builtin.env`, `ibmcloud_api_key`)}}"
    git_repo_url: "{{ lookup(`ansible.builtin.env`, `git_repo_url`)}}"
  tasks:
   - name: Print result
     ansible.builtin.debug:
       msg: "Received api key"
     when: ibmcloud_api_key is defined
   - name: Print result
     ansible.builtin.debug:
       msg: "The result is: {{ git_repo_url }}"
     when: git_repo_url is defined and git_repo_url != ""