【问题标题】:When using ansible conditionals can you tell ansible to perform an alternative action when encountering an error?当使用 ansible 条件时,你能告诉 ansible 在遇到错误时执行替代操作吗?
【发布时间】:2021-03-03 06:27:13
【问题描述】:

所以我有这个代码

- name: exectuing aws cli engine
  become: yes
  command: sh /tmp/aws/install
  register: aws_cli
- debug: msg={{ aws_cli.stdout }}

并且在执行时会由于已安装 aws cli 而产生此错误

fatal: [Jenkins_server]: FAILED! => {
    "changed": true,
    "cmd": [
        "sh",
        "/tmp/aws/install"
    ],
    "delta": "0:00:00.808705",
    "end": "2020-11-19 19:50:31.133925",
    "invocation": {
        "module_args": {
            "_raw_params": "sh /tmp/aws/install",
            "_uses_shell": false,
            "argv": null,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "stdin": null,
            "stdin_add_newline": true,
            "strip_empty_ends": true,
            "warn": true
        }
    },
    "msg": "non-zero return code",
    "rc": 1,
    "start": "2020-11-19 19:50:30.325220",
    "stderr": "Found preexisting AWS CLI installation: /usr/local/aws-cli/v2/current. Please rerun install script with --update flag.",
    "stderr_lines": [
        "Found preexisting AWS CLI installation: /usr/local/aws-cli/v2/current. Please rerun install script with --update flag."
    ],
    "stdout": "",
    "stdout_lines": []
}

这很好,但我的问题是 当 aws_cli.rc == 1

是否可以通过电话跳过跑步 这段代码

command: sh /tmp/aws/install

并改为运行更新 aws cli 命令?所以像

command: sh /tmp/aws/install --update

【问题讨论】:

    标签: amazon-web-services ansible yaml conditional-statements


    【解决方案1】:

    是的,有两种方法:ignore_errors: yes 或使用block: with rescue:

    选项 1:

    - name: exectuing aws cli engine
      become: yes
      command: sh /tmp/aws/install
      register: aws_cli
      ignore_errors: yes
    
    - name: exectuing aws cli engine, 2nd try
      when: aws_cli is failed
      become: yes
      command: sh /tmp/aws/install --update
      register: aws_cli
    

    选项 2:

    - block:
      - name: exectuing aws cli engine
        become: yes
        command: sh /tmp/aws/install
        register: aws_cli
      rescue:
      - name: exectuing aws cli engine, 2nd attempt
        become: yes
        command: sh /tmp/aws/install --upgrade
        register: aws_cli
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      相关资源
      最近更新 更多