以下是我的剧本中负责从源代码下载和构建
ruby的部分:
vars: ruby_version: '2.0.0-p247' ruby_url: 'ftp://ftp.ruby-lang.org//pub/ruby/2.0/ruby-{{ ruby_version }}.tar.gz' tasks: - name: Ensure ruby dependencies are installed apt: pkg=$item state=installed update-cache=yes sudo: yes with_items: - build-essential - git-core - libreadline6-dev - libyaml-dev - libsqlite3-dev - sqlite3 - libgdbm-dev - libncurses5-dev - libtool - bison - libffi-dev - libdigest-hmac-perl - unzip - zlib1g - zlib1g-dev - name: Ensure the ruby source is downloaded get_url: url=$ruby_url dest=/home/vagrant/ruby-{{ ruby_version }}.tar - name: Ensure the ruby source is extracted command: tar -zxf /home/vagrant/ruby-$ruby_version.tar creates=/home/vagrant/ruby-{{ ruby_version }} - name: Ensure ruby is installed command: $item chdir=/home/vagrant/ruby-$ruby_version with_items: - ./configure - make - sudo make install@H_502_3@最后一项任务(configure make和make install)在每次配置时运行.
我可以检查ruby是否已经使用ruby -v安装了正确的版本.如何在我的剧本中定义这是运行此步骤的条件?
另外,有没有办法让这个条件成为整个任务列表,而不仅仅是最后一个?
解决方法
您可以使用register task参数将ruby -v的结果保存到变量中,然后使用when task参数有条件地执行任务.
你的例子看起来像这样:
vars: ruby_version: '2.0.0-p247' ruby_url: 'ftp://ftp.ruby-lang.org//pub/ruby/2.0/ruby-{{ ruby_version }}.tar.gz' tasks: - name: get currently installed ruby version command: ruby -v register: result ignore_errors: True - name: Ensure ruby dependencies are installed apt: pkg={{ item }} state=installed update-cache=yes sudo: yes with_items: - build-essential - git-core - libreadline6-dev - libyaml-dev - libsqlite3-dev - sqlite3 - libgdbm-dev - libncurses5-dev - libtool - bison - libffi-dev - libdigest-hmac-perl - unzip - zlib1g - zlib1g-dev when: result.rc !=0 or result.stdout.split()[1] != ruby_version - name: Ensure the ruby source is downloaded get_url: url={{ ruby_url }} dest=/home/vagrant/ruby-{{ ruby_version }}.tar when: result.rc !=0 or result.stdout.split()[1] != ruby_version - name: Ensure the ruby source is extracted command: tar -zxf /home/vagrant/ruby-{{ ruby_version }}.tar creates=/home/vagrant/ruby-{{ ruby_version }} when: result.rc !=0 or result.stdout.split()[1] != ruby_version - name: Ensure ruby is installed command: $item chdir=/home/vagrant/ruby-{{ ruby_version }} with_items: - ./configure - make - sudo make install when: result.rc !=0 or result.stdout.split()[1] != ruby_version@H_502_3@您还可以将任务移动到单独的文件(例如,install_ruby_from_source.yaml),然后有条件地包含该文件:
vars: ruby_version: '2.0.0-p247' ruby_url: 'ftp://ftp.ruby-lang.org//pub/ruby/2.0/ruby-{{ ruby_version }}.tar.gz' tasks: - name: get currently installed ruby version command: ruby -v register: result ignore_errors: True - include: /path/to/install_ruby_from_source.yaml when: result.rc !=0 or result.stdout.split()[1] != ruby_version@H_502_3@