Using Terraform with AWS SSO

Hello,

I’m trying to use Terraform with some AWS accounts that have AWS SSO enabled, but have been unsuccessful.
I can’t use the aws configure sso feature and then the profile parameter in Terraform, because I’ll not only run terraform locally, but also on Bitbucket pipelines.

Could anyone that has done this before please suggest any solutions?

Thanks!
Lucas

Hi @lpossamai1,

Do you have any existing steps in your Bitbucket pipeline that make AWS API calls? Your options for giving AWS credentials to Terraform are largely the same as for giving AWS credentials to the AWS CLI, so it might be helpful to experiment with getting some AWS CLI calls working in that environment first (using AWS CLI documentation) and then try translating what you figured out into Terraform.

If you have something working with AWS CLI already then please share what you have and then hopefully I or someone else can give some hints on how to translate that to Terraform.

Sorry, I didn’t provide much information and now I can’t edit the original post.

I have some AWS Accounts being managed by AWS Control Tower with Landing Zone. These AWS accounts have AWS SSO setup to manage users, groups and permissions.

My goal is to have Bitbucket pipeline working with Terraform. I’ve followed these steps to setup OpenID connect.

At the moment, when running the pipeline I get the following error:

Error: error configuring S3 Backend: no valid credential sources for S3 Backend found.

providers.tf file:

provider "aws" {
  region  = "ap-southeast-2"
  assume_role {
    role_arn     = "${var.workspace_iam_roles[terraform.workspace]}"
    session_name = "SESSION_NAME"
    external_id  = "EXTERNAL_ID"
  }
}

terraform {
  backend "s3" {
    bucket  = "terraform-backend-tfstate-example"
    key     = "terraform.tfstate"
    region  = "ap-southeast-2"
    role_arn   = "arn:aws:iam::XXXXXXX:role/bitbucket-pipeline-role"
  }
}

The role arn:aws:iam::XXXXXXX:role/bitbucket-pipeline-role has access to the s3 bucket terraform-backend-tfstate-example.

Locally on my laptop I can use aws configure sso to have access to the accounts. But that is not possible on Bitbucket pipelines. Specially because the access provided by this command is temporary.

Having an access_key and secret_key for the backend and then using role_arn for the provider worked for me.

terraform {
  backend "s3" {
    bucket  = "terraform-backend-tfstate-example"
    key     = "terraform.tfstate"
    region  = "ap-southeast-2"
    access_key = var.aws_access_key
    secret_key = var.aws_secret_key
  }
}

provider "aws" {
  region  = "ap-southeast-2"
  assume_role {
    role_arn     = "${var.workspace_iam_roles[terraform.workspace]}"
    session_name = "SESSION_NAME"
    external_id  = "EXTERNAL_ID"
  }
}

Wondering if that’s the right way to do it? Please, feel free to suggest/comment other ways to achieve this.

@lpossamai1 , have you solved this?