Randomly Expressed


Welcome to my blog “randomly expressed”. I created this website to publish helpful tips. It’s mainly technology driven, but I will blog about other topics. I am a Unix sysadmin that is always looking to learn new things. My goal is to be able to share knowledge that others may find useful. xkcd.com

Continue Reading »


Connect With US

Connect with us on the following social networking sites.

Most Popular Posts.

Add Some Content to This Area

You should either deactivate this panel on the Theme Settings page, or add some content via the Widgets page in your WordPress dashboard.

Variable via shell command in Ansible

By on March 19, 2017 in Technology with 1 Comment

The ability to run shell commands and pass the output to a variable will enable you to add more logic to your playbooks. How to set a variable from the output of a shell command in your Ansible playbook? You will need to use the shell module to run your command and then use the register module to save the output of the command. In the following example I am running a shell command to get the region of an EC2 instance and then saving it to a variable named region with the register module.

  - name: Get the region from the EC2 instance
    shell: /usr/bin/ec2metadata --availability-zone | sed 's/.$//'
    register: region
    ignore_errors: True

Now you will need to know how to extract the contents of the variable in your playbook. In order to do that you will need to add .stdout to whatever you named your variable. In this example it was region so it will be called as region.stdout. The following example I am now using the region.stdout variable to set the region in my data dog playbook.

  - name: Setting region if required
    replace: dest=/etc/dd-agent/datadog.conf regexp='region:' replace={{region.stdout}} backup=yes
    when: region|succeeded

The reason I added “ignore_errors: True” when I was setting my region variable is that it will allow the playbook to continue to run in case that command doesn’t exist. Which in my environment it will allow me to run this playbook not just on AWS, but in our data center as well. Note that I also used the “when: region|succeeded” module to ensure my task named “Setting region if required” is only ran if the task named “Get the region from the EC2 instance” is successful in running the shell command. I don’t want it to run if the shell command fails.

Facebook Comments

Tagged With: , ,

1 Reader Comment

Trackback URL | Comments RSS Feed

  1. Matt says:

    I’m fairly new to ansible, and I just wanted to say that your “when | succeed” just saved me from having a mini-melt down.

    I was trying to collect information form a script, and IF that information had a host name, then only continue.

    I had everything working, except how to pars that into “when”.

Post a Comment

Your email address will not be published. Required fields are marked *