How to install R packages with Ansible
Here is a short snipet of Ansible playbook that installs R and any required packages to any nodes of the cluster:
- name: Making sure R is installed (debian/ubuntu apt)
apt: pkg=r-base state=installed
- name: adding a few R packages
command: /usr/bin/Rscript --slave --no-save --no-restore-history -e "if (! ('{{item}}' %in% installed.packages()[,'Package'])) install.packages(pkgs={{item}}, repos=c('http://www.freestatistics.org/cran/'))"
with_items:
- rjson
- rPython
- plyr
- psych
- reshape2
You should replace the repos
with one chosen from the list of Cran mirrors.
Note that the command above installs each package only if it is not already present, but messes up the “changed” status of Ansible’s PLAY RECAP by incorrectly reporting a change per R package at every run. To fix this, have a look at the improvement written by Adam Johnson here: http://adamj.eu/tech/2014/07/19/installing-and-removing-r-packages-with-ansible/
Thanks, this is awesome !
phraer
April 10, 2014 at 7:12 pm
Thanks for this info, it helped me! I extended it a bit to give a good return status that isn’t always “CHANGED” – see my blog post at http://adamj.eu/tech/2014/07/19/installing-and-removing-r-packages-with-ansible/ for code 🙂
Adam Chainz
July 19, 2014 at 7:11 pm
Great!
Svend
July 21, 2014 at 5:33 am
Thanks! I used it to make a second task to install Bioconductor packages:
– name: bioconductor packages
command: >
Rscript –slave –no-save –no-restore-history -e “source(‘http://bioconductor.org/biocLite.R’); if (! (‘{{ item }}’ %in% installed.packages()[,’Package’])) { biocLite(‘{{ item }}’); print(‘Added’); } else { print(‘Already installed’); }”
register: b_result
failed_when: “b_result.rc != 0 or ‘had non-zero exit status’ in b_result.stderr”
changed_when: “‘Added’ in b_result.stdout”
with_items:
– DESeq2
– edgeR
Jeffrey David Johnson
September 30, 2014 at 12:19 am
You can use repos=’http://cran.rstudio.com’ since this provides local redirects. Nice work!
Martin Tapp (@doctapp)
January 7, 2015 at 7:15 pm