Ansible ec2 to assume or not.

I am writing play’s using the ec2 cloud modules and would like to have the option to run the play using an assumed role or just standard IAM keys. I can use logic to let the play know if I will use IAM or a assumed role but when I skip the “Assume” task the play errors out on the unused variables in the ec2 module. Is there a way I can tell a task to ignore the variables in this task ec2_key when they are not needed, or do I have to write two play books?

Thanks
Dave

  • name: Test Assume Variables.
    hosts: localhost
    connection: local
    vars:
    arn: true
    tasks:

  • name: Assume
    sts_assume_role:
    region: us-west-2
    role_arn: “{{ arn }}”
    role_session_name: “admin”
    register: assumed_role
    when: arn != true

  • name: ec2 key
    ec2_key:
    aws_access_key: “{{ assumed_role.sts_creds.access_key }}”
    aws_secret_key: “{{ assumed_role.sts_creds.secret_key }}”
    security_token: “{{ assumed_role.sts_creds.session_token }}”
    region: us-west-2
    name: exampleKEYABC

Check out the filter default(omit)

https://docs.ansible.com/ansible/playbooks_filters.html#omitting-undefined-variables-and-parameters

if the token is null the tasks will still run.

Many thanks for your reply Kai, this only seems to work on module parameters and not bare variables.

Dave

Thanks for your Reply Steve, I did think I tested this I will have to give it another try…
Dave