如何适配移动云 EIP 绑定 API 差异?

解读

移动云(中国移动公有云)的弹性公网 IP(EIP)绑定接口与阿里云、腾讯云等主流厂商在请求域名、鉴权方式、参数命名、幂等策略、错误码定义上均存在差异。面试官想确认候选人是否具备“把厂商差异封装成 Ansible 模块”的能力,而不仅仅是会调用 API。核心考点有三层:

  1. 能否用 Ansible 的声明式语法屏蔽差异,让 Playbook 在移动云、他云之间零改动;
  2. 能否在模块内部实现幂等性与异常重试,避免重复绑定或产生僵尸 EIP;
  3. 能否把AK/SK 鉴权、project-id、region-id等移动云特有字段做成可配置变量,满足国内政企客户“一省一资源池”的合规要求。

知识点

  1. Ansible 模块开发规范:

    • 必须继承 AnsibleModule,在 argument_spec 里声明全部 API 参数并给出默认值;
    • 使用 supports_check_mode=True 实现** dry-run**,让金融客户敢在白天跑任务;
    • 返回字段需包含 changed、diff、eip_address、bind_instance_id,方便后续做配置漂移检查。
  2. 移动云 EIP 特有差异:

    • 域名格式:eip.{region}.ecloud.10086.cn,其中 region 取值不含“cn-”前缀,如“bj”“gd”;
    • 鉴权算法:采用HMAC-SHA256签名,Header 中必须带 X-Sdk-Date 且时间戳与 UTC 相差不超过 15 min;
    • 绑定接口为 POST /v2/{project_id}/publicips/{publicip_id}/bind,请求体字段叫 instance_id 与 instance_type,而阿里云叫 InstanceId 与 `InstanceType**;
    • 幂等键:移动云使用 client-token 放在 Query 参数,相同 client-token 5 min 内只执行一次;
    • 错误码 4003 表示“EIP 已绑定”,需捕获后主动回调查询接口,把 changed 置为 False,否则 Ansible 会误判为失败。
  3. 实战技巧:

    • 用 ansible_collections.cloud.cmcc 命名空间封装,与社区版本隔离,方便后期通过 ansible-galaxy collection install 分发;
    • 在模块内部调用 ansible.module_utils.urls.fetch_url 时,关闭 Python 的 urlib3 重试,自己实现指数退避,避免移动云 WAF 把高频重试视为攻击;
    • 把 project-id、region、endpoint 做成 env_fallback,支持从**中国移动集中管控平台(ESM)**注入环境变量,满足运营商内部“一台跳板机管全国资源池”的运维场景。

答案

  1. 创建 Collection 骨架
ansible-galaxy collection init cmcc.cloud
  1. 在 plugins/modules/ 下新建 cmcc_eip.py,核心代码框架:
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
from ansible_collections.cmcc.cloud.plugins.module_utils.sign import hmac_sha256  # 自研签名函数

def get_endpoint(region):
    return f"https://eip.{region}.ecloud.10086.cn"

def run():
    module = AnsibleModule(
        argument_spec=dict(
            access_key=dict(required=True, no_log=True, fallback=(env_fallback, ['CMCC_ACCESS_KEY'])),
            secret_key=dict(required=True, no_log=True, fallback=(env_fallback, ['CMCC_SECRET_KEY'])),
            project_id=dict(required=True),
            region=dict(choices=['bj', 'sh', 'gd', 'sc'], required=True),
            publicip_id=dict(required=True),
            instance_id=dict(required=True),
            instance_type=dict(choices=['PORT', 'NAT', 'ELB'], default='PORT'),
            state=dict(choices=['present', 'absent'], default='present'),
            client_token=dict(no_log=False),  # 幂等键
        ),
        supports_check_mode=True
    )
    state = module.params['state']
    endpoint = get_endpoint(module.params['region'])
    headers = hmac_sha256(module)          # 生成移动云签名头
    if module.check_mode:
        module.exit_json(changed=False)

    # 查询当前绑定关系
    query_url = f"{endpoint}/v2/{module.params['project_id']}/publicips/{module.params['publicip_id']}"
    resp, info = fetch_url(module, query_url, headers=headers, method='GET')
    if info['status'] != 200:
        module.fail_json(msg=f"query failed: {info['body']}")
    current = json.loads(resp.read())['publicip']['port_id']  # 移动云字段叫 port_id

    target = module.params['instance_id'] if state == 'present' else None
    if current == target:
        module.exit_json(changed=False, publicip=current)

    # 执行绑定/解绑
    bind_url = f"{endpoint}/v2/{module.params['project_id']}/publicips/{module.params['publicip_id']}/bind"
    payload = {
        'instance_id': module.params['instance_id'],
        'instance_type': module.params['instance_type']
    } if state == 'present' else {}
    method = 'POST' if state == 'present' else 'DELETE'
    resp, info = fetch_url(module, bind_url, data=module.jsonify(payload),
                           headers=headers, method=method,
                           timeout=30)
    if info['status'] in (200, 204):
        module.exit_json(changed=True, publicip=module.params['publicip_id'])
    elif info['status'] == 400 and 'already bind' in info['body']:
        module.exit_json(changed=False)   # 幂等兜底
    else:
        module.fail_json(msg=f"bind failed: {info['body']}")

if __name__ == '__main__':
    run()
  1. 在 Playbook 中使用
- hosts: localhost
  tasks:
    - name: 确保 EIP 绑定到移动云 CVM
      cmcc.cloud.cmcc_eip:
        access_key: "{{ vault_cmcc_ak }}"
        secret_key: "{{ vault_cmcc_sk }}"
        project_id: "cn-bj-ops"
        region: bj
        publicip_id: "{{ eip_id }}"
        instance_id: "{{ cvm_port_id }}"
        state: present
        client_token: "{{ ansible_run_id }}"

通过上述封装,移动云 API 差异对上层 Playbook 完全透明,同一套代码可在阿里云、华为云通过条件导入不同模块实现“一份剧本,多云通用”,满足国内大型央企“混合云合规审计”的刚性需求。

拓展思考

  1. 灰度发布场景:移动云 EIP 支持按标签批量绑定,可扩展 module 参数 tags,结合 Ansible 的 loop 与 batch(10) 实现每批 10 台滚动绑定,避免一次性切换导致业务洪峰。
  2. 费用优化:移动云对未绑定 EIP收取 0.07 元/小时闲置费,可在 Playbook 最后加一道 rescue,如果绑定失败则自动释放 EIP,把成本错误控制在分钟级。
  3. 合规审计:利用 Ansible 的 callback_plugin 把每一次绑定结果写入移动云自研日志仓库(LTS),字段包含 operator_uid、client_token、region、cost_center,方便后期工信部网络安全检查时一键导出证据链。