注册Ansible变量属性

时间:2016-05-27 09:18:31

标签: ansible ansible-playbook

使用Ansible我遇到了以我想要的方式注册变量的问题。使用下面的实现,我总是要在变量上调用.stdout - 有没有办法可以做得更好?

我的剧本: 注意.stdout的不必要的使用 - 我只是希望能够直接使用变量而不需要调用属性...?

---
- name: prepare for new deployment
  hosts: all
  user: ser85

  tasks:

  - name: init deploy dir
    shell: echo ansible-deploy-$(date +%Y%m%d-%H%M%S-%N)
    # http://docs.ansible.com/ansible/playbooks_variables.html
    register: deploy_dir

  - debug: var=deploy_dir

  - debug: var=deploy_dir.stdout

  - name: init scripts dir
    shell: echo {{ deploy_dir.stdout }}/scripts
    register: scripts_dir

  - debug: var=scripts_dir.stdout

执行playbook时的输出:

TASK [init deploy dir] *********************************************************
changed: [123.123.123.123]

TASK [debug] *******************************************************************
ok: [123.123.123.123] => {
    "deploy_dir": {
        "changed": true,
        "cmd": "echo ansible-deploy-$(date +%Y%m%d-%H%M%S-%N)",
        "delta": "0:00:00.002898",
        "end": "2016-05-27 10:53:38.122217",
        "rc": 0,
        "start": "2016-05-27 10:53:38.119319",
        "stderr": "",
        "stdout": "ansible-deploy-20160527-105338-121888719",
        "stdout_lines": [
            "ansible-deploy-20160527-105338-121888719"
        ],
        "warnings": []
    }
}

TASK [debug] *******************************************************************
ok: [123.123.123.123] => {
    "deploy_dir.stdout": "ansible-deploy-20160527-105338-121888719"
}

TASK [init scripts dir] ********************************************************
changed: [123.123.123.123]

TASK [debug] *******************************************************************
ok: [123.123.123.123] => {
    "scripts_dir.stdout": "ansible-deploy-20160527-105338-121888719/scripts"
}

任何帮助或见解表示赞赏 - 谢谢:)

1 个答案:

答案 0 :(得分:7)

如果我理解正确,您希望将deploy_dir.stdout分配给不使用stdout密钥即可使用的变量。可以使用set_fact模块完成:

tasks:
  - name: init deploy dir
    shell: echo ansible-deploy-$(date +%Y%m%d-%H%M%S-%N)
    # http://docs.ansible.com/ansible/playbooks_variables.html
    register: deploy_dir

  - set_fact: my_deploy_dir="{{ deploy_dir.stdout }}"

  - debug: var=my_deploy_dir